diff options
Diffstat (limited to 'tests')
242 files changed, 40894 insertions, 221 deletions
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4b346233..02b3a3e1 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,23 +1,59 @@ find_package (Qt5Test 5 REQUIRED) -# -# Compiler options -# -set (CMAKE_CXX_STANDARD 11) +add_test ( + NAME test_release_state + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-state + -P ${CMAKE_SOURCE_DIR}/tests/release/test_release_state.cmake) + +find_package (Git QUIET) +if (GIT_FOUND) + add_test ( + NAME test_release_git_archive + COMMAND ${CMAKE_COMMAND} + -D SOURCE_DIR=${CMAKE_SOURCE_DIR} + -D TEST_BINARY_DIR=${CMAKE_CURRENT_BINARY_DIR}/release-git-archive + -D GIT_EXECUTABLE=${GIT_EXECUTABLE} + -P ${CMAKE_SOURCE_DIR}/tests/release/test_git_archive.cmake) +endif () + add_compile_options ("$<$<COMPILE_LANGUAGE:Fortran>:-Wall;-Wno-conversion;-fno-second-underscore;-fno-f2c>") add_compile_options ("$<$<AND:$<COMPILE_LANGUAGE:Fortran>,$<CONFIG:Debug>>:-fbounds-check>") add_compile_options ("$<$<AND:$<COMPILE_LANGUAGE:Fortran>,$<NOT:$<CONFIG:Debug>>>:-funroll-all-loops>") add_compile_options ("$<$<AND:$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>,$<OR:$<C_COMPILER_ID:GNU>,$<C_COMPILER_ID:Clang>,$<C_COMPILER_ID:AppleClang>>>:-Wall;-Wextra>") add_compile_options ("$<$<AND:$<COMPILE_LANGUAGE:CXX>,$<CXX_COMPILER_ID:GNU>>:-Wno-pragmas>") add_compile_options ("$<$<AND:$<OR:$<C_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:GNU>>,$<NOT:$<CONFIG:Debug>>>:-fdata-sections;-ffunction-sections>") -if (${OPENMP_FOUND} OR APPLE) +if (WSJT_BUILD_FORTRAN_OPENMP) add_compile_options ("$<$<AND:$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>,$<C_COMPILER_ID:GNU>>:${OpenMP_C_FLAGS}>") endif () -# Tell CMake to run moc when necessary set (CMAKE_AUTOMOC ON) include_directories (${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR}) -add_executable (test_qt_helpers test_qt_helpers.cpp) -target_link_libraries (test_qt_helpers wsjt_qt Qt5::Test) -add_test (test_qt_helpers test_qt_helpers) +add_subdirectory (unit/audio) +add_subdirectory (unit/band_hopping) +add_subdirectory (unit/common) +add_subdirectory (unit/decoder_ipc) +add_subdirectory (unit/hrd) +add_subdirectory (unit/hash) +add_subdirectory (unit/message_filter) +add_subdirectory (unit/msk) +add_subdirectory (unit/network) +add_subdirectory (unit/qmap) +add_subdirectory (unit/jtty) +add_subdirectory (unit/jt9) +add_subdirectory (unit/jpl) +add_subdirectory (unit/logbook) +add_subdirectory (unit/map65) +add_subdirectory (unit/echo) +add_subdirectory (unit/ft8) +add_subdirectory (unit/fst4) +add_subdirectory (unit/legacy72) +add_subdirectory (unit/packjt77) +add_subdirectory (unit/q65) +add_subdirectory (unit/jt65) +add_subdirectory (unit/superfox) +add_subdirectory (unit/streaming) +add_subdirectory (unit/tci) +add_subdirectory (unit/wsprd) diff --git a/tests/fixtures/jtty/jtty_msgs.txt b/tests/fixtures/jtty/jtty_msgs.txt new file mode 100644 index 00000000..d1b1c04d --- /dev/null +++ b/tests/fixtures/jtty/jtty_msgs.txt @@ -0,0 +1,40 @@ +CQ KA1ABC CQ +WB9XYZ +WB9XYZ 599 0123 +KA1ABC 599 0456 +599 0456 +599 MA +TU KA1ABC CQ +WB9XYZ TU CQ KA1ABC CQ +TU NOW JA6DEF 599 123 + +WB9XYZ TU +WB9XYZ AGN? +WB9XYZ NR? +WB9XYZ 599 WI +WB9XYZ 599 05 MA +WB9XYZ GEORGE MA +WB9XYZ 599 GEORGE MA +CQ PJ4/KA1ABC CQ +VP2/KF2GHI +CQ KA1ABC +CQ KA1ABC FN42 +CQ DX KA1ABC +WB9XYZ KA1ABC -09 +WB9XYZ KA1ABC RR73 + +NOW IS THE TIME FOR ALL GOOD MEN TO COME TO THE AID OF THEIR PARTY. +THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG, TWICE. +0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_'=[]{}<>|:; + +CQ K7RU CQ +N6QEK/KL7 +N6QEK/KL7 599 123 +599 456 +TU K7RU CQ + +CQ N6QEK/KL7 CQ + EA7/HA3NZ +EA7/HA3NZ 599 124 + 599 457 +TU N6QEK/KL7 CQ diff --git a/tests/integration/ft8/run_tx_loopback.cmake b/tests/integration/ft8/run_tx_loopback.cmake new file mode 100644 index 00000000..52853949 --- /dev/null +++ b/tests/integration/ft8/run_tx_loopback.cmake @@ -0,0 +1,86 @@ +foreach (required_variable WSJTX WORK_DIR EXPECTED DATA_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +set (ipc_dir "${WORK_DIR}-ipc") +file (REMOVE_RECURSE "${WORK_DIR}") +file (MAKE_DIRECTORY + "${WORK_DIR}/capture/config" + "${WORK_DIR}/capture/data" + "${WORK_DIR}/capture/cache" + "${WORK_DIR}/replay/config" + "${WORK_DIR}/replay/data" + "${WORK_DIR}/replay/cache" + "${ipc_dir}/capture" + "${ipc_dir}/replay") + +set (capture "${WORK_DIR}/ft8-tx-loopback.wav") +set (capture_environment + "XDG_CONFIG_HOME=${WORK_DIR}/capture/config" + "XDG_DATA_HOME=${WORK_DIR}/capture/data" + "XDG_CACHE_HOME=${WORK_DIR}/capture/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_ft8_tx_loopback") +set (replay_environment + "XDG_CONFIG_HOME=${WORK_DIR}/replay/config" + "XDG_DATA_HOME=${WORK_DIR}/replay/data" + "XDG_CACHE_HOME=${WORK_DIR}/replay/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_ft8_tx_loopback") +if (NOT APPLE) + list (APPEND capture_environment "TMPDIR=${ipc_dir}/capture") + list (APPEND replay_environment "TMPDIR=${ipc_dir}/replay") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${capture_environment} + "${WSJTX}" + --ft8-tx-loopback-test "${capture}" + --rig-name CTEST-FT8-TX-CAPTURE + WORKING_DIRECTORY "${WORK_DIR}/capture" + RESULT_VARIABLE capture_result + OUTPUT_VARIABLE capture_stdout + ERROR_VARIABLE capture_stderr) +if (NOT capture_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X FT8 transmit capture failed with exit code ${capture_result}\n" + "stdout:\n${capture_stdout}\n" + "stderr:\n${capture_stderr}") +endif () + +if (NOT EXISTS "${capture}") + message (FATAL_ERROR "WSJT-X did not create ${capture}") +endif () +file (SIZE "${capture}" capture_size) +if (NOT capture_size EQUAL 1440044) + message (FATAL_ERROR + "WSJT-X FT8 capture must contain a 44-byte header and 720000 frames; size=${capture_size}") +endif () +file (READ "${capture}" capture_header OFFSET 0 LIMIT 44 HEX) +if (NOT capture_header MATCHES + "^5249464624f9150057415645666d7420100000000100010080bb000000770100020010006461746100f91500$") + message (FATAL_ERROR + "WSJT-X capture is not an exact 48 kHz mono signed 16-bit PCM RIFF/WAVE period: ${capture_header}") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${replay_environment} + "${WSJTX}" + --live-audio-test "${capture}" + --live-audio-expected "${EXPECTED}" + --live-audio-data-dir "${DATA_DIR}" + --rig-name CTEST-FT8-TX-REPLAY + WORKING_DIRECTORY "${WORK_DIR}/replay" + RESULT_VARIABLE replay_result + OUTPUT_VARIABLE replay_stdout + ERROR_VARIABLE replay_stderr) +if (NOT replay_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X FT8 transmit replay failed with exit code ${replay_result}\n" + "stdout:\n${replay_stdout}\n" + "stderr:\n${replay_stderr}") +endif () + +message (STATUS "WSJT-X FT8 transmit loopback smoke test passed") diff --git a/tests/integration/ft8/tx_loopback.expected.txt b/tests/integration/ft8/tx_loopback.expected.txt new file mode 100644 index 00000000..175fa871 --- /dev/null +++ b/tests/integration/ft8/tx_loopback.expected.txt @@ -0,0 +1,2 @@ +# Message identities are compared as a set; numeric metadata is informational. +000000 0 0.0 1500 ~ CQ KA1ABC FN42 diff --git a/tests/integration/jt9/compare_decoder_output.cmake b/tests/integration/jt9/compare_decoder_output.cmake new file mode 100644 index 00000000..a7d28827 --- /dev/null +++ b/tests/integration/jt9/compare_decoder_output.cmake @@ -0,0 +1,44 @@ +foreach (required_variable JT9 MODE SAMPLE EXPECTED WORK_DIR SOURCE_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +file (MAKE_DIRECTORY "${WORK_DIR}") +set (actual_file "${WORK_DIR}/actual.txt") +set (stderr_file "${WORK_DIR}/stderr.txt") + +execute_process ( + COMMAND "${JT9}" + -a "${WORK_DIR}" + -t "${WORK_DIR}" + -r "${SOURCE_DIR}" + ${MODE} + "${SAMPLE}" + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE decoder_result + OUTPUT_VARIABLE decoder_stdout + ERROR_VARIABLE decoder_stderr) + +file (WRITE "${actual_file}" "${decoder_stdout}") +file (WRITE "${stderr_file}" "${decoder_stderr}") + +if (NOT "${decoder_result}" STREQUAL "0") + message (FATAL_ERROR + "jt9 exited with ${decoder_result}\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () + +if (NOT "${decoder_stderr}" STREQUAL "") + message (FATAL_ERROR "jt9 wrote to stderr:\n${decoder_stderr}") +endif () + +file (READ "${EXPECTED}" expected_output) +if (NOT "${decoder_stdout}" STREQUAL "${expected_output}") + message (FATAL_ERROR + "jt9 output differs from ${EXPECTED}\n" + "expected:\n${expected_output}\n" + "actual:\n${decoder_stdout}\n" + "preserved output: ${actual_file}") +endif () diff --git a/tests/integration/jt9/compare_mtd_messages.cmake b/tests/integration/jt9/compare_mtd_messages.cmake new file mode 100644 index 00000000..4011dca7 --- /dev/null +++ b/tests/integration/jt9/compare_mtd_messages.cmake @@ -0,0 +1,133 @@ +foreach (required_variable JT9 SAMPLE EXPECTED WORK_DIR SOURCE_DIR MTD_WORKERS + DECODE_CYCLES FFT_THREADS) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +file (MAKE_DIRECTORY "${WORK_DIR}") + +set (input_samples "${SAMPLE}") +set (expected_completion_count 1) +if (CONSECUTIVE_PERIODS) + set (input_samples) + foreach (utc IN ITEMS 133430 133445 133500 133515) + set (period_sample "${WORK_DIR}/210703_${utc}.wav") + configure_file ("${SAMPLE}" "${period_sample}" COPYONLY) + list (APPEND input_samples "${period_sample}") + endforeach () + list (LENGTH input_samples expected_completion_count) +endif () + +set (qso_arguments) +set (qso_variables MY_CALL DX_CALL QSO_FREQUENCY QSO_PROGRESS) +set (configured_qso_variable_count 0) +foreach (qso_variable IN LISTS qso_variables) + if (DEFINED ${qso_variable} AND NOT "${${qso_variable}}" STREQUAL "") + math (EXPR configured_qso_variable_count + "${configured_qso_variable_count} + 1") + endif () +endforeach () +if (configured_qso_variable_count GREATER 0 AND + NOT configured_qso_variable_count EQUAL 4) + message (FATAL_ERROR + "MY_CALL, DX_CALL, QSO_FREQUENCY, and QSO_PROGRESS must be set together") +elseif (configured_qso_variable_count EQUAL 4) + list (APPEND qso_arguments + -c "${MY_CALL}" -x "${DX_CALL}" -f "${QSO_FREQUENCY}" -Q "${QSO_PROGRESS}") +endif () + +set (actual_file "${WORK_DIR}/actual.txt") +set (stderr_file "${WORK_DIR}/stderr.txt") +file (WRITE "${stderr_file}" "") + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env OMP_STACKSIZE=16M + "${JT9}" + -8 -M -N ${MTD_WORKERS} -d 3 -C ${DECODE_CYCLES} -E 3 -D 3 + -p 15 -m ${FFT_THREADS} -L 200 -H 3000 + -a "${WORK_DIR}" + -t "${WORK_DIR}" + -r "${SOURCE_DIR}" + ${qso_arguments} + ${input_samples} + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE decoder_result + OUTPUT_VARIABLE decoder_stdout + ERROR_FILE "${stderr_file}") + +file (WRITE "${actual_file}" "${decoder_stdout}") +file (READ "${stderr_file}" decoder_stderr) + +if (NOT "${decoder_result}" STREQUAL "0") + message (FATAL_ERROR + "jt9 MTD exited with ${decoder_result}\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () + +if (NOT "${decoder_stderr}" STREQUAL "") + message (FATAL_ERROR "jt9 MTD wrote to stderr:\n${decoder_stderr}") +endif () + +string (REGEX MATCHALL "<DecodeFinished>" completion_markers "${decoder_stdout}") +list (LENGTH completion_markers completion_count) +if (NOT completion_count EQUAL expected_completion_count) + message (FATAL_ERROR + "jt9 MTD completed ${completion_count} decode periods; " + "expected ${expected_completion_count}") +endif () + +file (READ "${EXPECTED}" expected_output) + +# OpenMP worker completion order and numeric decode metadata are not stable invariants. +function (extract_ft8_messages decoder_output output_variable) + set (required_period "${ARGV2}") + string (REPLACE "\r\n" "\n" normalized_output "${decoder_output}") + string (REPLACE "\n" ";" output_lines "${normalized_output}") + set (messages) + foreach (line IN LISTS output_lines) + if (NOT "${required_period}" STREQUAL "") + string (STRIP "${line}" stripped_line) + string (FIND "${stripped_line}" "${required_period} " period_position) + if (NOT period_position EQUAL 0) + continue () + endif () + endif () + string (FIND "${line}" "~" marker_position) + if (marker_position GREATER_EQUAL 0) + math (EXPR message_position "${marker_position} + 1") + string (SUBSTRING "${line}" ${message_position} -1 message) + string (STRIP "${message}" message) + if (NOT "${message}" STREQUAL "") + list (APPEND messages "${message}") + endif () + endif () + endforeach () + list (REMOVE_DUPLICATES messages) + list (SORT messages) + set (${output_variable} "${messages}" PARENT_SCOPE) +endfunction () + +extract_ft8_messages ("${expected_output}" expected_messages) +extract_ft8_messages ("${decoder_stdout}" actual_messages) + +if (CONSECUTIVE_PERIODS) + foreach (utc IN ITEMS 133430 133445 133500 133515) + extract_ft8_messages ("${decoder_stdout}" period_messages "${utc}") + if (NOT "${period_messages}" STREQUAL "${expected_messages}") + message (FATAL_ERROR + "jt9 MTD decoded message set differs in period ${utc}") + endif () + endforeach () +endif () + +if (NOT "${actual_messages}" STREQUAL "${expected_messages}") + string (REPLACE ";" "\n " expected_display "${expected_messages}") + string (REPLACE ";" "\n " actual_display "${actual_messages}") + message (FATAL_ERROR + "jt9 MTD decoded message set differs from ${EXPECTED}\n" + "expected:\n ${expected_display}\n" + "actual:\n ${actual_display}\n" + "preserved output: ${actual_file}") +endif () diff --git a/tests/integration/jt9/smoke_decoder_callback.cmake b/tests/integration/jt9/smoke_decoder_callback.cmake new file mode 100644 index 00000000..6a4e698f --- /dev/null +++ b/tests/integration/jt9/smoke_decoder_callback.cmake @@ -0,0 +1,47 @@ +foreach (required_variable JT9 SAMPLE EXPECTED_MESSAGE WORK_DIR SOURCE_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +file (MAKE_DIRECTORY "${WORK_DIR}") +set (actual_file "${WORK_DIR}/actual.txt") + +execute_process ( + COMMAND "${JT9}" + -a "${WORK_DIR}" + -t "${WORK_DIR}" + -r "${SOURCE_DIR}" + -8 + -d 1 + -x b + -L 1000 + -H 1400 + "${SAMPLE}" + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE decoder_result + OUTPUT_VARIABLE decoder_stdout + ERROR_VARIABLE decoder_stderr) + +file (WRITE "${actual_file}" "${decoder_stdout}") + +if (NOT "${decoder_result}" STREQUAL "0") + message (FATAL_ERROR + "jt9 exited with ${decoder_result}\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () + +if (NOT "${decoder_stderr}" STREQUAL "") + message (FATAL_ERROR "jt9 wrote to stderr:\n${decoder_stderr}") +endif () + +string (FIND "${decoder_stdout}" "${EXPECTED_MESSAGE}" message_position) +string (FIND "${decoder_stdout}" "<DecodeFinished>" completion_position) +if (message_position LESS 0 OR completion_position LESS 0) + message (FATAL_ERROR + "jt9 did not complete the expected FT8 callback path\n" + "expected message: ${EXPECTED_MESSAGE}\n" + "actual:\n${decoder_stdout}\n" + "preserved output: ${actual_file}") +endif () diff --git a/tests/integration/jt9/verify_elf_stack.cmake b/tests/integration/jt9/verify_elf_stack.cmake new file mode 100644 index 00000000..30db932b --- /dev/null +++ b/tests/integration/jt9/verify_elf_stack.cmake @@ -0,0 +1,30 @@ +foreach (required_variable READELF EXECUTABLE) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +execute_process ( + COMMAND "${READELF}" -W -l "${EXECUTABLE}" + RESULT_VARIABLE readelf_result + OUTPUT_VARIABLE readelf_stdout + ERROR_VARIABLE readelf_stderr) + +if (NOT "${readelf_result}" STREQUAL "0") + message (FATAL_ERROR + "readelf exited with ${readelf_result}\n" + "stdout:\n${readelf_stdout}\n" + "stderr:\n${readelf_stderr}") +endif () + +string (REGEX MATCH "GNU_STACK[^\r\n]*" stack_header "${readelf_stdout}") +if (NOT stack_header) + message (FATAL_ERROR "${EXECUTABLE} has no GNU_STACK program header") +endif () + +if (stack_header MATCHES "[ \t]RWE([ \t]|$)" OR + NOT stack_header MATCHES "[ \t]RW([ \t]|$)") + message (FATAL_ERROR + "${EXECUTABLE} does not have a non-executable read/write stack:\n" + "${stack_header}") +endif () diff --git a/tests/integration/jt9/verify_jt4_12000_read_extent.cmake b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake new file mode 100644 index 00000000..7011cc39 --- /dev/null +++ b/tests/integration/jt9/verify_jt4_12000_read_extent.cmake @@ -0,0 +1,67 @@ +foreach (required_variable JT9 JT4SIM WORK_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +file (MAKE_DIRECTORY "${WORK_DIR}") +execute_process ( + COMMAND "${JT4SIM}" "G3WDG OK1KIR RRR" F 1 0 0 1 99 + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE simulator_result + OUTPUT_QUIET + ERROR_VARIABLE simulator_stderr) +if (NOT "${simulator_result}" STREQUAL "0") + message (FATAL_ERROR + "jt4sim exited with ${simulator_result}\n${simulator_stderr}") +endif () + +set (full_wav "${WORK_DIR}/000000_0001.wav") +set (truncated_wav "${WORK_DIR}/000000_0001_truncated.wav") +# Keep enough samples to distinguish a complete JT4 read from premature termination. +set (truncate_script [=[ +import struct +import sys + +sample_count = 580000 +file_size = 44 + 2 * sample_count +with open(sys.argv[1], "rb") as source_file: + wav_data = bytearray(source_file.read(file_size)) +if len(wav_data) != file_size: + raise RuntimeError("generated JT4 WAV is too short") +struct.pack_into("<I", wav_data, 4, file_size - 8) +struct.pack_into("<I", wav_data, 40, 2 * sample_count) +with open(sys.argv[2], "wb") as truncated_file: + truncated_file.write(wav_data) +]=]) +execute_process ( + COMMAND python3 -c "${truncate_script}" "${full_wav}" "${truncated_wav}" + RESULT_VARIABLE truncate_result + OUTPUT_QUIET + ERROR_VARIABLE truncate_stderr) +if (NOT "${truncate_result}" STREQUAL "0") + message (FATAL_ERROR "Failed to create truncated JT4 WAV\n${truncate_stderr}") +endif () + +execute_process ( + COMMAND "${JT9}" + -a "${WORK_DIR}" + -t "${WORK_DIR}" + --jt4 -b F -f 1000 -d 3 + "${truncated_wav}" + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE decoder_result + OUTPUT_VARIABLE decoder_stdout + ERROR_VARIABLE decoder_stderr) +if (NOT "${decoder_result}" STREQUAL "0") + message (FATAL_ERROR + "jt9 exited with ${decoder_result}\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () +if (NOT "${decoder_stdout}" MATCHES "EOF on input file") + message (FATAL_ERROR + "jt9 did not read beyond the obsolete 570240-sample cutoff\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () diff --git a/tests/integration/jtty/live_audio.expected.txt b/tests/integration/jtty/live_audio.expected.txt new file mode 100644 index 00000000..7dbc5165 --- /dev/null +++ b/tests/integration/jtty/live_audio.expected.txt @@ -0,0 +1 @@ +CQ TEST DE KA1ABC LIVE AUDIO SMOKE TEST diff --git a/tests/integration/jtty/run_live_audio.cmake b/tests/integration/jtty/run_live_audio.cmake new file mode 100644 index 00000000..1dcbd7a2 --- /dev/null +++ b/tests/integration/jtty/run_live_audio.cmake @@ -0,0 +1,66 @@ +foreach (required_variable SJTTY WSJTX WORK_DIR EXPECTED) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +set (ipc_dir "${WORK_DIR}-ipc") +file (REMOVE_RECURSE "${WORK_DIR}") +file (MAKE_DIRECTORY + "${WORK_DIR}/config" + "${WORK_DIR}/data" + "${WORK_DIR}/cache" + "${ipc_dir}") + +execute_process ( + COMMAND "${SJTTY}" + "CQ TEST DE KA1ABC LIVE AUDIO SMOKE TEST" + 1500 0.25 AW 0 384 1 99 + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE generator_result + OUTPUT_VARIABLE generator_stdout + ERROR_VARIABLE generator_stderr) +if (NOT generator_result STREQUAL "0") + message (FATAL_ERROR + "sjtty failed with exit code ${generator_result}\n" + "stdout:\n${generator_stdout}\n" + "stderr:\n${generator_stderr}") +endif () + +set (fixture "${WORK_DIR}/000000_000001.wav") +if (NOT EXISTS "${fixture}") + message (FATAL_ERROR "sjtty did not create ${fixture}") +endif () +file (SIZE "${fixture}" fixture_size) +if (fixture_size LESS 45) + message (FATAL_ERROR "sjtty created a malformed ${fixture_size}-byte WAV") +endif () + +set (wsjtx_environment + "XDG_CONFIG_HOME=${WORK_DIR}/config" + "XDG_DATA_HOME=${WORK_DIR}/data" + "XDG_CACHE_HOME=${WORK_DIR}/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_live_audio_jtty") +if (NOT APPLE) + list (APPEND wsjtx_environment "TMPDIR=${ipc_dir}") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${wsjtx_environment} + "${WSJTX}" + --jtty-live-audio-test "${fixture}" + --jtty-live-audio-expected "${EXPECTED}" + --rig-name CTEST-LIVE-AUDIO-JTTY + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE wsjtx_result + OUTPUT_VARIABLE wsjtx_stdout + ERROR_VARIABLE wsjtx_stderr) +if (NOT wsjtx_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X JTTY live-audio smoke test failed with exit code ${wsjtx_result}\n" + "stdout:\n${wsjtx_stdout}\n" + "stderr:\n${wsjtx_stderr}") +endif () + +message (STATUS "WSJT-X JTTY live-audio smoke test passed") diff --git a/tests/integration/jtty/run_tx_loopback.cmake b/tests/integration/jtty/run_tx_loopback.cmake new file mode 100644 index 00000000..cb6c0494 --- /dev/null +++ b/tests/integration/jtty/run_tx_loopback.cmake @@ -0,0 +1,84 @@ +foreach (required_variable WSJTX WORK_DIR EXPECTED) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +set (ipc_dir "${WORK_DIR}-ipc") +file (REMOVE_RECURSE "${WORK_DIR}") +file (MAKE_DIRECTORY + "${WORK_DIR}/capture/config" + "${WORK_DIR}/capture/data" + "${WORK_DIR}/capture/cache" + "${WORK_DIR}/replay/config" + "${WORK_DIR}/replay/data" + "${WORK_DIR}/replay/cache" + "${ipc_dir}/capture" + "${ipc_dir}/replay") + +set (capture "${WORK_DIR}/jtty-tx-loopback.wav") +set (capture_environment + "XDG_CONFIG_HOME=${WORK_DIR}/capture/config" + "XDG_DATA_HOME=${WORK_DIR}/capture/data" + "XDG_CACHE_HOME=${WORK_DIR}/capture/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_jtty_tx_loopback") +set (replay_environment + "XDG_CONFIG_HOME=${WORK_DIR}/replay/config" + "XDG_DATA_HOME=${WORK_DIR}/replay/data" + "XDG_CACHE_HOME=${WORK_DIR}/replay/cache" + "WSJT_QMAP_SHARED_MEMORY_KEY=mem_qmap-test_wsjtx_jtty_tx_loopback") +if (NOT APPLE) + list (APPEND capture_environment "TMPDIR=${ipc_dir}/capture") + list (APPEND replay_environment "TMPDIR=${ipc_dir}/replay") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${capture_environment} + "${WSJTX}" + --jtty-tx-loopback-test "${capture}" + --rig-name CTEST-JTTY-TX-CAPTURE + WORKING_DIRECTORY "${WORK_DIR}/capture" + RESULT_VARIABLE capture_result + OUTPUT_VARIABLE capture_stdout + ERROR_VARIABLE capture_stderr) +if (NOT capture_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X JTTY transmit capture failed with exit code ${capture_result}\n" + "stdout:\n${capture_stdout}\n" + "stderr:\n${capture_stderr}") +endif () + +if (NOT EXISTS "${capture}") + message (FATAL_ERROR "WSJT-X did not create ${capture}") +endif () +file (SIZE "${capture}" capture_size) +if (capture_size LESS 45) + message (FATAL_ERROR "WSJT-X created a malformed ${capture_size}-byte WAV") +endif () +file (READ "${capture}" capture_header OFFSET 0 LIMIT 28 HEX) +if (NOT capture_header MATCHES + "^52494646........57415645666d7420100000000100010080bb0000$") + message (FATAL_ERROR + "WSJT-X capture is not a 48 kHz mono PCM RIFF/WAVE file: ${capture_header}") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E env + ${replay_environment} + "${WSJTX}" + --jtty-live-audio-test "${capture}" + --jtty-live-audio-expected "${EXPECTED}" + --rig-name CTEST-JTTY-TX-REPLAY + WORKING_DIRECTORY "${WORK_DIR}/replay" + RESULT_VARIABLE replay_result + OUTPUT_VARIABLE replay_stdout + ERROR_VARIABLE replay_stderr) +if (NOT replay_result STREQUAL "0") + message (FATAL_ERROR + "WSJT-X JTTY transmit replay failed with exit code ${replay_result}\n" + "stdout:\n${replay_stdout}\n" + "stderr:\n${replay_stderr}") +endif () + +message (STATUS "WSJT-X JTTY transmit loopback smoke test passed") diff --git a/tests/integration/jtty/tx_loopback.expected.txt b/tests/integration/jtty/tx_loopback.expected.txt new file mode 100644 index 00000000..3761f4f4 --- /dev/null +++ b/tests/integration/jtty/tx_loopback.expected.txt @@ -0,0 +1,2 @@ +WB9XYZ 599 0123 +WB9XYZ TU CQ KA1ABC CQ diff --git a/tests/integration/run-live-audio-parallel-experiment.sh b/tests/integration/run-live-audio-parallel-experiment.sh new file mode 100755 index 00000000..12079251 --- /dev/null +++ b/tests/integration/run-live-audio-parallel-experiment.sh @@ -0,0 +1,194 @@ +#!/usr/bin/env bash +# Local soak for overlapping GUI/audio smokes and non-GUI canaries. +# Not used by CI. +# +# --smoke checks the harness only (no GUI tests). Use that before a long soak. +set -u +set -o pipefail + +usage () { + cat <<'EOF' +Usage: run-live-audio-parallel-experiment.sh --build-dir DIR [options] + + --phase 1|2|3|all Default: all + --repeats-soak N Full-suite passes per soak (serial then -j3). Default: 20 + --repeats-pair N Full-suite passes per pairwise set. Default: 10 + --smoke Validate the script and ctest listing; do not run GUI tests +EOF +} + +build_dir="" +phase="all" +repeats_soak=20 +repeats_pair=10 +smoke=0 +audio_re='test_wsjtx_live_audio_ft8|test_wsjtx_live_audio_jtty|test_wsjtx_jtty_tx_loopback|test_wsjtx_ft8_tx_loopback' +gui_audio_re="test_wsjtx_startup|${audio_re}" +canary_re='test_q65_decode_pipeline|test_tci_transceiver_characterization' +experiment_re="${gui_audio_re}|${canary_re}" +experiment_tests=( + test_wsjtx_startup + test_wsjtx_live_audio_ft8 + test_wsjtx_live_audio_jtty + test_wsjtx_jtty_tx_loopback + test_wsjtx_ft8_tx_loopback + test_q65_decode_pipeline + test_tci_transceiver_characterization +) +xvfb=(xvfb-run -a -s '-screen 0 1280x1024x24') +failures=0 +ran=0 + +while [[ $# -gt 0 ]]; do + case "$1" in + --build-dir) build_dir=$2; shift 2 ;; + --phase) phase=$2; shift 2 ;; + --repeats-soak) repeats_soak=$2; shift 2 ;; + --repeats-pair) repeats_pair=$2; shift 2 ;; + --smoke) smoke=1; shift ;; + -h|--help) usage; exit 0 ;; + *) echo "unknown argument: $1" >&2; usage; exit 2 ;; + esac +done + +if [[ -z "${build_dir}" || ! -d "${build_dir}" ]]; then + echo "--build-dir must be an existing CMake build directory" >&2 + exit 2 +fi + +if ! command -v xvfb-run >/dev/null 2>&1; then + echo "xvfb-run is required" >&2 + exit 2 +fi + +if ! command -v ctest >/dev/null 2>&1; then + echo "ctest is required" >&2 + exit 2 +fi + +listed=$(ctest --test-dir "${build_dir}" -N -R "${experiment_re}" | awk '/Test #/{print $3}') +for expected in "${experiment_tests[@]}"; do + if [[ $'\n'"${listed}"$'\n' != *$'\n'"${expected}"$'\n'* ]]; then + echo "ctest did not list ${expected}:" >&2 + echo "${listed}" >&2 + exit 2 + fi +done +listed_count=$(printf '%s\n' "${listed}" | awk 'NF { count++ } END { print count + 0 }') +if [[ "${listed_count}" -ne "${#experiment_tests[@]}" ]]; then + echo "ctest listed unexpected experiment tests:" >&2 + echo "${listed}" >&2 + exit 2 +fi + +if [[ "${smoke}" -eq 1 ]]; then + echo "smoke: xvfb-run and ctest listing ok" + echo "smoke: tests:" + printf ' %s\n' "${experiment_tests[@]}" + echo "smoke: would run phase=${phase} soak=${repeats_soak} pair=${repeats_pair}" + echo "======== 3 load start/stop ========" + pids=() + for ((i = 0; i < 2; i++)); do + sleep 30 & + pids+=($!) + done + kill "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + echo "smoke: harness ok" + exit 0 +fi + +run_ctest () { + local label=$1 + shift + echo + echo "======== ${label} ========" + printf '+' + printf ' %q' "${xvfb[@]}" ctest --test-dir "${build_dir}" "$@" + echo + ran=$((ran + 1)) + if "${xvfb[@]}" ctest --test-dir "${build_dir}" "$@"; then + echo "RESULT ${label}: pass" + else + echo "RESULT ${label}: fail (exit $?)" + failures=$((failures + 1)) + fi +} + +# Repeat whole matching suites N times. Do not use --repeat-until-fail: +# one flaky FT8 case must not skip later phases or later passes. +run_suite_repeats () { + local label=$1 + local n=$2 + shift 2 + local i + for ((i = 1; i <= n; i++)); do + run_ctest "${label} pass ${i}/${n}" "$@" + done +} + +phase1 () { + run_suite_repeats "1 serial" "${repeats_soak}" \ + -R "${experiment_re}" --output-on-failure + run_suite_repeats "1 parallel -j3" "${repeats_soak}" \ + -j3 -R "${experiment_re}" --output-on-failure +} + +phase2 () { + run_suite_repeats "2 FT8 live || JTTY live" "${repeats_pair}" \ + -j2 -R 'test_wsjtx_live_audio_ft8|test_wsjtx_live_audio_jtty' \ + --output-on-failure + run_suite_repeats "2 FT8 live || JTTY TX loopback" "${repeats_pair}" \ + -j2 -R 'test_wsjtx_live_audio_ft8|test_wsjtx_jtty_tx_loopback' \ + --output-on-failure + run_suite_repeats "2 JTTY live || JTTY TX loopback" "${repeats_pair}" \ + -j2 -R 'test_wsjtx_live_audio_jtty|test_wsjtx_jtty_tx_loopback' \ + --output-on-failure + run_suite_repeats "2 FT8 TX || FT8 live" "${repeats_pair}" \ + -j3 -R 'test_wsjtx_ft8_tx_loopback|test_wsjtx_live_audio_ft8' \ + --output-on-failure + run_suite_repeats "2 FT8 TX || JTTY live" "${repeats_pair}" \ + -j3 -R 'test_wsjtx_ft8_tx_loopback|test_wsjtx_live_audio_jtty' \ + --output-on-failure + run_suite_repeats "2 FT8 TX || JTTY TX loopback" "${repeats_pair}" \ + -j3 -R 'test_wsjtx_ft8_tx_loopback|test_wsjtx_jtty_tx_loopback' \ + --output-on-failure + run_suite_repeats "2 FT8 TX || canaries" "${repeats_pair}" \ + -j3 -R "test_wsjtx_ft8_tx_loopback|${canary_re}" \ + --output-on-failure + run_suite_repeats "2 startup || audio tests -j3" "${repeats_pair}" \ + -j3 -R "${gui_audio_re}" --output-on-failure + run_suite_repeats "2 all four audio tests -j3" "${repeats_pair}" \ + -j3 -R "${audio_re}" --output-on-failure +} + +phase3 () { + echo + echo "======== 3 contended: background gzip load ========" + local pids=() + local i + for ((i = 0; i < 4; i++)); do + (while true; do dd if=/dev/zero bs=1M count=64 2>/dev/null | gzip -1 >/dev/null; done) & + pids+=($!) + done + run_suite_repeats "3 parallel -j3 under load" "${repeats_pair}" \ + -j3 -R "${experiment_re}" --output-on-failure + kill "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true +} + +case "${phase}" in + 1) phase1 ;; + 2) phase2 ;; + 3) phase3 ;; + all) phase1; phase2; phase3 ;; + *) echo "phase must be 1, 2, 3, or all" >&2; exit 2 ;; +esac + +echo +echo "======== summary ========" +echo "suites_run=${ran} suites_failed=${failures}" +if [[ "${failures}" -ne 0 ]]; then + exit 1 +fi +exit 0 diff --git a/tests/integration/wsprd/compare_wsprd_output.cmake b/tests/integration/wsprd/compare_wsprd_output.cmake new file mode 100644 index 00000000..63e37ed0 --- /dev/null +++ b/tests/integration/wsprd/compare_wsprd_output.cmake @@ -0,0 +1,41 @@ +foreach (required_variable WSPRD SAMPLE EXPECTED WORK_DIR) + if (NOT DEFINED ${required_variable} OR "${${required_variable}}" STREQUAL "") + message (FATAL_ERROR "${required_variable} is required") + endif () +endforeach () + +file (MAKE_DIRECTORY "${WORK_DIR}") +set (actual_file "${WORK_DIR}/actual.txt") +set (stderr_file "${WORK_DIR}/stderr.txt") + +execute_process ( + COMMAND "${WSPRD}" + -a "${WORK_DIR}" + "${SAMPLE}" + WORKING_DIRECTORY "${WORK_DIR}" + RESULT_VARIABLE decoder_result + OUTPUT_VARIABLE decoder_stdout + ERROR_VARIABLE decoder_stderr) + +file (WRITE "${actual_file}" "${decoder_stdout}") +file (WRITE "${stderr_file}" "${decoder_stderr}") + +if (NOT "${decoder_result}" STREQUAL "0") + message (FATAL_ERROR + "wsprd exited with ${decoder_result}\n" + "stdout:\n${decoder_stdout}\n" + "stderr:\n${decoder_stderr}") +endif () + +if (NOT "${decoder_stderr}" STREQUAL "") + message (FATAL_ERROR "wsprd wrote to stderr:\n${decoder_stderr}") +endif () + +file (READ "${EXPECTED}" expected_output) +if (NOT "${decoder_stdout}" STREQUAL "${expected_output}") + message (FATAL_ERROR + "wsprd output differs from ${EXPECTED}\n" + "expected:\n${expected_output}\n" + "actual:\n${decoder_stdout}\n" + "preserved output: ${actual_file}") +endif () diff --git a/tests/manual/pskreporter/PSKReporter.IESpec b/tests/manual/pskreporter/PSKReporter.IESpec new file mode 100644 index 00000000..8e95ffd0 --- /dev/null +++ b/tests/manual/pskreporter/PSKReporter.IESpec @@ -0,0 +1,12 @@ +senderCallsign(30351/1)<string>[65535] +receiverCallsign(30351/2)<string>[65535] +senderLocator(30351/3)<string>[65535] +receiverLocator(30351/4)<string>[65535] +frequency(30351/5)<unsigned32>[4] +sNR(30351/6)<signed8>[1] +iMD(30351/7)<signed8>[1] +decoderSoftware(30351/8)<string>[65535] +antennaInformation(30351/9)<string>[65535] +mode(30351/10)<string>[65535] +informationSource(30351/11)<signed8>[1] +persistentIdentifier(30351/12)<string>[65535] diff --git a/tests/manual/pskreporter/listener.py b/tests/manual/pskreporter/listener.py new file mode 100644 index 00000000..4cc0e29c --- /dev/null +++ b/tests/manual/pskreporter/listener.py @@ -0,0 +1,94 @@ +from __future__ import unicode_literals +import sys +import argparse +import logging +import time +import threading +import ipfix.ie +import ipfix.reader +import ipfix.message +import socketserver +import socket + +class IPFixDatagramHandler (socketserver.DatagramRequestHandler): + + def handle (self): + logging.info (f'Connection from {self.client_address}') + try: + self.server.msg_buffer.from_bytes (self.packet) + for rec in self.server.msg_buffer.namedict_iterator (): + logging.info (f't: {self.server.msg_buffer.get_export_time()}: {rec}') + except: + logging.error ('Unexpected exception:', sys.exc_info ()[0]) + + +class IPFixUdpServer (socketserver.UDPServer): + + def __init__ (self, *args, **kwargs): + + self.msg_buffer = ipfix.message.MessageBuffer () + super ().__init__ (*args, **kwargs) + +class IPFixStreamHandler (socketserver.StreamRequestHandler): + + def handle (self): + logging.info (f'Connection from {self.client_address}') + try: + msg_reader = ipfix.reader.from_stream (self.rfile) + for rec in msg_reader.namedict_iterator (): + logging.info (f't: {msg_reader.msg.get_export_time()}: {rec}') + logging.info (f'{self.client_address} closed their connection') + except ConnectionResetError: + logging.info (f'{self.client_address} connection reset') + except TimeoutError: + logging.info (f'{self.client_address} connection timed out') + except: + logging.error ('Unexpected exception:', sys.exc_info ()[0]) + + +if __name__ == "__main__": + INTERFACE, PORT = '', 4739 + + ap = argparse.ArgumentParser (description='Dump IPFIX data collected over UDP') + ap.add_argument ('-l', '--log', metavar='loglevel', default='WARNING', help='logging level') + ap.add_argument ('-s', '--spec', metavar='specfile', help='iespec file to read') + args = ap.parse_args () + + log_level = getattr (logging, args.log.upper (), None) + if not isinstance (log_level, int): + raise ValueError (f'Invalif log level: {log_level}') + logging.basicConfig ( + level=log_level + , format='[%(levelname)s] (%(threadName)-10s) %(message)s' + , + ) + + logging.info (f'Starting IPFix servers on service port: {PORT}') + + ipfix.ie.use_iana_default () + ipfix.ie.use_5103_default () + if args.spec: + ipfix.ie.use_specfile (args.spec) + + udp_server = IPFixUdpServer ((INTERFACE, PORT), IPFixDatagramHandler) + udp_thread = threading.Thread (name='UDP Server', target=udp_server.serve_forever) + + tcp_server = socketserver.TCPServer ((INTERFACE, PORT), IPFixStreamHandler) + tcp_server.allow_reuse_address = True + tcp_server.socket.setsockopt (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + tcp_thread = threading.Thread (name='TCP/IP Server', target=tcp_server.serve_forever) + + udp_thread.start () + tcp_thread.start () + + try: + while True: + time.sleep (1000) + except KeyboardInterrupt: + logging.warning ('Closing down servers') + udp_server.shutdown () + tcp_server.shutdown () + + udp_thread.join () + tcp_thread.join () + logging.info ('Servers closed') diff --git a/tests/manual/pskreporter/python-ipfix.patch b/tests/manual/pskreporter/python-ipfix.patch new file mode 100644 index 00000000..cb679709 --- /dev/null +++ b/tests/manual/pskreporter/python-ipfix.patch @@ -0,0 +1,64 @@ +The following changes since commit e487dfbead9965c1a251d110dc55039a7ba4afef: + + sphinx doc update (2017-09-20 16:07:22 +0200) + +are available in the Git repository at: + + git@github.com:g4wjs/python-ipfix.git varlen-and-padding + +for you to fetch changes up to 6dcc106f22d25ac21b27f8ccb9b82be12e7eb18e: + + Parse and emit data elements correctly when variable length items included (2020-06-19 19:53:33 +0100) + +---------------------------------------------------------------- +Bill Somerville (2): + Allow for alignment padding when parsing sets + Parse and emit data elements correctly when variable length items included + + ipfix/message.py | 3 ++- + ipfix/template.py | 4 ++-- + 2 files changed, 4 insertions(+), 3 deletions(-) + +diff --git a/ipfix/message.py b/ipfix/message.py +index 0af2fad..71c1328 100644 +--- a/ipfix/message.py ++++ b/ipfix/message.py +@@ -398,7 +398,7 @@ class MessageBuffer(object): + offset += _sethdr_st.size # skip set header in decode + if setid == template.TEMPLATE_SET_ID or\ + setid == template.OPTIONS_SET_ID: +- while offset < setend: ++ while offset + 4 < setend: # allow for padding up to 4 byte alignment + (tmpl, offset) = template.decode_template_from( + self.mbuf, offset, setid) + # FIXME handle withdrawal +@@ -431,6 +431,7 @@ class MessageBuffer(object): + # KeyError on template lookup - unknown data set + self.unknown_data_set_hook(self, + self.mbuf[offset-_sethdr_st.size:setend]) ++ offset = setend # real end may be greater that accumulated offset + + def namedict_iterator(self): + """ +diff --git a/ipfix/template.py b/ipfix/template.py +index 1203e55..26cd8c1 100644 +--- a/ipfix/template.py ++++ b/ipfix/template.py +@@ -187,7 +187,7 @@ class Template(object): + offset += packplan.st.size + + # short circuit on no varlen +- if not self.varlenslice: ++ if self.varlenslice is None: + return (vals, offset) + + # direct iteration over remaining IEs +@@ -239,7 +239,7 @@ class Template(object): + offset += packplan.st.size + + # shortcircuit no varlen +- if not self.varlenslice: ++ if self.varlenslice is None: + return offset + + # direct iteration over remaining IEs diff --git a/tests/release/test_git_archive.cmake b/tests/release/test_git_archive.cmake new file mode 100644 index 00000000..96cf78bc --- /dev/null +++ b/tests/release/test_git_archive.cmake @@ -0,0 +1,84 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR OR NOT TEST_BINARY_DIR OR NOT GIT_EXECUTABLE) + message (FATAL_ERROR "SOURCE_DIR, TEST_BINARY_DIR, and GIT_EXECUTABLE are required") +endif () + +set (archive "${TEST_BINARY_DIR}/source.tar") +set (extract_dir "${TEST_BINARY_DIR}/archive-source") +file (REMOVE_RECURSE "${extract_dir}") +file (MAKE_DIRECTORY "${extract_dir}") +# Job containers may see the runner-mounted checkout as owned by another user. +set (git_source_args -c "safe.directory=${SOURCE_DIR}" -C "${SOURCE_DIR}") +execute_process ( + COMMAND "${GIT_EXECUTABLE}" ${git_source_args} rev-parse HEAD + RESULT_VARIABLE revision_result + OUTPUT_VARIABLE revision + OUTPUT_STRIP_TRAILING_WHITESPACE) +execute_process ( + COMMAND "${GIT_EXECUTABLE}" ${git_source_args} archive --format=tar --output=${archive} HEAD + RESULT_VARIABLE archive_result) +execute_process ( + COMMAND "${CMAKE_COMMAND}" -E tar xf "${archive}" + WORKING_DIRECTORY "${extract_dir}" + RESULT_VARIABLE extract_result) +if (NOT revision_result EQUAL 0 OR NOT archive_result EQUAL 0 OR NOT extract_result EQUAL 0) + message (FATAL_ERROR "Could not create and extract the Git source archive") +endif () + +execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D SOURCE_DIR=${extract_dir} + -D TEST_BINARY_DIR=${TEST_BINARY_DIR}/archive-fixtures + -D EXPECT_ARCHIVE_REVISION=${revision} + -P ${extract_dir}/tests/release/test_release_state.cmake + RESULT_VARIABLE state_result) +if (NOT state_result EQUAL 0) + message (FATAL_ERROR "Extracted Git archive did not preserve release identity") +endif () + +include ("${extract_dir}/CMake/Modules/read_release_state.cmake") +wsjt_read_release_state ( + "${extract_dir}/release-state.txt" + archive_version archive_channel archive_rc archive_revision) +include ("${extract_dir}/CMake/Modules/set_build_type.cmake") +set (PROJECT_NAME wsjtx) +string (REPLACE "." ";" archive_version_parts "${archive_version}") +list (GET archive_version_parts 0 PROJECT_VERSION_MAJOR) +list (GET archive_version_parts 1 PROJECT_VERSION_MINOR) +list (GET archive_version_parts 2 PROJECT_VERSION_PATCH) +set (WSJT_RELEASE_CHANNEL "${archive_channel}" CACHE STRING "" FORCE) +set (WSJT_RC_NUMBER "${archive_rc}" CACHE STRING "" FORCE) +set_build_type () +if (archive_channel STREQUAL "DEVEL") + set (expected_version "${archive_version}-devel") +elseif (archive_channel STREQUAL "RC") + set (expected_version "${archive_version}-rc${archive_rc}") +else () + set (expected_version "${archive_version}") +endif () +set (actual_version + "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}${BUILD_TYPE_REVISION}") +if (NOT actual_version STREQUAL expected_version) + message (FATAL_ERROR + "Archived source produced version '${actual_version}', expected '${expected_version}'") +endif () + +set (version_output_dir "${TEST_BINARY_DIR}/archive-version") +file (MAKE_DIRECTORY "${version_output_dir}") +execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D SOURCE_DIR=${extract_dir} + -D BINARY_DIR=${version_output_dir} + -D OUTPUT_DIR=${version_output_dir} + -D SOURCE_REVISION=${archive_revision} + -P ${extract_dir}/CMake/getsvn.cmake + RESULT_VARIABLE version_result) +if (NOT version_result EQUAL 0) + message (FATAL_ERROR "Could not generate revision header from archived source") +endif () +string (SUBSTRING "${archive_revision}" 0 6 short_revision) +file (READ "${version_output_dir}/scs_version.h" revision_header) +if (NOT revision_header MATCHES "#define SCS_VERSION_STR \"${short_revision}\"") + message (FATAL_ERROR "Archived source revision was not written to scs_version.h") +endif () diff --git a/tests/release/test_release_state.cmake b/tests/release/test_release_state.cmake new file mode 100644 index 00000000..047669fe --- /dev/null +++ b/tests/release/test_release_state.cmake @@ -0,0 +1,123 @@ +cmake_minimum_required (VERSION 3.12) + +if (NOT SOURCE_DIR) + message (FATAL_ERROR "SOURCE_DIR is required") +endif () + +include ("${SOURCE_DIR}/CMake/Modules/read_release_state.cmake") + +function (assert_equal actual expected description) + if (NOT "${actual}" STREQUAL "${expected}") + message (FATAL_ERROR "${description}: expected '${expected}', got '${actual}'") + endif () +endfunction () + +function (expect_invalid name contents) + set (_fixture "${_fixture_dir}/${name}.txt") + file (WRITE "${_fixture}" "${contents}") + execute_process ( + COMMAND "${CMAKE_COMMAND}" + -D RELEASE_STATE_READER=${SOURCE_DIR}/CMake/Modules/read_release_state.cmake + -D RELEASE_STATE_FILE=${_fixture} + -P ${SOURCE_DIR}/tests/release/validate_release_state_fixture.cmake + RESULT_VARIABLE invalid_result + OUTPUT_QUIET + ERROR_QUIET) + if (invalid_result EQUAL 0) + message (FATAL_ERROR "Invalid release state was accepted: ${name}") + endif () +endfunction () + +wsjt_read_release_state ( + "${SOURCE_DIR}/release-state.txt" + version channel rc revision) + +if (EXPECT_ARCHIVE_REVISION) + assert_equal ("${revision}" "${EXPECT_ARCHIVE_REVISION}" "archive revision") +else () + assert_equal ("${revision}" "" "working-tree archive placeholder") +endif () + +if (TEST_BINARY_DIR) + set (_fixture_dir "${TEST_BINARY_DIR}") +else () + set (_fixture_dir "${CMAKE_CURRENT_BINARY_DIR}/release-state-test") +endif () +file (MAKE_DIRECTORY "${_fixture_dir}") +file (WRITE "${_fixture_dir}/rc.txt" + "version=3.2.0\nchannel=RC\nrc=7\nrevision=0123456789abcdef0123456789abcdef01234567\n") +wsjt_read_release_state ( + "${_fixture_dir}/rc.txt" + version channel rc revision) +assert_equal ("${channel}" "RC" "RC channel") +assert_equal ("${rc}" "7" "RC number") +assert_equal ("${revision}" "0123456789abcdef0123456789abcdef01234567" "expanded revision") + +file (WRITE "${_fixture_dir}/unsigned.txt" + "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n") +wsjt_read_release_state ( + "${_fixture_dir}/unsigned.txt" + version channel rc revision) +assert_equal ("${channel}" "RC" "unsigned release channel") +assert_equal ("${rc}" "1" "unsigned release number") + +file (WRITE "${_fixture_dir}/ga.txt" + "version=3.2.0\nchannel=GA\nrc=\nrevision=$Format:%H$\n") +wsjt_read_release_state ( + "${_fixture_dir}/ga.txt" + version channel rc revision) +assert_equal ("${channel}" "GA" "GA channel") +assert_equal ("${rc}" "" "GA RC number") + +expect_invalid (ga_with_rc + "version=3.2.0\nchannel=GA\nrc=1\nrevision=$Format:%H$\n") +expect_invalid (rc_without_number + "version=3.2.0\nchannel=RC\nrc=\nrevision=$Format:%H$\n") +expect_invalid (invalid_version + "version=3.2\nchannel=DEVEL\nrc=\nrevision=$Format:%H$\n") +expect_invalid (invalid_revision + "version=3.2.0\nchannel=DEVEL\nrc=\nrevision=not-a-git-object-id\n") +expect_invalid (unknown_key + "version=3.2.0\nchannel=DEVEL\nrc=\ncommit=$Format:%H$\n") +expect_invalid (invalid_windows_signing + "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=ephemeral\n") +expect_invalid (duplicate_windows_signing + "version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\nwindows_signing=unsigned\n") + +set (_cache_source "${_fixture_dir}/cache-source") +set (_cache_build "${_fixture_dir}/cache-build") +file (MAKE_DIRECTORY "${_cache_source}") +file (WRITE "${_cache_source}/CMakeLists.txt" + "cmake_minimum_required(VERSION 3.12)\n" + "project(release_cache NONE)\n" + "include(\"${SOURCE_DIR}/CMake/Modules/read_release_state.cmake\")\n" + "wsjt_read_release_state(\"${_cache_source}/state.txt\" version channel rc revision)\n" + "wsjt_set_source_default_cache(WSJT_RELEASE_CHANNEL \"\${channel}\" \"channel\")\n" + "wsjt_set_source_default_cache(WSJT_RC_NUMBER \"\${rc}\" \"rc\")\n" + "file(WRITE \"\${CMAKE_BINARY_DIR}/result.txt\" \"\${WSJT_RELEASE_CHANNEL}:\${WSJT_RC_NUMBER}\")\n") +file (WRITE "${_cache_source}/state.txt" + "version=3.2.0\nchannel=DEVEL\nrc=\nrevision=$Format:%H$\n") +execute_process ( + COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_cache_build}" + RESULT_VARIABLE cache_result OUTPUT_QUIET ERROR_QUIET) +if (NOT cache_result EQUAL 0) + message (FATAL_ERROR "Initial release cache configure failed") +endif () +file (WRITE "${_cache_source}/state.txt" + "version=3.2.0\nchannel=RC\nrc=2\nrevision=$Format:%H$\n") +execute_process ( + COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_cache_build}" + RESULT_VARIABLE cache_result OUTPUT_QUIET ERROR_QUIET) +file (READ "${_cache_build}/result.txt" cache_result_value) +assert_equal ("${cache_result_value}" "RC:2" "tracked metadata refresh") + +set (_override_build "${_fixture_dir}/override-build") +execute_process ( + COMMAND "${CMAKE_COMMAND}" -S "${_cache_source}" -B "${_override_build}" + -D WSJT_RELEASE_CHANNEL=GA -D WSJT_RC_NUMBER= + RESULT_VARIABLE override_result OUTPUT_QUIET ERROR_QUIET) +if (NOT override_result EQUAL 0) + message (FATAL_ERROR "Explicit release cache override configure failed") +endif () +file (READ "${_override_build}/result.txt" override_result_value) +assert_equal ("${override_result_value}" "GA:" "explicit cache override") diff --git a/tests/release/validate_release_state_fixture.cmake b/tests/release/validate_release_state_fixture.cmake new file mode 100644 index 00000000..6218e55b --- /dev/null +++ b/tests/release/validate_release_state_fixture.cmake @@ -0,0 +1,6 @@ +cmake_minimum_required (VERSION 3.12) + +include ("${RELEASE_STATE_READER}") +wsjt_read_release_state ( + "${RELEASE_STATE_FILE}" + version channel rc revision) diff --git a/tests/sanitizers/tsan-fortran.supp b/tests/sanitizers/tsan-fortran.supp new file mode 100644 index 00000000..1c020cf2 --- /dev/null +++ b/tests/sanitizers/tsan-fortran.supp @@ -0,0 +1,7 @@ +# ThreadSanitizer suppressions for tests linked with the common Fortran +# runtime. +# +# libgfortran's I/O-unit lock ordering is a classified third-party false +# positive in deterministic Fortran tests. Keep this scope on tests that +# exercise that runtime path. Tracked as WSJT-X#292. +deadlock:libgfortran.so diff --git a/tests/sanitizers/tsan-gui.supp b/tests/sanitizers/tsan-gui.supp new file mode 100644 index 00000000..40aaa34b --- /dev/null +++ b/tests/sanitizers/tsan-gui.supp @@ -0,0 +1,56 @@ +# ThreadSanitizer suppressions for GUI, Qt-multimedia, and live-audio tests. +# +# These reports are dependency-internal startup, bearer, and event-loop +# reports observed with the Arch Qt/GLib/GIO/DBus stack. Keep the scope on +# GUI integration and JTTY multimedia tests so ordinary unit tests retain the +# baseline signal. +# CMake combines this file with tsan.supp before assigning TSAN_OPTIONS. + +# GLib/GIO gdbus cleanup and socket races. +race:g_main_context_unref +race:g_source_dup_context +race:g_hash_table_unref +race:g_str_equal +race:g_queue_pop_head +race:g_socket_send_message_with_timeout +race:g_bytes_unref +race:g_queue_foreach +race:g_slice_free_chain_with_offset +race:g_dbus_connection_signal_subscribe +race:g_dbus_message_set_num_unix_fds +race:g_dbus_connection_call_with_unix_fd_list_sync +race:g_dbus_proxy_new_for_bus_sync + +# Qt event-loop and network-bearer startup/teardown races. +race:QArrayData::allocate +race:QCoreApplication::event +race:QCoreApplication::removePostedEvents +race:QCoreApplicationPrivate::sendPostedEvents +race:QCoreApplication::postEvent +race:QWaitCondition::wakeAll +race:QWaitCondition::~QWaitCondition +race:QObjectPrivate::Connection::~Connection +race:QObjectPrivate::ConnectionData::deleteOrphaned +race:QThreadPoolPrivate::reset +race:QMetaType::destroy +race:QMetaCallEvent::~QMetaCallEvent +race:QMetaObjectBuilder::relatedMetaObjectCount +race:QMetaType::unregisterConverterFunction +race:dbus_connection_get_is_connected + +# Qt/DBus lock-order in the uninstrumented system library. +deadlock:libdbus-1.so + +# The JTTY live-audio harness also launches sjtty. Its only report is the +# same classified libgfortran I/O-unit lock ordering as the Fortran tests. +deadlock:libgfortran.so + +# Additional DBus internals reported by the Arch DBus build. +race:_dbus_message_loader_get_buffer +race:_dbus_user_database_unlock_system +race:_dbus_string_init_const +race:dbus_connection_preallocate_send +race:dbus_bus_register +race:dbus_connection_remove_filter +race:dbus_connection_close +race:g_variant_builder_add_parsed diff --git a/tests/sanitizers/tsan-network.supp b/tests/sanitizers/tsan-network.supp new file mode 100644 index 00000000..e201547c --- /dev/null +++ b/tests/sanitizers/tsan-network.supp @@ -0,0 +1,48 @@ +# ThreadSanitizer suppressions for the network unit-test family. +# +# These reports were observed with Qt 5.15's network bearer and the Arch +# GLib/GIO stack. The conflicting accesses remain inside the dependencies; +# application and test frames only initiate or exercise the network paths. +# Keep this file scoped to the tests that exercise those paths. CMake +# combines it with tsan.supp before assigning TSAN_OPTIONS. + +# GLib/GIO gdbus cleanup and socket races. +race:g_main_context_unref +race:g_source_dup_context +race:g_hash_table_unref +race:g_str_equal +race:g_queue_pop_head +race:g_socket_send_message_with_timeout +race:g_bytes_unref +race:g_queue_foreach +race:g_slice_free_chain_with_offset +race:g_dbus_connection_signal_subscribe +race:g_dbus_message_set_num_unix_fds +race:g_dbus_connection_call_with_unix_fd_list_sync +race:g_dbus_proxy_new_for_bus_sync + +# Qt 5.15 network bearer startup and teardown races. +race:QArrayData::allocate +race:QCoreApplication::event +race:QCoreApplication::removePostedEvents +race:QCoreApplicationPrivate::sendPostedEvents +race:QCoreApplication::postEvent +race:QWaitCondition::wakeAll +race:QWaitCondition::~QWaitCondition +race:QObjectPrivate::Connection::~Connection +race:QObjectPrivate::ConnectionData::deleteOrphaned +race:QMetaObjectBuilder::relatedMetaObjectCount +race:QMetaType::unregisterConverterFunction +race:dbus_connection_get_is_connected + +# Qt/DBus lock-order in the uninstrumented system library. +deadlock:libdbus-1.so + +# Additional DBus internals reported by the Arch DBus build. +race:_dbus_message_loader_get_buffer +race:_dbus_user_database_unlock_system +race:_dbus_string_init_const +race:dbus_connection_preallocate_send +race:dbus_bus_register +race:dbus_connection_remove_filter +race:dbus_connection_close diff --git a/tests/sanitizers/tsan.supp b/tests/sanitizers/tsan.supp new file mode 100644 index 00000000..83014c77 --- /dev/null +++ b/tests/sanitizers/tsan.supp @@ -0,0 +1,57 @@ +# ThreadSanitizer suppressions for cross-cutting classified third-party reports. +# +# Hamlib is statically linked in the TSan prefix, so called_from_lib +# cannot be used for it. Match the SUMMARY functions from the +# classified 4.7.2 reports instead. +# +# Local runs should use an absolute path: +# TSAN_OPTIONS=halt_on_error=0:second_deadlock_stack=1:suppressions=/abs/path/tests/sanitizers/tsan.supp +# +# Do not suppress MainWindow::decode, Detector::writeData, or other +# in-tree frames. Those remain the advisory TSan signal. + +# Hamlib 4.7.2 cache and routing races. +# Upstream: Hamlib#2146. Remove after the WSJT-X Hamlib pin includes it. +race:rig_set_cache_freq +race:rig_set_cache_mode +race:rig_get_freq +race:rig_get_vfo +race:rig_poll_routine_stop + +# Hamlib 4.7.x debug-buffer race during rig_open. +# Match only the known shared buffer; retain visibility for other rig_open races. +race:debugmsgsave2 + +# Hamlib 4.7 Morse worker stop-flag race. +# Upstream: Hamlib#2109 / backport Hamlib#2126. Remove after that release. +race:morse_data_handler_stop + +# Boost.Log 1.83 publishes asynchronous queue nodes with relaxed atomics; +# the Arch investigation used Boost.Log 1.92.0. Function names and report +# coverage may change between Boost releases, so revalidate after upgrades. +# These reports leave TSan without a producer/consumer happens-before edge for +# the record payload. Match the queue operations and resulting attribute +# detachment reports without suppressing application logging frames. +race:boost::log::v2_mt_posix::aux::threadsafe_queue +race:boost::log::v2_mt_posix::attribute_value::detach_from_thread + +# Additional Boost.Log asynchronous record and attribute lifetime reports. +# These match the reported Boost.Log classes/functions without suppressing +# WSJT-X logging call sites or the entire Boost library. +race:boost::log::v2_mt_posix::attributes::attribute_value_impl +race:boost::log::v2_mt_posix::attribute_value::dispatch +race:boost::log::v2_mt_posix::attribute_value::impl +race:boost::log::v2_mt_posix::attribute_value_set::~attribute_value_set +race:boost::log::v2_mt_posix::record_view::public_data::destroy +race:boost::log::v2_mt_posix::intrusive_ptr_release + +# Additional Boost 1.92 formatting and attribute lifetime frames from the +# asynchronous logging path. Keep these tied to the reported Boost types; +# do not suppress generic std::string or unsymbolized Boost frames. +race:boost::intrusive_ptr<boost::log::v2_mt_posix::attribute_value::impl>::operator bool +race:boost::date_time::int_adapter<long>::as_number +race:boost::date_time::int_adapter<long>::is_nan + +# Dependency suppressions that only apply to Fortran-backed, network, or GUI tests +# live in tsan-fortran.supp, tsan-network.supp, and tsan-gui.supp. CMake +# combines each scope file with this baseline before assigning TSAN_OPTIONS. diff --git a/tests/test_qt_helpers.cpp b/tests/test_qt_helpers.cpp deleted file mode 100644 index 195c16e0..00000000 --- a/tests/test_qt_helpers.cpp +++ /dev/null @@ -1,212 +0,0 @@ -#include <QtTest> -#include <QDateTime> -#include <QDebug> - -#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 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); - } -}; - -QTEST_MAIN (TestQtHelpers); - -#include "test_qt_helpers.moc" diff --git a/tests/unit/audio/CMakeLists.txt b/tests/unit/audio/CMakeLists.txt new file mode 100644 index 00000000..a279a713 --- /dev/null +++ b/tests/unit/audio/CMakeLists.txt @@ -0,0 +1,134 @@ +add_executable (test_bwf_file test_bwf_file.cpp) +target_link_libraries (test_bwf_file wsjt_qtmm wsjt_qt Qt5::Test Qt5::Multimedia) +add_test (NAME test_bwf_file COMMAND test_bwf_file) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_bwf_file PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +endif () + +if (WSJT_BUILD_UTILS) + add_executable (test_echosim_wav_trailer test_echosim_wav_trailer.cpp) + target_link_libraries (test_echosim_wav_trailer wsjt_qtmm Qt5::Test Qt5::Multimedia) + target_compile_definitions (test_echosim_wav_trailer PRIVATE + ECHOSIM_EXECUTABLE="$<TARGET_FILE:echosim>") + add_dependencies (test_echosim_wav_trailer echosim) + add_test (NAME test_echosim_wav_trailer COMMAND test_echosim_wav_trailer) +endif () + +add_executable (test_wav_input_loading + test_wav_input_loading.cpp + ${CMAKE_SOURCE_DIR}/Audio/WavInputLoader.cpp) +target_link_libraries (test_wav_input_loading + wsjt_qtmm wsjt_qt wsjt_fort_common Qt5::Test Qt5::Multimedia) +add_test (NAME test_wav_input_loading COMMAND test_wav_input_loading) + +add_executable (test_wav_load_coordinator + test_wav_load_coordinator.cpp + ${CMAKE_SOURCE_DIR}/Audio/WavLoadCoordinator.cpp) +target_link_libraries (test_wav_load_coordinator wsjt_qt Qt5::Test) +add_test (NAME test_wav_load_coordinator COMMAND test_wav_load_coordinator) +set_tests_properties (test_wav_load_coordinator PROPERTIES TIMEOUT 15) + +add_executable (test_tx_playback_diagnostics + test_tx_playback_diagnostics.cpp + ${CMAKE_SOURCE_DIR}/Audio/TxPlaybackDiagnostics.cpp) +target_link_libraries (test_tx_playback_diagnostics Qt5::Core Qt5::Test) +add_test (NAME test_tx_playback_diagnostics COMMAND test_tx_playback_diagnostics) + +add_executable (test_tx_request test_tx_request.cpp) +target_link_libraries (test_tx_request Qt5::Test) +add_test (NAME test_tx_request COMMAND test_tx_request) + +add_executable (test_tx_audio_queue + test_tx_audio_queue.cpp + ${CMAKE_SOURCE_DIR}/Audio/TxAudioQueue.cpp + ${CMAKE_SOURCE_DIR}/Modulator/JttyPcmFifo.cpp) +target_link_libraries (test_tx_audio_queue Qt5::Core Qt5::Test) +add_test (NAME test_tx_audio_queue COMMAND test_tx_audio_queue) + +add_executable (test_audio_input_stream_descriptor + test_audio_input_stream_descriptor.cpp + ${CMAKE_SOURCE_DIR}/Audio/AudioDevice.cpp + ${CMAKE_SOURCE_DIR}/Audio/AudioInputSource.hpp + ${CMAKE_SOURCE_DIR}/Audio/FixtureAudioInput.cpp + ${CMAKE_SOURCE_DIR}/DecDataMutex.cpp + ${CMAKE_SOURCE_DIR}/Detector/Detector.cpp) +target_link_libraries (test_audio_input_stream_descriptor + wsjt_qtmm Qt5::Core Qt5::Test Qt5::Multimedia) +add_test (NAME test_audio_input_stream_descriptor + COMMAND test_audio_input_stream_descriptor) + +add_executable (test_receive_audio_handoff + test_receive_audio_handoff.cpp + receive_reference_probe.f90 + ${CMAKE_SOURCE_DIR}/Audio/AudioDevice.cpp + ${CMAKE_SOURCE_DIR}/DecDataMutex.cpp + ${CMAKE_SOURCE_DIR}/Detector/Detector.cpp) +target_link_libraries (test_receive_audio_handoff + wsjt_fort_common Qt5::Core Qt5::Test Qt5::Multimedia) +target_include_directories (test_receive_audio_handoff PRIVATE ${CMAKE_BINARY_DIR}) +set (receive_handoff_scenarios + downsamplersRetainIndependentHistory + producersRemainIsolatedAcrossSourceSwitch + queued_prefix_without_reuse + handoff_rejects_gaps_and_disk_stale_work + queued_period_must_retain_identity + reference_input_packetization + echo_metadata_vs_append + echo_metadata_vs_reset + stale_echo_metadata_must_not_modify_next_period) +add_test (NAME test_receive_audio_handoff + COMMAND test_receive_audio_handoff ${receive_handoff_scenarios}) + +# refspectrum has saved accumulation state, so keep DSP cases in fresh +# processes. +set (receive_handoff_isolated_scenarios + reference_measurement_vs_append + reference_measurement_vs_reset + reference_application_preserves_uncommitted_suffix + reference_application_packetization + reference_measurement_packetization) +set (receive_handoff_tests test_receive_audio_handoff) +foreach (scenario IN LISTS receive_handoff_isolated_scenarios) + add_test (NAME test_receive_${scenario} + COMMAND test_receive_audio_handoff ${scenario}) + list (APPEND receive_handoff_tests test_receive_${scenario}) +endforeach () +set_tests_properties (${receive_handoff_tests} PROPERTIES + TIMEOUT 30 LABELS "receive-handoff") +if (WSJT_ENABLE_TSAN) + # Do not inherit GUI event-dispatch suppressions: they can hide the very + # application callback accesses that these tests are intended to expose. + set_tests_properties (${receive_handoff_tests} PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") + # Reference file I/O triggers a libgfortran-internal lock-order warning. + set_tests_properties ( + test_receive_reference_application_preserves_uncommitted_suffix + test_receive_reference_application_packetization + test_receive_reference_measurement_packetization PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66:detect_deadlocks=0") +endif () + +add_executable (test_fast_decode_ownership + test_fast_decode_ownership.cpp + ${CMAKE_SOURCE_DIR}/FastDecode.cpp + ${CMAKE_SOURCE_DIR}/Audio/AudioDevice.cpp + ${CMAKE_SOURCE_DIR}/DecDataMutex.cpp + ${CMAKE_SOURCE_DIR}/Detector/Detector.cpp) +target_link_libraries (test_fast_decode_ownership + wsjt_fort_common Qt5::Core Qt5::Test Qt5::Multimedia) +target_include_directories (test_fast_decode_ownership PRIVATE ${CMAKE_BINARY_DIR}) +add_test (NAME test_fast_decode_ownership COMMAND test_fast_decode_ownership + captures_submission_inputs capture_does_not_race_live_append + overlapping_jobs_retain_submission_identity) +set_tests_properties (test_fast_decode_ownership PROPERTIES + TIMEOUT 30 LABELS "receive-handoff;fast-decode-ownership") +if (WSJT_ENABLE_TSAN) + add_test (NAME test_fast_decode_overlap_does_not_race_decoder + COMMAND test_fast_decode_ownership + overlapping_submission_does_not_race_decoder) + set_tests_properties (test_fast_decode_ownership + test_fast_decode_overlap_does_not_race_decoder PROPERTIES + TIMEOUT 30 LABELS "receive-handoff;fast-decode-ownership" + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/audio/receive_reference_probe.f90 b/tests/unit/audio/receive_reference_probe.f90 new file mode 100644 index 00000000..71c43acd --- /dev/null +++ b/tests/unit/audio/receive_reference_probe.f90 @@ -0,0 +1,43 @@ +! Keep the production reference-spectrum implementation in this test. This +! bridge only supplies its flags and the compiler-specific CHARACTER argument. +subroutine receive_reference_probe(id2,ninput) bind(C) + use iso_c_binding, only: c_int16_t,c_int + implicit none + integer(c_int16_t) :: id2(*) + integer(c_int), value :: ninput + logical*1 :: clear, measure, apply + + clear=.false. + measure=.true. + apply=.false. + ! One measurement per process: refspectrum writes a file every fourth call. + call refspectrum(id2,ninput,clear,measure,apply,'unused-receive-reference.dat') +end subroutine + +! Exercise the production filter-application path. Build a deterministic, +! non-identity reference file in the test process so the write footprint is +! observable without relying on a user's writable-data directory. +subroutine receive_reference_apply_probe(id2,ninput) bind(C) + use iso_c_binding, only: c_int16_t,c_int + implicit none + integer(c_int16_t) :: id2(*) + integer(c_int), value :: ninput + logical*1 :: clear, measure, apply + integer :: i + real :: frequency + character(len=*), parameter :: path='receive-reference-apply.dat' + + open(16,file=path,status='replace') + write(16,'(3i5,5e25.16)') 400,2600,5,0.d0,0.d0,0.d0,0.d0,0.d0 + do i=1,3456 + frequency=12000.0*i/6912.0 + write(16,'(f10.3,e12.3,f12.6,e12.3,f12.6)') & + frequency,1.0,0.0,0.5,20.0*log10(0.5) + enddo + close(16) + + clear=.false. + measure=.false. + apply=.true. + call refspectrum(id2,ninput,clear,measure,apply,path) +end subroutine diff --git a/tests/unit/audio/test_audio_input_stream_descriptor.cpp b/tests/unit/audio/test_audio_input_stream_descriptor.cpp new file mode 100644 index 00000000..57698073 --- /dev/null +++ b/tests/unit/audio/test_audio_input_stream_descriptor.cpp @@ -0,0 +1,411 @@ +#include <QtTest> + +#include <QAudioDeviceInfo> +#include <QAudioFormat> +#include <QDateTime> +#include <QFile> +#include <QSignalSpy> +#include <QTemporaryFile> +#include <QVector> + +#include <algorithm> +#include <utility> + +#include "Audio/AudioDevice.hpp" +#include "Audio/AudioStreamClock.hpp" +#include "Audio/AudioStreamDescriptor.hpp" +#include "Audio/BWFFile.hpp" +#include "Audio/FixtureAudioInput.hpp" +#include "DecDataMutex.hpp" +#include "Detector/Detector.hpp" +#include "commons.h" + +namespace +{ + dec_data_t test_dec_data {}; + + void clear_dec_data (dec_data_t& data) + { + std::fill_n (data.ss, sizeof data.ss / sizeof *data.ss, 0.F); + std::fill_n (data.savg, sizeof data.savg / sizeof *data.savg, 0.F); + std::fill_n (data.sred, sizeof data.sred / sizeof *data.sred, 0.F); + std::fill_n (data.d2, sizeof data.d2 / sizeof *data.d2, 0); + data.params = {}; + } +} + +dec_data_t& dec_data = test_dec_data; + +extern "C" void fil4_state_ (qint16 *, qint32 *, qint16 *, qint32 *, float *) +{ +} + +namespace +{ + QAudioFormat pcmFormat (QAudioFormat::SampleType sampleType, + int sampleSize, QAudioFormat::Endian byteOrder, + int channels) + { + QAudioFormat format; + format.setByteOrder (byteOrder); + format.setChannelCount (channels); + format.setCodec ("audio/pcm"); + format.setSampleRate (12000); + format.setSampleSize (sampleSize); + format.setSampleType (sampleType); + return format; + } + + QString createJttyFixture () + { + QTemporaryFile temp; + temp.setAutoRemove (false); + if (!temp.open ()) + { + return {}; + } + auto const path = temp.fileName (); + temp.close (); + + BWFFile file { + pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1), path}; + if (!file.open (QIODevice::WriteOnly)) + { + QFile::remove (path); + return {}; + } + char const samples[] = {'\0', '\0'}; + auto constexpr sampleBytes = qint64 {sizeof samples}; + if (file.write (samples, sampleBytes) != sampleBytes) + { + file.close (); + QFile::remove (path); + return {}; + } + file.close (); + return path; + } + + class TestAudioSink final + : public AudioDevice + { + protected: + qint64 readData (char *, qint64) override {return -1;} + qint64 writeData (char const *, qint64 size) override {return size;} + }; + + class TemporaryPathCleanup final + { + public: + explicit TemporaryPathCleanup (QString path) + : path_ {std::move (path)} + { + } + + ~TemporaryPathCleanup () + { + if (!path_.isEmpty ()) QFile::remove (path_); + } + + TemporaryPathCleanup (TemporaryPathCleanup const&) = delete; + TemporaryPathCleanup& operator= (TemporaryPathCleanup const&) = delete; + + private: + QString path_; + }; +} + +class TestAudioInputStreamDescriptor + : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void init () + { + set_dec_data_input_blocked (false); + clear_dec_data (dec_data); + } + + Q_SLOT void cleanup () + { + set_dec_data_input_blocked (false); + } + + Q_SLOT void default_descriptor_is_invalid () + { + AudioStreamDescriptor const descriptor; + QVERIFY (!descriptor.isValid ()); + QCOMPARE (descriptor.sample_rate_hz, 0); + QVERIFY (descriptor.sample_encoding + == AudioStreamDescriptor::SampleEncoding::Unknown); + QCOMPARE (descriptor.sample_size_bits, 0); + QVERIFY (descriptor.byte_order == AudioStreamDescriptor::ByteOrder::Unknown); + QCOMPARE (descriptor.channel_count, 0); + QCOMPARE (descriptor.capture_anchor_utc_ms, qint64 {0}); + QVERIFY (descriptor.channel_layout + == AudioStreamDescriptor::ChannelLayout::Unknown); + QVERIFY (descriptor.clock_domain + == AudioStreamDescriptor::ClockDomain::Unknown); + QVERIFY (descriptor.timing_evidence + == AudioStreamDescriptor::TimingEvidence::Unavailable); + QVERIFY (!descriptor.can_report_discontinuities); + } + + Q_SLOT void validity_and_equality_cover_all_facts () + { + AudioStreamDescriptor descriptor; + descriptor.sample_rate_hz = 48000; + descriptor.sample_encoding = + AudioStreamDescriptor::SampleEncoding::SignedInteger; + descriptor.sample_size_bits = 16; + descriptor.byte_order = AudioStreamDescriptor::ByteOrder::LittleEndian; + descriptor.channel_count = 2; + descriptor.channel_layout = AudioStreamDescriptor::ChannelLayout::Stereo; + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::DeviceClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::PositionCountable; + + QVERIFY (descriptor.isValid ()); + auto copy = descriptor; + QVERIFY (copy == descriptor); + copy.can_report_discontinuities = true; + QVERIFY (copy != descriptor); + + copy = descriptor; + copy.sample_rate_hz = 0; + QVERIFY (!copy.isValid ()); + copy = descriptor; + copy.sample_encoding = AudioStreamDescriptor::SampleEncoding::Unknown; + QVERIFY (!copy.isValid ()); + copy = descriptor; + copy.sample_size_bits = 0; + QVERIFY (!copy.isValid ()); + copy = descriptor; + copy.byte_order = AudioStreamDescriptor::ByteOrder::Unknown; + QVERIFY (!copy.isValid ()); + copy = descriptor; + copy.channel_count = 0; + QVERIFY (!copy.isValid ()); + + copy = descriptor; + copy.capture_anchor_utc_ms = 123; + QVERIFY (copy != descriptor); + } + + Q_SLOT void selects_capture_anchor_for_system_clock () + { + auto descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1)); + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + descriptor.capture_anchor_utc_ms = 123456789000; + + AudioStreamClock clock; + clock.setDescriptor (descriptor); + QVERIFY (clock.reference () == AudioStreamClock::Reference::CaptureAnchor); + QCOMPARE (clock.timestamp (987654321000), qint64 {123456789000}); + + clock.advance (12000); + QCOMPARE (clock.timestamp (987654321000), qint64 {123456790000}); + } + + Q_SLOT void uses_arrival_clock_without_capture_evidence () + { + auto descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1)); + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::DeviceClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::PositionCountable; + descriptor.capture_anchor_utc_ms = 123456789000; + + AudioStreamClock clock; + clock.setDescriptor (descriptor); + QVERIFY (clock.reference () == AudioStreamClock::Reference::ArrivalWallClock); + QCOMPARE (clock.timestamp (987654321000), qint64 {987654321000}); + + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::Unknown; + clock.setDescriptor (descriptor); + QVERIFY (clock.reference () == AudioStreamClock::Reference::ArrivalWallClock); + QCOMPARE (clock.timestamp (987654321000), qint64 {987654321000}); + + clock.setDescriptor ({}); + QVERIFY (clock.reference () == AudioStreamClock::Reference::ArrivalWallClock); + QCOMPARE (clock.timestamp (987654321000), qint64 {987654321000}); + } + + Q_SLOT void maps_qt_pcm_formats () + { + auto descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1)); + QVERIFY (descriptor.isValid ()); + QCOMPARE (descriptor.sample_rate_hz, 12000); + QCOMPARE (descriptor.sample_size_bits, 16); + QCOMPARE (descriptor.channel_count, 1); + QVERIFY (descriptor.sample_encoding + == AudioStreamDescriptor::SampleEncoding::SignedInteger); + QVERIFY (descriptor.byte_order + == AudioStreamDescriptor::ByteOrder::LittleEndian); + QVERIFY (descriptor.channel_layout + == AudioStreamDescriptor::ChannelLayout::Mono); + + descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::UnSignedInt, 8, + QAudioFormat::LittleEndian, 6)); + QVERIFY (descriptor.isValid ()); + QCOMPARE (descriptor.sample_rate_hz, 12000); + QCOMPARE (descriptor.sample_size_bits, 8); + QCOMPARE (descriptor.channel_count, 6); + QVERIFY (descriptor.sample_encoding + == AudioStreamDescriptor::SampleEncoding::UnsignedInteger); + QVERIFY (descriptor.byte_order == AudioStreamDescriptor::ByteOrder::Unknown); + QVERIFY (descriptor.channel_layout + == AudioStreamDescriptor::ChannelLayout::Unknown); + + descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::Float, 32, QAudioFormat::BigEndian, 2)); + QVERIFY (descriptor.isValid ()); + QCOMPARE (descriptor.sample_rate_hz, 12000); + QCOMPARE (descriptor.sample_size_bits, 32); + QCOMPARE (descriptor.channel_count, 2); + QVERIFY (descriptor.sample_encoding + == AudioStreamDescriptor::SampleEncoding::FloatingPoint); + QVERIFY (descriptor.byte_order + == AudioStreamDescriptor::ByteOrder::BigEndian); + QVERIFY (descriptor.channel_layout + == AudioStreamDescriptor::ChannelLayout::Stereo); + } + + Q_SLOT void rejects_unrecognized_qt_formats () + { + QVERIFY (!audioStreamDescriptorFromQAudioFormat (QAudioFormat {}).isValid ()); + + auto unknown = pcmFormat (QAudioFormat::Unknown, 16, + QAudioFormat::LittleEndian, 1); + QVERIFY (!audioStreamDescriptorFromQAudioFormat (unknown).isValid ()); + + auto nonPcm = pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1); + nonPcm.setCodec ("audio/example"); + QVERIFY (!audioStreamDescriptorFromQAudioFormat (nonPcm).isValid ()); + + auto nonByteAligned = pcmFormat (QAudioFormat::SignedInt, 7, + QAudioFormat::LittleEndian, 1); + QVERIFY (!audioStreamDescriptorFromQAudioFormat (nonByteAligned).isValid ()); + } + + Q_SLOT void fixture_reports_opened_stream () + { + auto const path = createJttyFixture (); + QVERIFY (!path.isEmpty ()); + TemporaryPathCleanup cleanup {path}; + + FixtureAudioInput source {path, FixtureAudioInput::Profile::Jtty}; + TestAudioSink sink; + QVector<AudioStreamDescriptor> changes; + connect (&source, &AudioInputSource::streamDescriptorChanged, + [&changes] (AudioStreamDescriptor descriptor) { + changes.append (descriptor); + }); + + QVERIFY (!source.streamDescriptor ().isValid ()); + source.start (QAudioDeviceInfo {}, 0, &sink, 1, AudioDevice::Mono); + + QCOMPARE (changes.size (), 1); + auto const descriptor = source.streamDescriptor (); + QVERIFY (descriptor.isValid ()); + QCOMPARE (descriptor.sample_rate_hz, 12000); + QVERIFY (descriptor.sample_encoding + == AudioStreamDescriptor::SampleEncoding::SignedInteger); + QCOMPARE (descriptor.sample_size_bits, 16); + QVERIFY (descriptor.byte_order + == AudioStreamDescriptor::ByteOrder::LittleEndian); + QCOMPARE (descriptor.channel_count, 1); + QVERIFY (descriptor.channel_layout + == AudioStreamDescriptor::ChannelLayout::Mono); + QVERIFY (descriptor.clock_domain + == AudioStreamDescriptor::ClockDomain::SystemClock); + QVERIFY (descriptor.timing_evidence + == AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored); + QCOMPARE (descriptor.capture_anchor_utc_ms, qint64 {0}); + QVERIFY (!descriptor.can_report_discontinuities); + QVERIFY (changes.constFirst () == descriptor); + + auto constexpr fixturePeriodMs = qint64 {180000}; + auto const periodOffset = QDateTime::currentMSecsSinceEpoch () + % fixturePeriodMs; + auto const untilNextPeriod = fixturePeriodMs - periodOffset; + if (untilNextPeriod < 3000) + { + QTest::qWait (static_cast<int> (untilNextPeriod + 100)); + } + + QSignalSpy emissions {&source, &FixtureAudioInput::emissionStarted}; + source.resume (); + source.arm (); + auto const anchored = source.streamDescriptor (); + QVERIFY (anchored.capture_anchor_utc_ms > 0); + QCOMPARE (changes.size (), 2); + QVERIFY (changes.constLast () == anchored); + + QTRY_VERIFY_WITH_TIMEOUT (emissions.count () > 0, 1000); + QCOMPARE (emissions.constFirst ().constFirst ().toLongLong (), + anchored.capture_anchor_utc_ms); + QTest::qWait (200); + source.suspend (); + auto const beforeResume = QDateTime::currentMSecsSinceEpoch (); + source.resume (); + auto const resumed = source.streamDescriptor (); + QVERIFY (resumed.capture_anchor_utc_ms >= beforeResume - 20); + QVERIFY (resumed.capture_anchor_utc_ms <= beforeResume + 20); + QCOMPARE (changes.size (), 3); + + source.stop (); + QCOMPARE (changes.size (), 4); + QVERIFY (!changes.constLast ().isValid ()); + QVERIFY (!source.streamDescriptor ().isValid ()); + } + + Q_SLOT void detector_clock_advances_for_consumed_frames () + { + Detector detector {12000, 1.0, 1}; + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + detector.setBlockSize (1200); + QSignalSpy framesWritten {&detector, &Detector::framesWritten}; + + auto descriptor = audioStreamDescriptorFromQAudioFormat ( + pcmFormat (QAudioFormat::SignedInt, 16, + QAudioFormat::LittleEndian, 1)); + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + descriptor.timing_evidence = + AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + descriptor.capture_anchor_utc_ms = 100500; + detector.setStreamDescriptor (descriptor); + + QByteArray accepted {2400, '\0'}; + QCOMPARE (detector.write (accepted.constData (), accepted.size ()), + qint64 {accepted.size ()}); + QCOMPARE (framesWritten.constLast ().constFirst ().toLongLong (), qint64 {1200}); + + QByteArray blocked {14400, '\0'}; + set_dec_data_input_blocked (true); + QCOMPARE (detector.write (blocked.constData (), blocked.size ()), + qint64 {blocked.size ()}); + set_dec_data_input_blocked (false); + + detector.setBlockSize (1); + QByteArray finalFrame {2, '\0'}; + QCOMPARE (detector.write (finalFrame.constData (), finalFrame.size ()), + qint64 {finalFrame.size ()}); + QCOMPARE (framesWritten.constLast ().constFirst ().toLongLong (), qint64 {1}); + } +}; + +QTEST_GUILESS_MAIN (TestAudioInputStreamDescriptor) + +#include "test_audio_input_stream_descriptor.moc" diff --git a/tests/unit/audio/test_bwf_file.cpp b/tests/unit/audio/test_bwf_file.cpp new file mode 100644 index 00000000..61456aa1 --- /dev/null +++ b/tests/unit/audio/test_bwf_file.cpp @@ -0,0 +1,423 @@ +#include <QtTest> + +#include <QFile> +#include <QTemporaryFile> +#include <QtMultimedia/QAudioFormat> + +#include "Audio/BWFFile.hpp" +#include "Audio/WavFile.hpp" + +namespace +{ + QByteArray le16 (quint16 value) + { + QByteArray bytes (2, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + return bytes; + } + + QByteArray le32 (quint32 value) + { + QByteArray bytes (4, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + bytes[2] = static_cast<char> ((value >> 16) & 0xffu); + bytes[3] = static_cast<char> ((value >> 24) & 0xffu); + return bytes; + } + + QByteArray chunk (char const * id, QByteArray const& payload) + { + QByteArray out; + out.append (id, 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + if (payload.size () & 1) + { + out.append ('\0'); + } + return out; + } + + QByteArray wave_file (QList<QByteArray> const& chunks) + { + QByteArray payload {"WAVE", 4}; + for (auto const& current : chunks) + { + payload.append (current); + } + + QByteArray out; + out.append ("RIFF", 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + return out; + } + + QByteArray fmt_chunk (quint16 channels = 1, quint32 sample_rate = 12000, + quint16 bits_per_sample = 16, quint16 block_align = 0, + quint32 byte_rate = 0) + { + if (!block_align) + { + block_align = static_cast<quint16> (channels * (bits_per_sample / 8u)); + } + if (!byte_rate) + { + byte_rate = sample_rate * block_align; + } + + QByteArray payload; + payload.append (le16 (1)); + payload.append (le16 (channels)); + payload.append (le32 (sample_rate)); + payload.append (le32 (byte_rate)); + payload.append (le16 (block_align)); + payload.append (le16 (bits_per_sample)); + return chunk ("fmt ", payload); + } + + QByteArray data_chunk (QByteArray const& data = {}) + { + return chunk ("data", data); + } + + QByteArray info_list_chunk () + { + QByteArray payload {"INFO", 4}; + payload.append (chunk ("INAM", QByteArray {"wsjtx", 5})); + return chunk ("LIST", payload); + } + + QByteArray info_list_chunk_with_terminal_pad_outside_size () + { + QByteArray payload {"INFO", 4}; + payload.append ("ISRC", 4); + payload.append (le32 (5)); + payload.append ("K1JT", 5); + + QByteArray out; + out.append ("LIST", 4); + out.append (le32 (static_cast<quint32> (payload.size ()))); + out.append (payload); + out.append ('\0'); + return out; + } + + QByteArray bare_bext_payload () + { + return QByteArray (604, '\0'); + } + + QAudioFormat default_format () + { + QAudioFormat format; + format.setByteOrder (QAudioFormat::LittleEndian); + format.setChannelCount (1); + format.setCodec ("audio/pcm"); + format.setSampleRate (12000); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + return format; + } + + QString write_temp_file (QByteArray const& data) + { + QTemporaryFile file; + file.setAutoRemove (false); + if (!file.open ()) + { + return {}; + } + + if (file.write (data) != data.size ()) + { + return {}; + } + + auto const name = file.fileName (); + file.close (); + return name; + } +} + +class TestBWFFile + : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void opens_valid_pcm_wave () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.format ().channelCount (), 1); + QCOMPARE (file.format ().sampleRate (), 12000); + file.close (); + QFile::remove (name); + } + + Q_SLOT void loads_supported_decode_wave () + { + QByteArray samples; + samples.append (le16 (0x1234)); + samples.append (le16 (0x5678)); + samples.append (le16 (0x9abc)); + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk (samples)})); + QVERIFY (!name.isEmpty ()); + + auto const result = Radio::WavFile::load (name, 2); + QVERIFY2 (result.isValid (), qPrintable (result.error)); + QCOMPARE (result.frames, 2); + QCOMPARE (result.samples, samples.left (4)); + QFile::remove (name); + } + + Q_SLOT void loads_legacy_decode_waves () + { + auto const eight_bit_name = write_temp_file ( + wave_file ({fmt_chunk (1, 11025, 8), data_chunk (QByteArray::fromHex ("7f80"))})); + QVERIFY (!eight_bit_name.isEmpty ()); + auto const eight_bit = Radio::WavFile::load (eight_bit_name, 2); + QVERIFY2 (eight_bit.isValid (), qPrintable (eight_bit.error)); + QCOMPARE (eight_bit.frames, 2); + QCOMPARE (eight_bit.samples, QByteArray::fromHex ("7f80")); + QFile::remove (eight_bit_name); + + auto const sixteen_bit_name = write_temp_file ( + wave_file ({fmt_chunk (1, 11025, 16), data_chunk (QByteArray::fromHex ("01000200"))})); + QVERIFY (!sixteen_bit_name.isEmpty ()); + auto const sixteen_bit = Radio::WavFile::load (sixteen_bit_name, 2); + QVERIFY2 (sixteen_bit.isValid (), qPrintable (sixteen_bit.error)); + QCOMPARE (sixteen_bit.frames, 2); + QCOMPARE (sixteen_bit.samples, QByteArray::fromHex ("01000200")); + QFile::remove (sixteen_bit_name); + } + + Q_SLOT void rejects_multichannel_decode_wave () + { + auto const name = write_temp_file ( + wave_file ({fmt_chunk (2000, 12000, 16), data_chunk (QByteArray::fromHex ("0000"))})); + QVERIFY (!name.isEmpty ()); + + BWFFile parsed {QAudioFormat {}, name}; + QVERIFY (parsed.open (QIODevice::ReadOnly)); + QCOMPARE (parsed.format ().channelCount (), 2000); + parsed.close (); + + auto const result = Radio::WavFile::load (name, 36000); + QVERIFY (!result.isValid ()); + QVERIFY (result.samples.isEmpty ()); + QCOMPARE (result.frames, 0); + QFile::remove (name); + } + + Q_SLOT void discards_partial_decode_frame () + { + auto const name = write_temp_file ( + wave_file ({fmt_chunk (), data_chunk (QByteArray::fromHex ("010002"))})); + QVERIFY (!name.isEmpty ()); + + auto const result = Radio::WavFile::load (name, 2); + QVERIFY2 (result.isValid (), qPrintable (result.error)); + QCOMPARE (result.frames, 1); + QCOMPARE (result.samples, QByteArray::fromHex ("0100")); + QFile::remove (name); + } + + Q_SLOT void opens_valid_list_info_chunk () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), info_list_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + BWFFile::InfoDictionary::key_type const inam {{'I', 'N', 'A', 'M'}}; + QByteArray const expected_name {"wsjtx", 5}; + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (file.list_info ().contains (inam)); + QCOMPARE (file.list_info ().value (inam), expected_name); + file.close (); + QFile::remove (name); + } + + Q_SLOT void opens_list_info_with_terminal_subchunk_pad () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk (), + info_list_chunk_with_terminal_pad_outside_size ()})); + QVERIFY (!name.isEmpty ()); + BWFFile::InfoDictionary::key_type const isrc {{'I', 'S', 'R', 'C'}}; + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (file.list_info ().contains (isrc)); + QCOMPARE (file.list_info ().value (isrc), QByteArray ("K1JT", 5)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_version_without_chunk_defaults_to_v0 () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + BWFFile const& const_file = file; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (static_cast<int> (const_file.bext_version ()), + static_cast<int> (BWFFile::BextVersion::v_0)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_fixed_field_getter_stays_bounded () + { + QByteArray bext = bare_bext_payload (); + bext.replace (0, 256, QByteArray (256, 'B')); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("bext", bext), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_description (), QByteArray (256, 'B')); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_origination_date_time_stays_bounded () + { + QByteArray bext = bare_bext_payload (); + bext.replace (320, 10, QByteArray {"2026-04-06", 10}); + bext.replace (330, 10, QByteArray {"12-34-56ZZ", 10}); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("bext", bext), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_origination_date_time ().date (), QDate (2026, 4, 6)); + QCOMPARE (file.bext_origination_date_time ().time (), QTime (12, 34, 56)); + file.close (); + QFile::remove (name); + } + + Q_SLOT void bext_origination_date_time_setter_handles_invalid_value () + { + QTemporaryFile temp; + temp.setAutoRemove (false); + QVERIFY (temp.open ()); + auto const name = temp.fileName (); + temp.close (); + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + file.bext_origination_date_time ({}); + file.close (); + } + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QVERIFY (!file.bext_origination_date_time ().isValid ()); + file.close (); + } + + QFile::remove (name); + } + + Q_SLOT void bext_setter_truncates_without_overread () + { + QTemporaryFile temp; + temp.setAutoRemove (false); + QVERIFY (temp.open ()); + auto const name = temp.fileName (); + temp.close (); + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::WriteOnly)); + file.bext_description (QByteArray (300, 'A')); + file.close (); + } + + { + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.bext_description (), QByteArray (256, 'A')); + file.close (); + } + + QFile::remove (name); + } + + Q_SLOT void rejects_truncated_bext_chunk () + { + QByteArray bad_bext; + bad_bext.append ("bext", 4); + bad_bext.append (le32 (700)); + bad_bext.append (QByteArray (16, '\0')); + auto const name = write_temp_file (wave_file ({fmt_chunk (), bad_bext, data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_list_info_subchunk_overrun () + { + QByteArray payload {"INFO", 4}; + payload.append ("INAM", 4); + payload.append (le32 (8)); + payload.append ("bad", 3); + auto const name = write_temp_file (wave_file ({fmt_chunk (), chunk ("LIST", payload), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_short_fmt_chunk () + { + QByteArray payload; + payload.append (le16 (1)); + payload.append (le16 (1)); + auto const name = write_temp_file (wave_file ({chunk ("fmt ", payload), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void rejects_zero_channel_fmt () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (0), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (!file.open (QIODevice::ReadOnly)); + QFile::remove (name); + } + + Q_SLOT void tolerates_inconsistent_fmt_rates () + { + auto const name = write_temp_file (wave_file ({fmt_chunk (1, 12000, 16, 4, 48000), data_chunk ()})); + QVERIFY (!name.isEmpty ()); + + BWFFile file {default_format (), name}; + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.format ().sampleRate (), 12000); + QCOMPARE (file.format ().sampleSize (), 16); + file.close (); + QFile::remove (name); + } +}; + +QTEST_MAIN (TestBWFFile) + +#include "test_bwf_file.moc" diff --git a/tests/unit/audio/test_echosim_wav_trailer.cpp b/tests/unit/audio/test_echosim_wav_trailer.cpp new file mode 100644 index 00000000..3348b8d5 --- /dev/null +++ b/tests/unit/audio/test_echosim_wav_trailer.cpp @@ -0,0 +1,96 @@ +#include <QtTest> + +#include <QDir> +#include <QProcess> +#include <QTemporaryDir> +#include <QtEndian> +#include <QtMultimedia/QAudioFormat> + +#include "Audio/BWFFile.hpp" + +namespace +{ + QAudioFormat default_format () + { + QAudioFormat format; + format.setByteOrder (QAudioFormat::LittleEndian); + format.setChannelCount (1); + format.setCodec ("audio/pcm"); + format.setSampleRate (12000); + format.setSampleSize (16); + format.setSampleType (QAudioFormat::SignedInt); + return format; + } +} + +class TestEchosimWavTrailer + : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void preserves_generated_sample_alignment () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + + QProcess process; + process.setWorkingDirectory (dir.path ()); + process.start (ECHOSIM_EXECUTABLE, {"1500", "0.0", "0.0", "1", "100"}); + QVERIFY (process.waitForFinished (30000)); + QCOMPARE (process.exitCode (), 0); + + QDir out {dir.path ()}; + auto const wavs = out.entryList ({"*.wav"}, QDir::Files); + QCOMPARE (wavs.size (), 1); + + BWFFile file {default_format (), out.filePath (wavs.first ())}; + QVERIFY (file.open (QIODevice::ReadOnly)); + + // The first ten samples contain Echo metadata; sample 11 is generated audio. + qint16 sample; + QVERIFY (file.seek (10 * sizeof sample)); + QCOMPARE (file.read (reinterpret_cast<char *> (&sample), sizeof sample), + static_cast<qint64> (sizeof sample)); + sample = qFromLittleEndian (sample); + QVERIFY (sample >= 23168 && sample <= 23172); + + file.close (); + } + + Q_SLOT void writes_correct_data_size_and_list_info_trailer () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + + QProcess process; + process.setWorkingDirectory (dir.path ()); + process.start (ECHOSIM_EXECUTABLE, {"1500", "0.0", "4.0", "1", "-22"}); + QVERIFY (process.waitForFinished (30000)); + QCOMPARE (process.exitCode (), 0); + + QDir out {dir.path ()}; + auto const wavs = out.entryList ({"*.wav"}, QDir::Files); + QCOMPARE (wavs.size (), 1); + + BWFFile file {default_format (), out.filePath (wavs.first ())}; + QVERIFY (file.open (QIODevice::ReadOnly)); + + qint64 constexpr sample_count = 36000; + QCOMPARE (file.size (), 2 * sample_count); + + BWFFile::InfoDictionary::key_type const isft {{'I', 'S', 'F', 'T'}}; + BWFFile::InfoDictionary::key_type const icrd {{'I', 'C', 'R', 'D'}}; + BWFFile::InfoDictionary::key_type const icmt {{'I', 'C', 'M', 'T'}}; + QVERIFY (file.list_info ().contains (isft)); + QVERIFY (file.list_info ().contains (icrd)); + QVERIFY (file.list_info ().contains (icmt)); + QVERIFY (!file.list_info ().value (icmt).isEmpty ()); + + file.close (); + } +}; + +QTEST_GUILESS_MAIN (TestEchosimWavTrailer) + +#include "test_echosim_wav_trailer.moc" diff --git a/tests/unit/audio/test_fast_decode_ownership.cpp b/tests/unit/audio/test_fast_decode_ownership.cpp new file mode 100644 index 00000000..9375b527 --- /dev/null +++ b/tests/unit/audio/test_fast_decode_ownership.cpp @@ -0,0 +1,336 @@ +#include <QtTest> +#include <QThread> + +#include <algorithm> +#include <array> +#include <chrono> +#include <condition_variable> +#include <cstring> +#include <memory> +#include <mutex> +#include <vector> + +#include "FastDecode.hpp" +#include "Detector/Detector.hpp" +#include "commons.h" +#include "wsjtx_config.h" + +namespace +{ +dec_data_t storage {}; +constexpr int capacity = 360000; +constexpr int committed = 7168; + +class Rendezvous +{ +public: + bool arrive () + { + std::unique_lock<std::mutex> lock {mutex_}; + ++arrivals_; + changed_.notify_all (); + return changed_.wait_for (lock, std::chrono::seconds {5}, + [this] { return arrivals_ == 2; }); + } +private: + std::mutex mutex_; + std::condition_variable changed_; + int arrivals_ = 0; +}; + +struct DecoderProbe +{ + std::mutex mutex; + std::condition_variable changed; + bool entered = false; + bool released = false; + bool timedOut = false; + bool validCount = false; + bool offCallerThread = false; + QThread * callerThread = QThread::currentThread (); + std::vector<short> samples; + std::array<int, 15> arguments; + double period = 0; + QByteArray myCall, hisCall; + std::array<fortran_charlen_t, 3> lengths; + Rendezvous * sampleAccessStart = nullptr; + + bool waitForEntry () + { + std::unique_lock<std::mutex> lock {mutex}; + return changed.wait_for (lock, std::chrono::seconds {5}, + [this] { return entered; }); + } + + void release () + { + std::lock_guard<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + } +}; + +DecoderProbe * activeProbe = nullptr; +std::array<DecoderProbe *, 2> overlappingProbes {{nullptr, nullptr}}; + +struct Inputs +{ + std::array<int, 15> arguments {}; + double period = 15; + std::array<char, 8000> messages {}; + std::array<char, 12> myCall, hisCall; + + Inputs () + { + arguments[0] = 123000; + arguments[1] = committed; + arguments[3] = 1; + arguments[8] = 2; + arguments[9] = 104; + arguments[10] = 1500; + arguments[11] = 100; + std::memcpy (myCall.data (), "K1ABC ", 12); + std::memcpy (hisCall.data (), "W9XYZ ", 12); + } + + QFuture<FastDecodeResult> submit (short const * samples = storage.d2) + { + return startFastDecode (samples, arguments.data (), period, + myCall.data (), hisCall.data ()); + } +}; +} + +dec_data_t& dec_data = storage; + +// Substitute only the decoder at its ABI boundary. The production helper +// still copies the source and launches the real QtConcurrent job. Delaying +// input consumption models an ordinarily scheduled-but-not-yet-running job. +extern "C" void fast_decode_ (short samples[], int arguments[], double * period, + char messages[], char myCall[], char hisCall[], + fortran_charlen_t messageLength, + fortran_charlen_t myCallLength, + fortran_charlen_t hisCallLength) +{ + auto * selected = activeProbe; + if (!selected && arguments[0] == 111000) selected = overlappingProbes[0]; + if (!selected && arguments[0] == 222000) selected = overlappingProbes[1]; + auto& probe = *selected; + { + std::unique_lock<std::mutex> lock {probe.mutex}; + probe.entered = true; + probe.changed.notify_all (); + probe.timedOut = !probe.changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return probe.released; }); + } + if (probe.timedOut) return; // A harness timeout must not introduce an unordered read. + if (probe.sampleAccessStart && !probe.sampleAccessStart->arrive ()) + { + probe.timedOut = true; + return; + } + probe.offCallerThread = QThread::currentThread () != probe.callerThread; + probe.validCount = arguments[1] >= 0 && arguments[1] <= capacity; + if (probe.validCount) probe.samples.assign (samples, samples + arguments[1]); + std::copy_n (arguments, 15, probe.arguments.begin ()); + probe.period = *period; + probe.lengths = {{messageLength, myCallLength, hisCallLength}}; + probe.myCall = QByteArray (myCall, 12); + probe.hisCall = QByteArray (hisCall, 12); + // Preserve the existing ABI's output behavior, including in/out arguments. + std::memcpy (messages, "PROBE", 6); + arguments[12] = 31; + arguments[13] = 248; +} + +class TestFastDecodeOwnership : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void captures_submission_inputs () + { + std::fill_n (storage.d2, committed, short (1234)); + Inputs input; + auto const expectedArguments = input.arguments; + DecoderProbe probe; + activeProbe = &probe; + auto future = input.submit (); + bool const entered = probe.waitForEntry (); + // All caller storage remains alive. The release orders these mutations + // before the probe reads, so an assertion failure is an ownership defect, + // not undefined behavior deliberately introduced by the test. + std::fill_n (storage.d2, committed, short (5678)); + std::memcpy (input.myCall.data (), "N0NEW ", 12); + std::memcpy (input.hisCall.data (), "G4NEW ", 12); + input.period = 30; + input.arguments[10] = 2500; + probe.release (); + future.waitForFinished (); + activeProbe = nullptr; + + QVERIFY (entered); + QVERIFY (!probe.timedOut); + QVERIFY (probe.offCallerThread); + QVERIFY (probe.validCount); + QCOMPARE (probe.lengths[0], fortran_charlen_t (8000)); + QCOMPARE (probe.lengths[1], fortran_charlen_t (12)); + QCOMPARE (probe.lengths[2], fortran_charlen_t (12)); + auto const result = future.result (); + QCOMPARE (QByteArray (result.messages.data ()), QByteArray ("PROBE")); + QCOMPARE (result.arguments[12], 31); + QCOMPARE (result.arguments[13], 248); + QCOMPARE (input.arguments[12], 0); // worker never writes caller storage + QVERIFY (probe.arguments == expectedArguments); + QCOMPARE (probe.samples.size (), std::size_t (committed)); + QVERIFY (std::all_of (probe.samples.begin (), probe.samples.end (), + [] (short x) { return x == 1234; })); + QCOMPARE (probe.myCall, QByteArray ("K1ABC ", 12)); + QCOMPARE (probe.hisCall, QByteArray ("W9XYZ ", 12)); + QCOMPARE (probe.period, 15.0); + } + + void capture_does_not_race_live_append () + { + Detector detector {12000, 15.0, 1}; + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + AudioStreamDescriptor descriptor; + descriptor.sample_rate_hz = 12000; + descriptor.sample_encoding = AudioStreamDescriptor::SampleEncoding::SignedInteger; + descriptor.sample_size_bits = 16; + descriptor.byte_order = AudioStreamDescriptor::ByteOrder::LittleEndian; + descriptor.channel_count = 1; + descriptor.channel_layout = AudioStreamDescriptor::ChannelLayout::Mono; + descriptor.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + descriptor.timing_evidence = AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + descriptor.capture_anchor_utc_ms = 90000; + detector.setStreamDescriptor (descriptor); + ReceiveAudioConsumer consumer; + auto connection = connect (&detector, &Detector::audioBlock, this, + [&] (ReceiveAudio audio) { QVERIFY (consumer.accept (audio, storage)); }); + std::vector<short> initial (committed, 1234); + QCOMPARE (detector.write (reinterpret_cast<char const *> (initial.data ()), + initial.size () * sizeof (short)), qint64 (2 * committed)); + disconnect (connection); + + std::mutex mutex; + std::condition_variable changed; + bool ready = false, released = false, writerStarted = false; + qint64 written = -1; + auto * callerThread = QThread::currentThread (); + std::unique_ptr<QThread> writer {QThread::create ([&] { + { + std::unique_lock<std::mutex> lock {mutex}; + ready = true; + changed.notify_all (); + writerStarted = changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return released; }); + } + if (writerStarted) + { + std::vector<short> next (3584, 5678); + written = detector.write (reinterpret_cast<char const *> (next.data ()), + next.size () * sizeof (short)); + } + detector.moveToThread (callerThread); + })}; + detector.moveToThread (writer.get ()); + writer->start (); + bool writerReady; + { + std::unique_lock<std::mutex> lock {mutex}; + writerReady = changed.wait_for (lock, std::chrono::seconds {5}, [&] { return ready; }); + released = true; + changed.notify_all (); + } + // Both the production capture and the append execute after releasing the + // gate. No completion handshake orders one sample access before the other. + Inputs input; + DecoderProbe probe; + probe.released = true; + activeProbe = &probe; + auto future = input.submit (); + future.waitForFinished (); + writer->wait (); + activeProbe = nullptr; + QVERIFY (writerReady); + QVERIFY (writerStarted); + QCOMPARE (written, qint64 (2 * 3584)); + QCOMPARE (dec_data.params.kin, committed); + QVERIFY (probe.validCount); + QCOMPARE (probe.samples.size (), std::size_t (committed)); + QVERIFY (std::all_of (probe.samples.begin (), probe.samples.end (), + [] (short x) { return x == 1234; })); + // Producer appends cannot mutate the decoder's accepted snapshot. + } + + void overlapping_jobs_retain_submission_identity () + { + std::fill_n (storage.d2, committed, short (1234)); + std::vector<short> secondSamples (committed, short (5678)); + Inputs first, second; + first.arguments[0] = 111000; + second.arguments[0] = 222000; + DecoderProbe firstProbe, secondProbe; + secondProbe.released = true; + overlappingProbes = {{&firstProbe, &secondProbe}}; + + auto firstFuture = first.submit (); + bool const firstEntered = firstProbe.waitForEntry (); + // Submission performs the production staging copy synchronously. The + // first decoder is already pending but has not consumed any samples. + auto secondFuture = second.submit (secondSamples.data ()); + firstProbe.release (); + firstFuture.waitForFinished (); + secondFuture.waitForFinished (); + overlappingProbes = {{nullptr, nullptr}}; + + QVERIFY (firstEntered); + QVERIFY (!firstProbe.timedOut); + QVERIFY (!secondProbe.timedOut); + QVERIFY (firstProbe.entered); + QVERIFY (secondProbe.entered); + QCOMPARE (firstProbe.samples.size (), std::size_t (committed)); + QCOMPARE (secondProbe.samples.size (), std::size_t (committed)); + QVERIFY (std::all_of (firstProbe.samples.begin (), firstProbe.samples.end (), + [] (short x) { return x == 1234; })); + QVERIFY (std::all_of (secondProbe.samples.begin (), secondProbe.samples.end (), + [] (short x) { return x == 5678; })); + } + + void overlapping_submission_does_not_race_decoder () + { + std::fill_n (storage.d2, committed, short (1234)); + std::vector<short> secondSamples (committed, short (5678)); + Inputs first, second; + first.arguments[0] = 111000; + second.arguments[0] = 222000; + DecoderProbe firstProbe, secondProbe; + firstProbe.released = true; + secondProbe.released = true; + Rendezvous sampleAccessStart; + firstProbe.sampleAccessStart = &sampleAccessStart; + overlappingProbes = {{&firstProbe, &secondProbe}}; + + auto firstFuture = first.submit (); + QFuture<FastDecodeResult> secondFuture; + std::unique_ptr<QThread> submitter {QThread::create ([&] { + if (sampleAccessStart.arrive ()) + secondFuture = second.submit (secondSamples.data ()); + })}; + submitter->start (); + submitter->wait (); + firstFuture.waitForFinished (); + secondFuture.waitForFinished (); + overlappingProbes = {{nullptr, nullptr}}; + + QVERIFY (!firstProbe.timedOut); + QVERIFY (!secondProbe.timedOut); + QVERIFY (firstProbe.entered); + QVERIFY (secondProbe.entered); + // Under TSan, the production staging memcpy conflicts with the first + // decoder's read. No data-value assertion relies on that C++ race. + } +}; + +QTEST_GUILESS_MAIN (TestFastDecodeOwnership) +#include "test_fast_decode_ownership.moc" diff --git a/tests/unit/audio/test_receive_audio_handoff.cpp b/tests/unit/audio/test_receive_audio_handoff.cpp new file mode 100644 index 00000000..07cc9865 --- /dev/null +++ b/tests/unit/audio/test_receive_audio_handoff.cpp @@ -0,0 +1,535 @@ +#include <QtTest> +#include <QCoreApplication> +#include <QEvent> +#include <QEventLoop> +#include <QMutexLocker> +#include <QThread> +#include <QTimer> +#include <QTemporaryDir> +#include <QFile> +#include <cmath> + +#include <algorithm> +#include <array> +#include <chrono> +#include <condition_variable> +#include <memory> +#include <mutex> +#include <utility> +#include <vector> + +#include "Audio/AudioDevice.hpp" +#include "DecDataMutex.hpp" +#include "Detector/Detector.hpp" +#include "commons.h" +#include "ReferenceSpectrum.hpp" +#include "wsjtx_config.h" + +extern "C" void refspectrum_ (short *, int *, bool *, bool *, bool *, char const *, fortran_charlen_t); + +namespace +{ +dec_data_t storage {}; +constexpr int block = 3584; +constexpr int committed = 2 * block; +constexpr short patternA = 1234; +constexpr short patternB = 5678; + +// Both conflicting accesses take place AFTER this rendezvous. In particular, +// there is no producer-completion acknowledgement before the DSP read. +class Rendezvous +{ +public: + bool arrive () + { + std::unique_lock<std::mutex> lock {mutex_}; + ++arrivals_; + changed_.notify_all (); + return changed_.wait_for (lock, std::chrono::seconds {5}, + [this] { return arrivals_ == 2; }); + } +private: + std::mutex mutex_; + std::condition_variable changed_; + int arrivals_ = 0; +}; + +AudioStreamDescriptor descriptor (bool rollover) +{ + AudioStreamDescriptor result; + result.sample_rate_hz = 12000; + result.sample_encoding = AudioStreamDescriptor::SampleEncoding::SignedInteger; + result.sample_size_bits = 16; + result.byte_order = AudioStreamDescriptor::ByteOrder::LittleEndian; + result.channel_count = 1; + result.channel_layout = AudioStreamDescriptor::ChannelLayout::Mono; + result.clock_domain = AudioStreamDescriptor::ClockDomain::SystemClock; + result.timing_evidence = AudioStreamDescriptor::TimingEvidence::CaptureTimeAnchored; + // With a one-second period, 7168 samples advance 100.500 s to 101.097 s. + // Detector's next write therefore takes its real period-reset path. + result.capture_anchor_utc_ms = rollover ? 100500 : 90000; + return result; +} + +bool writeSamples (Detector& detector, int count, short value) +{ + std::vector<short> samples (count, value); + auto const bytes = qint64 (samples.size () * sizeof (short)); + return detector.write (reinterpret_cast<char const *> (samples.data ()), bytes) == bytes; +} + +bool writeReferenceSpectrum (QFile& file) +{ + if (!file.open (QIODevice::WriteOnly)) return false; + file.write (QString::asprintf ("%5d%5d%5d", 400, 2600, 5).toLatin1 ()); + for (int i = 0; i < 5; ++i) + file.write (QString::asprintf ("%25.16e", 0.).toLatin1 ()); + file.write ("\n"); + for (int i = 1; i <= 3456; ++i) + file.write (QString::asprintf ("%10.3f%12.3e%12.6f%12.6f%12.6f\n", + 12000. * i / 6912., 1., 0., 0.5, -6.0206).toLatin1 ()); + file.close (); + return true; +} + +std::vector<short> noiseSamples (int count) +{ + std::vector<short> samples (count); + unsigned noise = 1; + for (auto& sample : samples) + { + noise = 1664525u * noise + 1013904223u; + sample = short (int (noise >> 20) - 2048); + } + return samples; +} + +std::vector<short> runReferenceSpectrum (std::vector<short> const& original, + int step, bool measure, + QByteArray const& path) +{ + auto samples = original; + bool clear = true, apply = !measure; + int zero = 0; + refspectrum_ (samples.data (), &zero, &clear, &measure, &apply, + path.constData (), fortran_charlen_t (path.size ())); + clear = false; + ReferenceSpectrumInput reference; + for (int end = std::min (step, int (samples.size ())); ; + end = std::min (end + step, int (samples.size ()))) + { + reference.consume (samples.data (), end, measure ? 1 : 2, + [&] (short * p, int count) { + refspectrum_ (p, &count, &clear, &measure, &apply, + path.constData (), fortran_charlen_t (path.size ())); + }); + if (end == int (samples.size ())) break; + } + return samples; +} +} + +dec_data_t& dec_data = storage; +extern "C" void receive_reference_probe (short *, int); +extern "C" void receive_reference_apply_probe (short *, int); +extern "C" void fil4_state_ (qint16 *, qint32 *, qint16 *, qint32 *, float *); +extern "C" void save_echo_params_ (int *, int *, int *, float *, float *, + int *, int *, short *, int *); + +struct EchoMetadata +{ + int total = 123456, audio = 789, rit = 123, spacing = 15; + float frequency = 1500.5f, spread = 2.5f; + std::array<int, 6> tones {{0, 1, 2, 3, 4, 5}}; + + void transfer (short * samples, int direction) + { + save_echo_params_ (&total, &audio, &rit, &frequency, &spread, + &spacing, tones.data (), samples, &direction); + } +}; + +class TestReceiveAudioHandoff : public QObject +{ + Q_OBJECT + + void notificationTest (bool rollover) + { + Detector detector {12000, 1.0, 1}; + detector.setBlockSize (block); + auto * guiThread = QThread::currentThread (); + std::vector<short> observed; + std::vector<qint64> counts; + auto received = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer consumer; + int rejected = 0; + connect (&detector, &Detector::audioBlock, this, [&] (ReceiveAudio audio) { + if (!consumer.accept (audio, *received)) { ++rejected; return; } + counts.push_back (audio->end ()); + observed.push_back (received->d2[audio->end () - 1]); + }, Qt::QueuedConnection); + + bool wrote = false; + std::unique_ptr<QThread> worker {QThread::create ([&] { + bool ok = detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono); + detector.setStreamDescriptor (descriptor (true)); + ok = writeSamples (detector, committed, patternA) && ok; + if (rollover) ok = writeSamples (detector, committed, patternB) && ok; + wrote = ok; + detector.moveToThread (guiThread); + })}; + detector.moveToThread (worker.get ()); + worker->start (); + // Intentionally withhold GUI delivery until *all* writes have completed. + // There is no data race here: the assertion checks period identity. + worker->wait (); + QCoreApplication::sendPostedEvents (this, QEvent::MetaCall); + QVERIFY (wrote); + QCOMPARE (counts.size (), std::size_t (2)); + QCOMPARE (rejected, rollover ? 2 : 0); + QCOMPARE (counts[0], qint64 (block)); + QCOMPARE (counts[1], qint64 (committed)); + QCOMPARE (observed[0], rollover ? patternB : patternA); + QCOMPARE (observed[1], rollover ? patternB : patternA); + } + + void consumerRace (bool rollover, bool echo = false) + { + int const initialFrames = echo ? 8 * block : committed; + Detector detector {12000, rollover ? (echo ? 3.0 : 1.0) : 15.0, 1}; + detector.setBlockSize (block); + auto * guiThread = QThread::currentThread (); + Rendezvous start; + bool consumed = false; + bool consumerReady = false; + bool producerReady = false; + bool wrote = false; + auto received = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer consumer; + QEventLoop events; + QTimer timeout; + timeout.setSingleShot (true); + connect (&timeout, &QTimer::timeout, &events, &QEventLoop::quit); + connect (&detector, &Detector::audioBlock, this, [&] (ReceiveAudio audio) { + if (consumed || !consumer.accept (audio, *received)) return; + int const frames = audio->end (); + if (frames != initialFrames) return; + consumed = true; + // Use the production committed-range adapter, independent of MSK's + // 3584-sample notification step or symbol length. + auto * input = echo ? received->d2 + : received->d2 + frames - 3456; + consumerReady = start.arrive (); + if (consumerReady) + { + if (echo) + { + EchoMetadata metadata; + metadata.transfer (input, 1); + } + else + { + ReferenceSpectrumInput reference; + reference.consume (input, 3456, 1, receive_reference_probe); + } + } + }, Qt::QueuedConnection); + + std::unique_ptr<QThread> worker {QThread::create ([&] { + bool ok = detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono); + detector.setStreamDescriptor (descriptor (rollover)); + ok = writeSamples (detector, initialFrames, patternA) && ok; + producerReady = start.arrive (); + if (producerReady) ok = writeSamples (detector, block, patternB) && ok; + wrote = ok; + detector.moveToThread (guiThread); + })}; + connect (worker.get (), &QThread::finished, &events, &QEventLoop::quit); + detector.moveToThread (worker.get ()); + timeout.start (15000); + worker->start (); + events.exec (); + worker->wait (); + QCoreApplication::sendPostedEvents (this, QEvent::MetaCall); + QVERIFY (wrote); + QVERIFY (consumed); + QVERIFY (producerReady); + QVERIFY (consumerReady); + QVERIFY (std::all_of (received->d2 + (echo ? 15 : 0), + received->d2 + initialFrames, + [] (short x) { return x == patternA; })); + if (echo) + { + EchoMetadata actual; + actual.total = actual.audio = actual.rit = actual.spacing = 0; + actual.frequency = actual.spread = 0; + actual.tones.fill (0); + actual.transfer (received->d2, -1); + EchoMetadata expected; + QCOMPARE (actual.total, expected.total); + QCOMPARE (actual.audio, expected.audio); + QCOMPARE (actual.rit, expected.rit); + QCOMPARE (actual.spacing, expected.spacing); + QCOMPARE (actual.frequency, expected.frequency); + QCOMPARE (actual.spread, expected.spread); + QVERIFY (actual.tones == expected.tones); + // Header insertion must leave all captured audio after sample 15 intact. + QVERIFY (std::all_of (received->d2 + 15, received->d2 + initialFrames, + [] (short x) { return x == patternA; })); + } + // TSan checks conflicting accesses when the compiler instruments them. + // See echo-jtty-ownership.md for the local Echo array-copy blind spot. + QCOMPARE (received->params.kin, initialFrames); + } + +private Q_SLOTS: + void downsamplersRetainIndependentHistory () + { + std::array<float, 49> firstState {}, secondState {}, referenceState {}; + std::array<qint16, 16> firstInput, secondInput, interferingInput; + firstInput.fill (1200); + secondInput.fill (2400); + interferingInput.fill (-3000); + std::array<qint16, 4> ignored {}, actual {}, expected {}; + qint32 inputFrames = int (firstInput.size ()); + qint32 outputFrames = 0; + + fil4_state_ (firstInput.data (), &inputFrames, ignored.data (), + &outputFrames, firstState.data ()); + fil4_state_ (interferingInput.data (), &inputFrames, ignored.data (), + &outputFrames, secondState.data ()); + fil4_state_ (secondInput.data (), &inputFrames, actual.data (), + &outputFrames, firstState.data ()); + fil4_state_ (firstInput.data (), &inputFrames, ignored.data (), + &outputFrames, referenceState.data ()); + fil4_state_ (secondInput.data (), &inputFrames, expected.data (), + &outputFrames, referenceState.data ()); + + QVERIFY (actual == expected); + } + + void producersRemainIsolatedAcrossSourceSwitch () + { + ReceiveAudioProducer first; + ReceiveAudioProducer second; + ReceiveAudio firstPrefix, firstContinuation, secondPrefix, secondContinuation; + { + QMutexLocker lock {&dec_data_mutex ()}; + first.reset (15.0); + std::fill_n (first.data ().d2, block, patternA); + first.setFrames (block); + firstPrefix = first.capture (block, 15.0); + + second.reset (15.0); + std::fill_n (second.data ().d2, block, patternB); + second.setFrames (block); + secondPrefix = second.capture (block, 15.0); + + std::fill_n (first.data ().d2 + block, block, patternA); + first.setFrames (committed); + firstContinuation = first.capture (committed, 15.0); + std::fill_n (second.data ().d2 + block, block, patternB); + second.setFrames (committed); + secondContinuation = second.capture (committed, 15.0); + } + + QCOMPARE (first.frames (), committed); + QCOMPARE (second.frames (), committed); + QCOMPARE (firstContinuation->start, block); + QCOMPARE (secondContinuation->start, block); + QVERIFY (std::all_of (firstContinuation->samples.begin (), + firstContinuation->samples.end (), + [] (short sample) { return sample == patternA; })); + QVERIFY (std::all_of (secondContinuation->samples.begin (), + secondContinuation->samples.end (), + [] (short sample) { return sample == patternB; })); + + auto target = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer consumer; + QVERIFY (consumer.accept (firstPrefix, *target)); + QVERIFY (consumer.accept (secondPrefix, *target)); + QVERIFY (!consumer.accept (firstContinuation, *target)); + QVERIFY (consumer.accept (secondContinuation, *target)); + QCOMPARE (target->params.kin, committed); + QCOMPARE (target->d2[committed - 1], patternB); + } + + void handoff_rejects_gaps_and_disk_stale_work () + { + Detector detector {12000, 15.0, 1}; + detector.setBlockSize (block); + QVERIFY (detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono)); + detector.setStreamDescriptor (descriptor (false)); + std::vector<ReceiveAudio> blocks; + connect (&detector, &Detector::audioBlock, this, + [&] (ReceiveAudio audio) { blocks.push_back (std::move (audio)); }); + QVERIFY (writeSamples (detector, committed, patternA)); + QCOMPARE (blocks.size (), std::size_t (2)); + ReceiveAudioConsumer consumer; + auto received = std::make_unique<dec_data_t> (); + QVERIFY (!consumer.accept (blocks[1], *received)); // missing prefix + QCOMPARE (received->params.kin, 0); + QVERIFY (consumer.accept (blocks[0], *received)); + QVERIFY (!consumer.accept (blocks[0], *received)); // duplicate + QVERIFY (consumer.accept (blocks[1], *received)); + QCOMPARE (received->params.kin, committed); + // Installing a WAV invalidates all queued work from the old live epoch. + consumer.invalidate (); + std::fill_n (received->d2, committed, short {-123}); + QVERIFY (!consumer.accept (blocks[0], *received)); + QCOMPARE (received->d2[0], short {-123}); + detector.reset (); + QVERIFY (writeSamples (detector, block, patternB)); + QCOMPARE (blocks.size (), std::size_t (3)); + QVERIFY (consumer.accept (blocks.back (), *received)); + QCOMPARE (received->params.kin, block); + QVERIFY (std::all_of (received->d2, received->d2 + block, + [] (short x) { return x == patternB; })); + QVERIFY (std::all_of (received->d2 + block, received->d2 + committed, + [] (short x) { return x == 0; })); + // Producer reset and consumer writes cannot change an already owned block. + QVERIFY (std::all_of (blocks[0]->samples.begin (), blocks[0]->samples.end (), + [] (short x) { return x == patternA; })); + detector.setTRPeriod (30.0); + QVERIFY (writeSamples (detector, block, patternA)); + QCOMPARE (blocks.size (), std::size_t (4)); + QVERIFY (!consumer.accept (blocks[2], *received)); + QVERIFY (consumer.accept (blocks[3], *received)); + QCOMPARE (received->params.kin, block); + QCOMPARE (received->d2[0], patternA); + QVERIFY (writeSamples (detector, 288, patternB)); + QCOMPARE (blocks.size (), std::size_t (4)); // incomplete notification + detector.flushBufferedFrames (block + 288); + QCOMPARE (blocks.size (), std::size_t (5)); + QVERIFY (consumer.accept (blocks.back (), *received)); + QCOMPARE (received->params.kin, block + 288); + QCOMPARE (received->d2[block + 287], patternB); + detector.flushBufferedFrames (block + 288); + QCOMPARE (blocks.size (), std::size_t (5)); // flush is idempotent + } + void stale_echo_metadata_must_not_modify_next_period () + { + constexpr int echoFrames = 8 * block; + Detector detector {12000, 3.0, 1}; + detector.setBlockSize (block); + auto * guiThread = QThread::currentThread (); + bool handled = false, wrote = false; + auto received = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer consumer; + int rejected = 0; + connect (&detector, &Detector::audioBlock, this, [&] (ReceiveAudio audio) { + if (!consumer.accept (audio, *received)) { ++rejected; return; } + if (audio->end () != echoFrames) return; + handled = true; // B is still processed; stale A cannot change it. + EchoMetadata metadata; + metadata.transfer (received->d2, 1); + }, Qt::QueuedConnection); + std::unique_ptr<QThread> worker {QThread::create ([&] { + bool ok = detector.initialize (QIODevice::WriteOnly, AudioDevice::Mono); + detector.setStreamDescriptor (descriptor (true)); + ok = writeSamples (detector, echoFrames, patternA) && ok; + ok = writeSamples (detector, echoFrames, patternB) && ok; + wrote = ok; + detector.moveToThread (guiThread); + })}; + detector.moveToThread (worker.get ()); + worker->start (); + worker->wait (); + QCoreApplication::sendPostedEvents (this, QEvent::MetaCall); + QVERIFY (wrote); + QVERIFY (handled); + QCOMPARE (rejected, 8); + QCOMPARE (received->params.kin, echoFrames); + QVERIFY (std::all_of (received->d2 + 15, received->d2 + echoFrames, + [] (short x) { return x == patternB; })); + } + + void queued_prefix_without_reuse () { notificationTest (false); } + void queued_period_must_retain_identity () { notificationTest (true); } + void reference_measurement_vs_append () { consumerRace (false); } + void reference_measurement_vs_reset () { consumerRace (true); } + void reference_application_preserves_uncommitted_suffix () + { + std::fill_n (dec_data.d2, committed, patternA); + dec_data.params.kin = committed; + std::fill_n (dec_data.d2 + committed, 3456, patternB); + std::array<short, 3456> suffix; + std::copy_n (dec_data.d2 + committed, suffix.size (), suffix.begin ()); + + ReferenceSpectrumInput reference; + reference.consume (dec_data.d2, committed, 2, receive_reference_apply_probe); + QVERIFY (std::equal (suffix.begin (), suffix.end (), + dec_data.d2 + committed)); + } + void reference_input_packetization () + { + std::vector<short> samples (13952); + std::vector<std::pair<int, int>> calls; + ReferenceSpectrumInput reference; + auto record = [&] (short * p, int count) { + calls.emplace_back (int (p - samples.data ()), count); + }; + + reference.consume (samples.data (), 128, 2, record); + reference.consume (samples.data (), 2176, 2, record); + reference.consume (samples.data (), 5760, 2, record); + reference.consume (samples.data (), 13952, 2, record); + reference.consume (samples.data (), 13952, 2, record); + + std::vector<std::pair<int, int>> const expected { + {0, 0}, {0, 128}, {128, 2048}, {2176, 3456}, {5632, 128}, + {5760, 3456}, {9216, 3456}, {12672, 1280} + }; + QVERIFY (calls == expected); + + calls.clear (); + reference.consume (samples.data (), 32, 2, record); + std::vector<std::pair<int, int>> const newPeriod {{0, 0}, {0, 32}}; + QVERIFY (calls == newPeriod); + + calls.clear (); + reference.reset (); + reference.consume (samples.data (), 64, 2, record); + std::vector<std::pair<int, int>> const reset {{0, 0}, {0, 64}}; + QVERIFY (calls == reset); + } + void reference_application_packetization () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto path = (directory.path () + "/refspec.dat").toLocal8Bit (); + QFile file (QString::fromLocal8Bit (path)); + QVERIFY (writeReferenceSpectrum (file)); + auto const original = noiseSamples (2 * 3456); + auto const baseline = runReferenceSpectrum (original, 3456, false, path); + QCOMPARE (baseline.size (), original.size ()); + QVERIFY (baseline != original); + QVERIFY (std::any_of (baseline.begin (), baseline.end (), [] (short s) {return s != 0;})); + auto const output = runReferenceSpectrum (original, 3584, false, path); + QCOMPARE (output.size (), baseline.size ()); + for (std::size_t i = 0; i < output.size (); ++i) + QVERIFY (std::abs (int (output[i]) - int (baseline[i])) <= 1); + } + void reference_measurement_packetization () + { + QTemporaryDir directory; + QVERIFY (directory.isValid ()); + auto path = (directory.path () + "/refspec.dat").toLocal8Bit (); + QFile file (QString::fromLocal8Bit (path)); + auto const original = noiseSamples (4 * 3456); + + QCOMPARE (runReferenceSpectrum (original, 3456, true, path), original); + QVERIFY (file.open (QIODevice::ReadOnly)); + auto const measured = file.readAll (); + file.close (); + QVERIFY (!measured.isEmpty ()); + QCOMPARE (runReferenceSpectrum (original, 3584, true, path), original); + QVERIFY (file.open (QIODevice::ReadOnly)); + QCOMPARE (file.readAll (), measured); + } + void echo_metadata_vs_append () { consumerRace (false, true); } + void echo_metadata_vs_reset () { consumerRace (true, true); } +}; + +QTEST_GUILESS_MAIN (TestReceiveAudioHandoff) +#include "test_receive_audio_handoff.moc" diff --git a/tests/unit/audio/test_tx_audio_queue.cpp b/tests/unit/audio/test_tx_audio_queue.cpp new file mode 100644 index 00000000..e73eb79e --- /dev/null +++ b/tests/unit/audio/test_tx_audio_queue.cpp @@ -0,0 +1,209 @@ +#include <QtTest> + +#include <type_traits> + +#include "Audio/TxAudioQueue.hpp" +#include "Audio/TxAudioQueueEpochSnapshot.hpp" +#include "Modulator/JttyPcmFifo.hpp" + +namespace +{ + TxAudioQueueEpoch epoch (qint64 value) + { + return TxAudioQueueEpoch {value}; + } +} + +class TestTxAudioQueue : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void epoch_snapshot_requires_stable_even_sequence () + { + TxAudioQueueEpoch snapshot; + QVERIFY (!TxAudioQueueDetail::tryMakeEpochSnapshot (1, 11, 1, snapshot)); + QVERIFY (!TxAudioQueueDetail::tryMakeEpochSnapshot (2, 11, 4, snapshot)); + QVERIFY (TxAudioQueueDetail::tryMakeEpochSnapshot (6, 11, 6, snapshot)); + QCOMPARE (snapshot, epoch (11)); + } + + Q_SLOT void exposes_value_types_and_capacity () + { + static_assert (!std::is_copy_constructible<TxAudioQueue>::value, + "the queue must not be copied"); + static_assert (!std::is_copy_assignable<TxAudioQueue>::value, + "the queue must not be copy assigned"); + + TxAudioQueue queue; + JttyPcmFifo fifo {TxAudioQueue::defaultCapacity ()}; + QCOMPARE (queue.capacity (), TxAudioQueue::defaultCapacity ()); + QCOMPARE (queue.capacity (), fifo.capacity ()); + QVERIFY (qMetaTypeId<TxAudioQueueEpoch> () != QMetaType::UnknownType); + QVERIFY (qMetaTypeId<TxAudioQueueProgress> () != QMetaType::UnknownType); + QVERIFY (qMetaTypeId<TxAudioQueueDrainState> () != QMetaType::UnknownType); + QVERIFY (qMetaTypeId<TxAudioQueueEnqueueResult> () != QMetaType::UnknownType); + QVERIFY (epoch (1) == epoch (1)); + QVERIFY (epoch (1) != epoch (2)); + } + + Q_SLOT void enqueues_vectors_and_raw_samples_gaplessly () + { + TxAudioQueue queue {5}; + auto const current = epoch (11); + queue.clear (current); + queue.applyPendingReset (); + + QVector<qint16> const first {1, 2, 3}; + auto result = queue.enqueue (first, current); + QVERIFY (result.accepted); + QCOMPARE (result.progress.epoch, current); + QCOMPARE (result.progress.queued_samples, qint64 (3)); + QCOMPARE (result.progress.served_samples, qint64 (0)); + QCOMPARE (result.progress.total_samples, qint64 (3)); + + QCOMPARE (queue.pullSample (10), qint16 (1)); + QCOMPARE (queue.pullSample (10), qint16 (2)); + + qint16 const second[] {4, 5, 6}; + result = queue.enqueue (second, 3, current); + QVERIFY (result.accepted); + QCOMPARE (result.progress.queued_samples, qint64 (4)); + QCOMPARE (result.progress.served_samples, qint64 (2)); + QCOMPARE (result.progress.total_samples, qint64 (6)); + + QCOMPARE (queue.pullSample (10), qint16 (3)); + QCOMPARE (queue.pullSample (10), qint16 (4)); + QCOMPARE (queue.pullSample (10), qint16 (5)); + QCOMPARE (queue.pullSample (10), qint16 (6)); + QCOMPARE (queue.pullSample (10), qint16 (0)); + + auto const progress = queue.progress (); + QCOMPARE (progress.queued_samples, qint64 (0)); + QCOMPARE (progress.served_samples, qint64 (6)); + QCOMPARE (progress.total_samples, qint64 (6)); + } + + Q_SLOT void rejects_stale_epoch_with_authoritative_progress () + { + TxAudioQueue queue {4}; + auto const current = epoch (21); + queue.clear (current); + queue.applyPendingReset (); + QVERIFY (queue.enqueue (QVector<qint16> {7, 8}, current).accepted); + + qint16 const stale_sample {9}; + auto const rejected = queue.enqueue (&stale_sample, 1, epoch (22)); + QVERIFY (!rejected.accepted); + QCOMPARE (rejected.progress.epoch, current); + QCOMPARE (rejected.progress.queued_samples, qint64 (2)); + QCOMPARE (rejected.progress.served_samples, qint64 (0)); + QCOMPARE (rejected.progress.total_samples, qint64 (2)); + + auto const empty = queue.enqueue (nullptr, 0, current); + QVERIFY (empty.accepted); + QCOMPARE (empty.progress.total_samples, qint64 (2)); + QVERIFY (!queue.enqueue (nullptr, 0, epoch (99)).accepted); + } + + Q_SLOT void pending_reset_excludes_aborted_samples () + { + TxAudioQueue queue {8}; + auto const aborted = epoch (31); + auto const replacement = epoch (32); + queue.clear (aborted); + queue.applyPendingReset (); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3, 4}, aborted).accepted); + QCOMPARE (queue.pullSample (0), qint16 (1)); + + queue.clear (replacement); + auto progress = queue.progress (); + QCOMPARE (progress.epoch, replacement); + QCOMPARE (progress.queued_samples, qint64 (0)); + QCOMPARE (progress.served_samples, qint64 (0)); + QCOMPARE (progress.total_samples, qint64 (0)); + + qint16 const samples[] {8, 9}; + auto const result = queue.enqueue (samples, 2, replacement); + QVERIFY (result.accepted); + QCOMPARE (result.progress.queued_samples, qint64 (2)); + QCOMPARE (result.progress.total_samples, qint64 (2)); + + queue.applyPendingReset (); + QCOMPARE (queue.pullSample (0), qint16 (8)); + QCOMPARE (queue.pullSample (0), qint16 (9)); + progress = queue.progress (); + QCOMPARE (progress.served_samples, qint64 (2)); + QCOMPARE (progress.total_samples, qint64 (2)); + } + + Q_SLOT void overflow_leaves_accounting_unchanged () + { + TxAudioQueue queue {3}; + auto const current = epoch (41); + queue.clear (current); + queue.applyPendingReset (); + QVERIFY (queue.enqueue (QVector<qint16> {10, 11}, current).accepted); + + auto const rejected = queue.enqueue (QVector<qint16> {12, 13}, current); + QVERIFY (!rejected.accepted); + QCOMPARE (rejected.progress.queued_samples, qint64 (2)); + QCOMPARE (rejected.progress.total_samples, qint64 (2)); + + QCOMPARE (queue.pullSample (0), qint16 (10)); + QVERIFY (queue.enqueue (QVector<qint16> {12, 13}, current).accepted); + QCOMPARE (queue.pullSample (0), qint16 (11)); + QCOMPARE (queue.pullSample (0), qint16 (12)); + QCOMPARE (queue.pullSample (0), qint16 (13)); + } + + Q_SLOT void reports_drain_epoch_total_and_rearms () + { + TxAudioQueue queue {4}; + auto const current = epoch (51); + queue.clear (current); + queue.applyPendingReset (); + QVERIFY (queue.enqueue (QVector<qint16> {20, 21}, current).accepted); + + QCOMPARE (queue.pullSample (2), qint16 (20)); + QCOMPARE (queue.pullSample (2), qint16 (21)); + QCOMPARE (queue.pullSample (2), qint16 (0)); + QVERIFY (!queue.takeDrainReady ().ready); + QCOMPARE (queue.pullSample (2), qint16 (0)); + + auto drain = queue.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, current); + QCOMPARE (drain.total_at_drain, qint64 (2)); + QVERIFY (!queue.takeDrainReady ().ready); + + qint16 const next {22}; + QVERIFY (queue.enqueue (&next, 1, current).accepted); + QCOMPARE (queue.pullSample (0), qint16 (22)); + drain = queue.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, current); + QCOMPARE (drain.total_at_drain, qint64 (3)); + } + + Q_SLOT void reset_suppresses_stale_drain () + { + TxAudioQueue queue {2}; + auto const first = epoch (61); + auto const second = epoch (62); + queue.clear (first); + queue.applyPendingReset (); + QVERIFY (queue.enqueue (QVector<qint16> {30}, first).accepted); + QCOMPARE (queue.pullSample (0), qint16 (30)); + + queue.clear (second); + auto const stale = queue.takeDrainReady (); + QVERIFY (!stale.ready); + QCOMPARE (stale.epoch, second); + QCOMPARE (stale.total_at_drain, qint64 (0)); + } +}; + +QTEST_GUILESS_MAIN (TestTxAudioQueue) + +#include "test_tx_audio_queue.moc" diff --git a/tests/unit/audio/test_tx_playback_diagnostics.cpp b/tests/unit/audio/test_tx_playback_diagnostics.cpp new file mode 100644 index 00000000..90d9ec7e --- /dev/null +++ b/tests/unit/audio/test_tx_playback_diagnostics.cpp @@ -0,0 +1,261 @@ +#include <QtTest> + +#include <type_traits> + +#include "Audio/TxPlaybackDiagnostics.hpp" + +namespace +{ + TxEvidence::TxRawPlayoutSnapshot deviceClockStart (qint64 sequence) + { + TxEvidence::TxRawPlayoutSnapshot raw; + raw.tier = TxEvidence::TxPlayoutTier::DeviceClock; + raw.backend_start_sequence = sequence; + raw.start_event = true; + raw.available = true; + raw.state = TxEvidence::TxBackendState::Active; + raw.sample_rate_hz = 12000; + raw.processed_usecs = 250000; + raw.successfully_written_frames = 3000; + raw.report_interval_ms = 25; + return raw; + } +} + +class TestTxPlaybackDiagnostics : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void identities_are_trivial_and_strong () + { + static_assert (std::is_trivially_copyable<TxEvidence::TxSessionId>::value, + "session identities must remain trivially copyable"); + static_assert (std::is_trivially_copyable<TxEvidence::TxGeneration>::value, + "generation identities must remain trivially copyable"); + static_assert (!std::is_convertible<qint64, TxEvidence::TxSessionId>::value, + "session identity conversion must be explicit"); + QCOMPARE (TxEvidence::TxSessionId {}.value (), qint64 (0)); + QCOMPARE (TxEvidence::TxSessionId::invalid (), TxEvidence::TxSessionId {}); + QCOMPARE (TxEvidence::TxGeneration::invalid (), TxEvidence::TxGeneration {}); + QVERIFY (!TxEvidence::TxGeneration {}.isValid ()); + QVERIFY (TxEvidence::TxSessionId {4} < TxEvidence::TxSessionId {5}); + QVERIFY (TxEvidence::TxGeneration {4} < TxEvidence::TxGeneration {5}); + QVERIFY (qMetaTypeId<TxEvidence::TxSessionId> () != QMetaType::UnknownType); + QVERIFY (qMetaTypeId<TxEvidence::TxGeneration> () != QMetaType::UnknownType); + auto const generation1 = TxEvidence::TxPlaybackDiagnostics::allocateGeneration (); + auto const generation2 = TxEvidence::TxPlaybackDiagnostics::allocateGeneration (); + QVERIFY (generation1 < generation2); + } + + Q_SLOT void preserves_every_stop_reason_and_tail () + { + TxEvidence::TxPlaybackDiagnostics recorder; + TxEvidence::TxStopReason const reasons[] = { + TxEvidence::TxStopReason::NormalEnd, + TxEvidence::TxStopReason::UserHalt, + TxEvidence::TxStopReason::Watchdog, + TxEvidence::TxStopReason::Error, + TxEvidence::TxStopReason::ModeChange + }; + for (int index = 0; index != 5; ++index) + { + auto const session = recorder.beginSession ("FT8", 12000); + auto const generation = recorder.beginGeneration (session); + QVERIFY (generation.isValid ()); + auto const decision = recorder.stop (session, generation, reasons[index], index + 1); + QCOMPARE (decision.reason, reasons[index]); + QCOMPARE (decision.tail_ms, index + 1); + } + QCOMPARE (recorder.terminalSessions ().size (), 5); + } + + Q_SLOT void constructs_bounded_commit_extents () + { + QCOMPARE (TxEvidence::boundedCommittedEndSample (0, 0, 47999), qint64 (47999)); + QCOMPARE (TxEvidence::boundedCommittedEndSample (4800, 0, 47999), qint64 (52799)); + QCOMPARE (TxEvidence::boundedCommittedEndSample (0, 12000, 47999), qint64 (35999)); + QCOMPARE (TxEvidence::boundedCommittedEndSample (0, 48000, 47999), qint64 (-1)); + QCOMPARE (TxEvidence::interleavedFrameCount (2000, 2), qint64 (1000)); + QCOMPARE (TxEvidence::interleavedFrameCount (1999, 2), qint64 (-1)); + } + + Q_SLOT void rejects_invalid_session_start () + { + TxEvidence::TxPlaybackDiagnostics recorder; + QCOMPARE (recorder.beginSession ("FT8", 0), TxEvidence::TxSessionId::invalid ()); + } + + Q_SLOT void maps_legacy_tails_for_every_stop_reason () + { + TxEvidence::TxStopReason const reasons[] = { + TxEvidence::TxStopReason::NormalEnd, + TxEvidence::TxStopReason::UserHalt, + TxEvidence::TxStopReason::Watchdog, + TxEvidence::TxStopReason::Error, + TxEvidence::TxStopReason::ModeChange + }; + for (auto reason : reasons) + { + QCOMPARE (TxEvidence::TxPlaybackDiagnostics::decisionFor (reason, false).tail_ms, 200); + QCOMPARE (TxEvidence::TxPlaybackDiagnostics::decisionFor (reason, true).tail_ms, 0); + } + } + + Q_SLOT void captures_lifecycle_and_growing_target () + { + TxEvidence::TxPlaybackDiagnostics recorder; + auto const session = recorder.beginSession ("JTTY", 12000, 100, true); + auto const generation = recorder.beginGeneration (session); + QVERIFY (recorder.commitTarget (session, generation, 300)); + QVERIFY (!recorder.commitTarget (session, generation, 299)); + QVERIFY (recorder.observe (session, generation, deviceClockStart (7))); + QVERIFY (recorder.observeSourceProgress (session, generation, 250, 301, + "JTTY FIFO progress")); + QVERIFY (!recorder.observeSourceProgress (session, generation, 249, 301)); + recorder.stop (session, generation, TxEvidence::TxStopReason::NormalEnd, 42); + auto later = deviceClockStart (7); + later.start_event = false; + later.processed_usecs = 300000; + QVERIFY (recorder.observe (session, generation, later)); + + auto terminal = recorder.terminalSessions ().last (); + QCOMPARE (terminal.committed_end_sample, qint64 (300)); + QCOMPARE (terminal.consumed_samples, qint64 (3600)); + QCOMPARE (terminal.source_served_samples, qint64 (250)); + QCOMPARE (terminal.stop.tail_ms, 42); + QVERIFY (terminal.terminal_playout_observed); + QVERIFY (terminal.diagnostic.contains ("JTTY FIFO progress")); + + QVERIFY (recorder.commitTarget (session, generation, 400, true, + "Final JTTY source commitment")); + terminal = recorder.terminalSessions ().last (); + QCOMPARE (terminal.committed_end_sample, qint64 (400)); + QVERIFY (terminal.diagnostic.contains ("Final JTTY source commitment")); + QVERIFY (terminal.diagnostic.contains ("JTTY FIFO progress")); + QVERIFY (recorder.diagnosticDump ().contains ("Final JTTY source commitment")); + } + + Q_SLOT void normalizes_evidence_tiers_and_underrun () + { + TxEvidence::TxPlaybackDiagnostics recorder; + auto const session = recorder.beginSession ("FT4", 12000, 7999, true); + auto const generation = recorder.beginGeneration (session); + + auto raw = deviceClockStart (10); + raw.processed_usecs = 500000; + raw.source_served_frames = 5000; + raw.error = TxEvidence::TxBackendError::Underrun; + QVERIFY (recorder.observe (session, generation, raw)); + raw.start_event = false; + raw.processed_usecs = 600000; + raw.error = TxEvidence::TxBackendError::None; + QVERIFY (recorder.observe (session, generation, raw)); + recorder.stop (session, generation, TxEvidence::TxStopReason::Error); + auto terminal = recorder.terminalSessions ().last (); + QCOMPARE (terminal.consumed_samples, qint64 (7200)); + QVERIFY (terminal.underrun); + QVERIFY (terminal.truncated_known); + QVERIFY (terminal.truncated); + QVERIFY (recorder.diagnosticDump ().contains ("underrun=true")); + + auto const deadSession = recorder.beginSession ("FT8", 12000); + auto const deadGeneration = recorder.beginGeneration (deadSession); + raw = deviceClockStart (11); + raw.tier = TxEvidence::TxPlayoutTier::DeadReckoning; + raw.successfully_written_frames = 123; + QVERIFY (recorder.observe (deadSession, deadGeneration, raw)); + recorder.stop (deadSession, deadGeneration, TxEvidence::TxStopReason::NormalEnd); + QCOMPARE (recorder.terminalSessions ().last ().consumed_samples, qint64 (123)); + + auto const unavailableSession = recorder.beginSession ("FT8", 12000); + auto const unavailableGeneration = recorder.beginGeneration (unavailableSession); + raw = deviceClockStart (12); + raw.tier = TxEvidence::TxPlayoutTier::Unavailable; + QVERIFY (recorder.observe (unavailableSession, unavailableGeneration, raw)); + recorder.stop (unavailableSession, unavailableGeneration, + TxEvidence::TxStopReason::NormalEnd); + QCOMPARE (recorder.terminalSessions ().last ().consumed_samples, qint64 (-1)); + QVERIFY (!recorder.terminalSessions ().last ().terminal_playout_observed); + } + + Q_SLOT void unavailable_start_is_retained_and_obvious () + { + TxEvidence::TxPlaybackDiagnostics recorder; + auto const session = recorder.beginSession ("FT8", 48000, 47999, true); + auto const generation = recorder.beginGeneration (session); + TxEvidence::TxRawPlayoutSnapshot raw; + raw.start_event = true; + raw.backend_start_sequence = 20; + raw.tier = TxEvidence::TxPlayoutTier::Unavailable; + raw.state = TxEvidence::TxBackendState::Unavailable; + raw.diagnostic = "No audio output device configured"; + QVERIFY (recorder.observe (session, generation, raw)); + recorder.stop (session, generation, TxEvidence::TxStopReason::Error, 200); + auto const terminal = recorder.terminalSessions ().last (); + QCOMPARE (terminal.tier, TxEvidence::TxPlayoutTier::Unavailable); + QVERIFY (!terminal.terminal_playout_observed); + QVERIFY (recorder.diagnosticDump ().contains ("tier=unavailable")); + } + + Q_SLOT void weaker_snapshot_does_not_replace_device_clock_evidence () + { + TxEvidence::TxPlaybackDiagnostics recorder; + auto const session = recorder.beginSession ("JTTY", 12000, 2999, true); + auto const generation = recorder.beginGeneration (session); + auto raw = deviceClockStart (21); + QVERIFY (recorder.observe (session, generation, raw)); + recorder.stop (session, generation, TxEvidence::TxStopReason::NormalEnd); + + TxEvidence::TxRawPlayoutSnapshot unavailable; + unavailable.backend_start_sequence = 21; + unavailable.diagnostic = "No audio output stream is active"; + QVERIFY (!recorder.observe (session, generation, unavailable)); + + auto const terminal = recorder.terminalSessions ().last (); + QCOMPARE (terminal.tier, TxEvidence::TxPlayoutTier::DeviceClock); + QCOMPARE (terminal.consumed_samples, qint64 (3000)); + QVERIFY (terminal.terminal_playout_observed); + } + + Q_SLOT void rejects_stale_and_regressing_events () + { + TxEvidence::TxPlaybackDiagnostics recorder; + auto const session = recorder.beginSession ("FT8", 12000); + auto const generation = recorder.beginGeneration (session); + auto raw = deviceClockStart (17); + QVERIFY (recorder.observe (session, generation, raw)); + QVERIFY (!recorder.observe (session, generation, raw)); + QVERIFY (!recorder.observe (session, TxEvidence::TxGeneration {generation.value () - 1}, raw)); + raw.start_event = false; + raw.backend_start_sequence = 18; + QVERIFY (!recorder.observe (session, generation, raw)); + raw.backend_start_sequence = 17; + raw.processed_usecs = 1; + QVERIFY (!recorder.observe (session, generation, raw)); + + recorder.stop (session, generation, TxEvidence::TxStopReason::NormalEnd); + raw.processed_usecs = 750000; + QVERIFY (recorder.observe (session, generation, raw)); + QCOMPARE (recorder.terminalSessions ().last ().consumed_samples, qint64 (9000)); + } + + Q_SLOT void retains_the_last_sixteen_terminal_sessions () + { + TxEvidence::TxPlaybackDiagnostics recorder; + for (int index = 0; index != 20; ++index) + { + auto const session = recorder.beginSession ("FT8", 12000); + auto const generation = recorder.beginGeneration (session); + recorder.stop (session, generation, TxEvidence::TxStopReason::NormalEnd); + } + auto const terminals = recorder.terminalSessions (); + QCOMPARE (terminals.size (), 16); + QVERIFY (terminals.first ().session_id.value () < terminals.last ().session_id.value ()); + QVERIFY (recorder.diagnosticDump ().contains ("terminal")); + } +}; + +QTEST_GUILESS_MAIN (TestTxPlaybackDiagnostics) + +#include "test_tx_playback_diagnostics.moc" diff --git a/tests/unit/audio/test_tx_request.cpp b/tests/unit/audio/test_tx_request.cpp new file mode 100644 index 00000000..ee4b24f2 --- /dev/null +++ b/tests/unit/audio/test_tx_request.cpp @@ -0,0 +1,125 @@ +#include <QtTest> + +#include <QCoreApplication> +#include <QMetaType> + +#include "Audio/TxRequest.hpp" + +class TxRequestRelay : public QObject +{ + Q_OBJECT + +public: + TxEvidence::TxRequest received; + bool delivered {false}; + + Q_SIGNAL void requestReady (TxEvidence::TxRequest request); + + Q_SLOT void receive (TxEvidence::TxRequest request) + { + received = request; + delivered = true; + } +}; + +class TestTxRequest : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void has_ft8_defaults () + { + TxEvidence::TxRequest const request; + QCOMPARE (request.mode, QString {"FT8"}); + QCOMPARE (request.symbols_length, 79u); + QCOMPARE (request.frames_per_symbol, 1920.0); + QCOMPARE (request.frequency_hz, 1500.0); + QCOMPARE (request.tone_spacing, -3.0); + QCOMPARE (request.channel, AudioDevice::Mono); + QVERIFY (request.synchronize); + QVERIFY (!request.fast_mode); + QCOMPARE (request.snr_db, 99.0); + QCOMPARE (request.tr_period_s, 60.0); + QCOMPARE (request.session_id, TxEvidence::TxSessionId::invalid ()); + QCOMPARE (request.generation, TxEvidence::TxGeneration::invalid ()); + QCOMPARE (request.queue_epoch, TxAudioQueueEpoch::invalid ()); + QVERIFY (!request.tuning); + QVERIFY (request.cw_id.isEmpty ()); + QCOMPARE (request.start_window_open_ms, qint64 {-1}); + QCOMPARE (request.start_window_close_ms, qint64 {-1}); + } + + Q_SLOT void copies_every_distinct_field () + { + TxEvidence::TxRequest source; + source.mode = "JTTY"; + source.symbols_length = 101; + source.frames_per_symbol = 202.5; + source.frequency_hz = 303.5; + source.tone_spacing = 404.5; + source.channel = AudioDevice::Right; + source.synchronize = false; + source.fast_mode = true; + source.snr_db = 505.5; + source.tr_period_s = 606.5; + source.session_id = TxEvidence::TxSessionId {707}; + source.generation = TxEvidence::TxGeneration {808}; + source.queue_epoch = TxAudioQueueEpoch {909}; + source.tuning = true; + source.cw_id = {1, 0, 1}; + source.start_window_open_ms = 1010; + source.start_window_close_ms = 1111; + + auto const copy = source; + source = {}; + + QCOMPARE (copy.mode, QString {"JTTY"}); + QCOMPARE (copy.symbols_length, 101u); + QCOMPARE (copy.frames_per_symbol, 202.5); + QCOMPARE (copy.frequency_hz, 303.5); + QCOMPARE (copy.tone_spacing, 404.5); + QCOMPARE (copy.channel, AudioDevice::Right); + QVERIFY (!copy.synchronize); + QVERIFY (copy.fast_mode); + QCOMPARE (copy.snr_db, 505.5); + QCOMPARE (copy.tr_period_s, 606.5); + QCOMPARE (copy.session_id, TxEvidence::TxSessionId {707}); + QCOMPARE (copy.generation, TxEvidence::TxGeneration {808}); + QCOMPARE (copy.queue_epoch, TxAudioQueueEpoch {909}); + QVERIFY (copy.tuning); + QCOMPARE (copy.cw_id, QVector<int> ({1, 0, 1})); + QCOMPARE (copy.start_window_open_ms, qint64 {1010}); + QCOMPARE (copy.start_window_close_ms, qint64 {1111}); + } + + Q_SLOT void registers_and_delivers_queued_requests () + { + TxEvidence::register_tx_request_type (); + QCOMPARE (QMetaType::type ("TxEvidence::TxRequest"), + qMetaTypeId<TxEvidence::TxRequest> ()); + + TxRequestRelay relay; + QVERIFY (connect (&relay, &TxRequestRelay::requestReady, + &relay, &TxRequestRelay::receive, + Qt::QueuedConnection)); + + TxEvidence::TxRequest request; + request.mode = "FT4"; + request.session_id = TxEvidence::TxSessionId {12}; + request.generation = TxEvidence::TxGeneration {34}; + request.queue_epoch = TxAudioQueueEpoch {56}; + request.cw_id = {0, 1, 0}; + Q_EMIT relay.requestReady (request); + + QTRY_VERIFY (relay.delivered); + QCOMPARE (relay.received.mode, QString {"FT4"}); + QCOMPARE (relay.received.session_id, TxEvidence::TxSessionId {12}); + QCOMPARE (relay.received.generation, TxEvidence::TxGeneration {34}); + QCOMPARE (relay.received.queue_epoch, request.queue_epoch); + QCOMPARE (relay.received.cw_id, QVector<int> ({0, 1, 0})); + } +}; + +QTEST_GUILESS_MAIN (TestTxRequest) + +#include "test_tx_request.moc" diff --git a/tests/unit/audio/test_wav_input_loading.cpp b/tests/unit/audio/test_wav_input_loading.cpp new file mode 100644 index 00000000..d66e3f23 --- /dev/null +++ b/tests/unit/audio/test_wav_input_loading.cpp @@ -0,0 +1,203 @@ +#include <QtTest> + +#include <algorithm> +#include <future> + +#include <QFile> +#include <QSemaphore> +#include <QTemporaryFile> + +#include "Audio/WavInputLoader.hpp" + +namespace +{ +QByteArray le16 (quint16 value) +{ + QByteArray bytes (2, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + return bytes; +} + +QByteArray le32 (quint32 value) +{ + QByteArray bytes (4, '\0'); + bytes[0] = static_cast<char> (value & 0xffu); + bytes[1] = static_cast<char> ((value >> 8) & 0xffu); + bytes[2] = static_cast<char> ((value >> 16) & 0xffu); + bytes[3] = static_cast<char> ((value >> 24) & 0xffu); + return bytes; +} + +QByteArray wave_file (quint32 sample_rate, quint16 bits_per_sample, + QByteArray const& samples) +{ + auto const bytes_per_frame = static_cast<quint16> (bits_per_sample / 8u); + QByteArray format; + format.append (le16 (1)); + format.append (le16 (1)); + format.append (le32 (sample_rate)); + format.append (le32 (sample_rate * bytes_per_frame)); + format.append (le16 (bytes_per_frame)); + format.append (le16 (bits_per_sample)); + + QByteArray payload {"WAVE", 4}; + payload.append ("fmt ", 4); + payload.append (le32 (static_cast<quint32> (format.size ()))); + payload.append (format); + payload.append ("data", 4); + payload.append (le32 (static_cast<quint32> (samples.size ()))); + payload.append (samples); + if (samples.size () & 1) + { + payload.append ('\0'); + } + + QByteArray result {"RIFF", 4}; + result.append (le32 (static_cast<quint32> (payload.size ()))); + result.append (payload); + return result; +} + +QString write_temp_file (QByteArray const& contents) +{ + QTemporaryFile file; + file.setAutoRemove (false); + if (!file.open () || file.write (contents) != contents.size ()) + { + return {}; + } + auto const name = file.fileName (); + file.close (); + return name; +} + +QByteArray signed_samples (int count) +{ + QByteArray samples; + samples.reserve (count * 2); + for (int index = 0; index < count; ++index) + { + samples.append (le16 (static_cast<quint16> (1000 + index % 100))); + } + return samples; +} +} + +class TestWavInputLoading : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void preserves_short_input_and_zero_fills_tail () + { + QByteArray samples; + samples.append (le16 (1234)); + samples.append (le16 (static_cast<quint16> (-2345))); + samples.append (le16 (32767)); + auto const name = write_temp_file (wave_file (12000, 16, samples)); + QVERIFY (!name.isEmpty ()); + + auto const result = Radio::load_wav_input (name, 8); + QVERIFY (result.valid); + QCOMPARE (result.frames, 3); + QCOMPARE (result.samples.size (), std::size_t {8}); + QCOMPARE (result.samples[0], short {1234}); + QCOMPARE (result.samples[1], short {-2345}); + QCOMPARE (result.samples[2], short {32767}); + QVERIFY (std::all_of (result.samples.cbegin () + result.frames, + result.samples.cend (), [] (short sample) {return !sample;})); + QFile::remove (name); + } + + Q_SLOT void truncates_oversized_input_to_capacity () + { + int constexpr sample_limit = 13000; + auto const name = write_temp_file ( + wave_file (12000, 16, signed_samples (sample_limit + 1000))); + QVERIFY (!name.isEmpty ()); + + auto const result = Radio::load_wav_input (name, sample_limit); + QVERIFY (result.valid); + QCOMPARE (result.frames, sample_limit); + QCOMPARE (result.samples.size (), std::size_t {sample_limit}); + QCOMPARE (result.samples.back (), short {1000 + (sample_limit - 1) % 100}); + QFile::remove (name); + } + + Q_SLOT void resamples_legacy_input_data () + { + QTest::addColumn<int> ("sampleSize"); + QTest::addColumn<QByteArray> ("samples"); + + QTest::newRow ("unsigned-8-bit") << 8 << QByteArray (11025, static_cast<char> (200)); + QTest::newRow ("signed-16-bit") << 16 << signed_samples (11025); + } + + Q_SLOT void resamples_legacy_input () + { + QFETCH (int, sampleSize); + QFETCH (QByteArray, samples); + int constexpr sample_limit = 13000; + auto const name = write_temp_file ( + wave_file (11025, static_cast<quint16> (sampleSize), samples)); + QVERIFY (!name.isEmpty ()); + + auto const result = Radio::load_wav_input (name, sample_limit); + QVERIFY (result.valid); + QCOMPARE (result.frames, 12000); + QCOMPARE (result.samples.size (), std::size_t {sample_limit}); + QVERIFY (std::any_of (result.samples.cbegin (), result.samples.cbegin () + result.frames, + [] (short sample) {return sample != 0;})); + QVERIFY (std::all_of (result.samples.cbegin () + result.frames, result.samples.cend (), + [] (short sample) {return sample == 0;})); + QFile::remove (name); + } + + Q_SLOT void serializes_concurrent_legacy_resampling () + { + int constexpr input_frames = 60 * 11025; + int constexpr sample_limit = 60 * 12000; + auto const first_name = write_temp_file ( + wave_file (11025, 8, QByteArray (input_frames, static_cast<char> (40)))); + auto const second_name = write_temp_file ( + wave_file (11025, 8, QByteArray (input_frames, static_cast<char> (200)))); + QVERIFY (!first_name.isEmpty ()); + QVERIFY (!second_name.isEmpty ()); + + auto const expected_first = Radio::load_wav_input (first_name, sample_limit); + auto const expected_second = Radio::load_wav_input (second_name, sample_limit); + QVERIFY (expected_first.valid); + QVERIFY (expected_second.valid); + + QSemaphore ready; + QSemaphore start; + auto concurrent_load = [&] (QString name) { + return std::async (std::launch::async, [&, name] { + ready.release (); + start.acquire (); + return Radio::load_wav_input (name, sample_limit); + }); + }; + + auto first = concurrent_load (first_name); + auto second = concurrent_load (second_name); + ready.acquire (2); + start.release (2); + auto const actual_first = first.get (); + auto const actual_second = second.get (); + + QVERIFY (actual_first.valid); + QVERIFY (actual_second.valid); + QCOMPARE (actual_first.frames, expected_first.frames); + QCOMPARE (actual_second.frames, expected_second.frames); + QVERIFY (actual_first.samples == expected_first.samples); + QVERIFY (actual_second.samples == expected_second.samples); + QFile::remove (first_name); + QFile::remove (second_name); + } +}; + +QTEST_GUILESS_MAIN (TestWavInputLoading) + +#include "test_wav_input_loading.moc" diff --git a/tests/unit/audio/test_wav_load_coordinator.cpp b/tests/unit/audio/test_wav_load_coordinator.cpp new file mode 100644 index 00000000..a69c8c74 --- /dev/null +++ b/tests/unit/audio/test_wav_load_coordinator.cpp @@ -0,0 +1,117 @@ +#include <QtTest> + +#include <atomic> + +#include <QCoreApplication> +#include <QEventLoop> +#include <QSemaphore> +#include <QThread> + +#include "Audio/WavLoadCoordinator.hpp" +#include "DecDataMutex.hpp" + +class TestWavLoadCoordinator : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void init () + { + set_dec_data_input_blocked (false); + } + + Q_SLOT void cleanup () + { + set_dec_data_input_blocked (false); + } + + Q_SLOT void delivers_single_flight_lifecycle_data () + { + QTest::addColumn<bool> ("valid"); + QTest::newRow ("valid-result") << true; + QTest::newRow ("invalid-result") << false; + } + + Q_SLOT void delivers_single_flight_lifecycle () + { + QFETCH (bool, valid); + + WavLoadCoordinator coordinator; + QSemaphore entered; + QSemaphore release; + std::atomic_bool rejected_work_ran {false}; + QStringList lifecycle; + int result_count {0}; + QThread * delivery_thread {nullptr}; + bool loading_during_result {false}; + bool gate_during_result {false}; + bool controls_enabled {true}; + bool gate_at_idle {true}; + bool loading_at_idle {true}; + + connect (&coordinator, &WavLoadCoordinator::loadingChanged, + this, [&] (bool loading) { + lifecycle.append (loading ? "loading" : "idle"); + controls_enabled = !loading; + if (!loading) + { + gate_at_idle = dec_data_input_blocked (); + loading_at_idle = coordinator.isLoading (); + } + }); + connect (&coordinator, &WavLoadCoordinator::resultReady, this, [&] { + lifecycle.append ("result"); + ++result_count; + delivery_thread = QThread::currentThread (); + loading_during_result = coordinator.isLoading (); + gate_during_result = dec_data_input_blocked (); + }); + + QVERIFY (coordinator.start ([&] { + entered.release (); + release.tryAcquire (1, 5000); + auto result = std::make_shared<Radio::WavInputResult> (); + result->valid = valid; + return result; + })); + QVERIFY2 (entered.tryAcquire (1, 5000), "load A did not enter its worker"); + QVERIFY (!coordinator.start ([&] { + rejected_work_ran.store (true, std::memory_order_release); + return std::make_shared<Radio::WavInputResult> (); + })); + + QCoreApplication::processEvents (QEventLoop::AllEvents, 100); + QCOMPARE (result_count, 0); + QVERIFY (!rejected_work_ran.load (std::memory_order_acquire)); + QVERIFY (coordinator.isLoading ()); + QVERIFY (dec_data_input_blocked ()); + QVERIFY (!controls_enabled); + + release.release (); + coordinator.waitForFinished (); + QTRY_VERIFY_WITH_TIMEOUT (!coordinator.isLoading (), 5000); + + QCOMPARE (lifecycle, QStringList ({"loading", "result", "idle"})); + QCOMPARE (result_count, 1); + QCOMPARE (delivery_thread, coordinator.thread ()); + QVERIFY (loading_during_result); + QVERIFY (gate_during_result); + QVERIFY (coordinator.result ()); + QCOMPARE (coordinator.result ()->valid, valid); + QVERIFY (controls_enabled); + QVERIFY (!gate_at_idle); + QVERIFY (!loading_at_idle); + QVERIFY (!dec_data_input_blocked ()); + + QVERIFY (coordinator.start ([] { + return std::make_shared<Radio::WavInputResult> (); + })); + coordinator.waitForFinished (); + QTRY_VERIFY_WITH_TIMEOUT (!coordinator.isLoading (), 5000); + QCOMPARE (result_count, 2); + } +}; + +QTEST_GUILESS_MAIN (TestWavLoadCoordinator) + +#include "test_wav_load_coordinator.moc" diff --git a/tests/unit/band_hopping/CMakeLists.txt b/tests/unit/band_hopping/CMakeLists.txt new file mode 100644 index 00000000..94d7485a --- /dev/null +++ b/tests/unit/band_hopping/CMakeLists.txt @@ -0,0 +1,6 @@ +add_executable (test_band_hopping + test_band_hopping.cpp + ${CMAKE_SOURCE_DIR}/widgets/BandHopping.cpp +) +target_link_libraries (test_band_hopping Qt5::Test) +add_test (NAME test_band_hopping COMMAND test_band_hopping) diff --git a/tests/unit/band_hopping/test_band_hopping.cpp b/tests/unit/band_hopping/test_band_hopping.cpp new file mode 100644 index 00000000..6555b149 --- /dev/null +++ b/tests/unit/band_hopping/test_band_hopping.cpp @@ -0,0 +1,52 @@ +#include <QtTest> + +#include "widgets/BandHopping.hpp" + +class TestBandHopping + : public QObject +{ + Q_OBJECT + +private: + Q_SLOT void empty_selection_returns_no_hop () + { + QCOMPARE (next_band_hop_index ({false, false, false}, 0), -1); + } + + Q_SLOT void single_selection_returns_same_entry () + { + std::vector<bool> const selected {false, true, false}; + + QCOMPARE (next_band_hop_index (selected, 0), 1); + QCOMPARE (next_band_hop_index (selected, 1), 1); + QCOMPARE (next_band_hop_index (selected, 2), 1); + } + + Q_SLOT void multiple_selections_advance_from_start () + { + std::vector<bool> const selected {false, true, false, true}; + + QCOMPARE (next_band_hop_index (selected, 0), 1); + QCOMPARE (next_band_hop_index (selected, 2), 3); + } + + Q_SLOT void selection_wraps_after_end () + { + std::vector<bool> const selected {true, false, false, true}; + + QCOMPARE (next_band_hop_index (selected, 4), 0); + QCOMPARE (next_band_hop_index (selected, 5), 3); + } + + Q_SLOT void start_index_normalizes_safely () + { + std::vector<bool> const selected {false, false, true}; + + QCOMPARE (next_band_hop_index (selected, -1), 2); + QCOMPARE (next_band_hop_index (selected, 8), 2); + } +}; + +QTEST_MAIN (TestBandHopping); + +#include "test_band_hopping.moc" 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" diff --git a/tests/unit/decoder_ipc/CMakeLists.txt b/tests/unit/decoder_ipc/CMakeLists.txt new file mode 100644 index 00000000..0d8c0083 --- /dev/null +++ b/tests/unit/decoder_ipc/CMakeLists.txt @@ -0,0 +1,42 @@ +if (APPLE) + add_library (test_decoder_ipc_fortran_probe STATIC decoder_ipc_fortran_probe.f90) + target_include_directories (test_decoder_ipc_fortran_probe PRIVATE ${CMAKE_SOURCE_DIR}/lib) + set (decoder_ipc_fortran_probe_sources) +else () + set (decoder_ipc_fortran_probe_sources decoder_ipc_fortran_probe.f90) +endif () + +add_executable (test_decoder_ipc_protocol + test_decoder_ipc_protocol.cpp + ${decoder_ipc_fortran_probe_sources} + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp + ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp +) +set_target_properties (test_decoder_ipc_protocol PROPERTIES LINKER_LANGUAGE CXX) +target_include_directories (test_decoder_ipc_protocol PRIVATE ${CMAKE_SOURCE_DIR}/lib) +if (APPLE) + target_link_libraries (test_decoder_ipc_protocol Qt5::Test test_decoder_ipc_fortran_probe) +else () + target_link_libraries (test_decoder_ipc_protocol Qt5::Test) +endif () +add_test (NAME test_decoder_ipc_protocol COMMAND test_decoder_ipc_protocol) + +add_executable (test_decoder_output_framer + test_decoder_output_framer.cpp + ${CMAKE_SOURCE_DIR}/DecoderOutputFramer.cpp + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp + ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp +) +target_include_directories (test_decoder_output_framer PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/lib +) +target_link_libraries (test_decoder_output_framer Qt5::Test) +add_test (NAME test_decoder_output_framer COMMAND test_decoder_output_framer) + +add_executable (test_decode_operating_context + test_decode_operating_context.cpp +) +target_include_directories (test_decode_operating_context PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_decode_operating_context Qt5::Test) +add_test (NAME test_decode_operating_context COMMAND test_decode_operating_context) diff --git a/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 b/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 new file mode 100644 index 00000000..c1304ee7 --- /dev/null +++ b/tests/unit/decoder_ipc/decoder_ipc_fortran_probe.f90 @@ -0,0 +1,23 @@ +subroutine decoder_ipc_fortran_probe(address, values) bind(C) + use, intrinsic :: iso_c_binding, only: c_ptr, c_f_pointer, c_int, c_sizeof + include 'jt9com.f90' + + type(c_ptr), value :: address + integer(c_int), intent(out) :: values(10) + type(shared_dec_data), pointer :: shared + + call c_f_pointer(address, shared) + values(1) = c_sizeof(shared%control) + values(2) = c_sizeof(shared%payload%params) + values(3) = c_sizeof(shared%payload) + values(4) = c_sizeof(shared) + values(5) = DECODER_IPC_VERSION + values(6) = DECODER_IPC_IDLE + values(7) = DECODER_IPC_READY + values(8) = DECODER_IPC_DECODING + values(9) = DECODER_IPC_COMPLETE + values(10) = DECODER_IPC_SHUTDOWN + + shared%control%generation = shared%control%generation + 1 + shared%payload%id2(1) = 1234 +end subroutine decoder_ipc_fortran_probe diff --git a/tests/unit/decoder_ipc/test_decode_operating_context.cpp b/tests/unit/decoder_ipc/test_decode_operating_context.cpp new file mode 100644 index 00000000..0380434d --- /dev/null +++ b/tests/unit/decoder_ipc/test_decode_operating_context.cpp @@ -0,0 +1,152 @@ +#include <QtTest> + +#include "DecodeOperatingContext.hpp" + +class TestDecodeOperatingContext final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void identityMatchesEquivalentContext (); + void sequenceStartIsAttributionOnly (); + void identityChangeMakesContextObsolete_data (); + void identityChangeMakesContextObsolete (); + void ft8PendingIdentityChangeMakesSnapshotObsolete_data (); + void ft8PendingIdentityChangeMakesSnapshotObsolete (); + void ft8PendingIdentityRejectsOtherModes (); +}; + +namespace +{ + DecodeOperatingContext context () + { + DecodeOperatingContext result; + result.mode = "FT8"; + result.specOp = SpecialOperatingActivity::NONE; + result.periodFrequency = 14074000; + result.band = "20m"; + result.sequenceStart = QDateTime::fromString ("2026-07-26T12:00:00Z", Qt::ISODate); + result.trPeriod = 15.0; + result.submode = 0; + result.diskData = false; + result.multithreadFt8 = true; + result.ft8DecoderStart = 1; + result.ft8ThreadCount = 4; + result.decodeDepth = 3; + result.ft8Cycles = 3; + result.ft8Sensitivity = 3; + result.ft8RxFrequencySensitivity = 3; + result.decodeLowFrequency = 200; + result.decodeHighFrequency = 3000; + result.ft8WideDxCallSearch = true; + result.hideFt8DuplicateMessages = true; + result.ft8ApEnabled = true; + result.superFox = false; + result.myCall = "K1ABC"; + return result; + } +} + +void TestDecodeOperatingContext::identityMatchesEquivalentContext () +{ + auto const captured = context (); + QVERIFY (captured.hasSameDecodeIdentity (context ())); +} + +void TestDecodeOperatingContext::sequenceStartIsAttributionOnly () +{ + auto captured = context (); + auto current = context (); + current.sequenceStart = current.sequenceStart.addSecs (15); + + QVERIFY (captured.hasSameDecodeIdentity (current)); +} + +void TestDecodeOperatingContext::identityChangeMakesContextObsolete_data () +{ + QTest::addColumn<QString> ("field"); + QTest::newRow ("mode") << QString {"mode"}; + QTest::newRow ("special operation") << QString {"special operation"}; + QTest::newRow ("frequency") << QString {"frequency"}; + QTest::newRow ("band") << QString {"band"}; + QTest::newRow ("TR period") << QString {"TR period"}; + QTest::newRow ("submode") << QString {"submode"}; + QTest::newRow ("disk data") << QString {"disk data"}; + QTest::newRow ("multithread FT8") << QString {"multithread FT8"}; + QTest::newRow ("FT8 start") << QString {"FT8 start"}; + QTest::newRow ("SuperFox") << QString {"SuperFox"}; + QTest::newRow ("callsign") << QString {"callsign"}; +} + +void TestDecodeOperatingContext::identityChangeMakesContextObsolete () +{ + QFETCH (QString, field); + auto captured = context (); + auto current = context (); + + if (field == "mode") current.mode = "FT4"; + else if (field == "special operation") current.specOp = SpecialOperatingActivity::HOUND; + else if (field == "frequency") ++current.periodFrequency; + else if (field == "band") current.band = "17m"; + else if (field == "TR period") current.trPeriod = 30.0; + else if (field == "submode") ++current.submode; + else if (field == "disk data") current.diskData = true; + else if (field == "multithread FT8") current.multithreadFt8 = false; + else if (field == "FT8 start") ++current.ft8DecoderStart; + else if (field == "SuperFox") current.superFox = true; + else if (field == "callsign") current.myCall = "K1XYZ"; + + QVERIFY (!captured.hasSameDecodeIdentity (current)); +} + +void TestDecodeOperatingContext::ft8PendingIdentityChangeMakesSnapshotObsolete_data () +{ + QTest::addColumn<QString> ("field"); + QTest::newRow ("FT8 threads") << QString {"FT8 threads"}; + QTest::newRow ("decode depth") << QString {"decode depth"}; + QTest::newRow ("FT8 cycles") << QString {"FT8 cycles"}; + QTest::newRow ("FT8 sensitivity") << QString {"FT8 sensitivity"}; + QTest::newRow ("FT8 RX sensitivity") << QString {"FT8 RX sensitivity"}; + QTest::newRow ("decode low frequency") << QString {"decode low frequency"}; + QTest::newRow ("decode high frequency") << QString {"decode high frequency"}; + QTest::newRow ("FT8 wide DX search") << QString {"FT8 wide DX search"}; + QTest::newRow ("hide FT8 duplicates") << QString {"hide FT8 duplicates"}; + QTest::newRow ("FT8 AP") << QString {"FT8 AP"}; +} + +void TestDecodeOperatingContext::ft8PendingIdentityChangeMakesSnapshotObsolete () +{ + QFETCH (QString, field); + auto captured = context (); + auto current = context (); + + if (field == "FT8 threads") ++current.ft8ThreadCount; + else if (field == "decode depth") ++current.decodeDepth; + else if (field == "FT8 cycles") ++current.ft8Cycles; + else if (field == "FT8 sensitivity") ++current.ft8Sensitivity; + else if (field == "FT8 RX sensitivity") ++current.ft8RxFrequencySensitivity; + else if (field == "decode low frequency") ++current.decodeLowFrequency; + else if (field == "decode high frequency") ++current.decodeHighFrequency; + else if (field == "FT8 wide DX search") current.ft8WideDxCallSearch = false; + else if (field == "hide FT8 duplicates") current.hideFt8DuplicateMessages = false; + else if (field == "FT8 AP") current.ft8ApEnabled = false; + + QVERIFY (captured.hasSameDecodeIdentity (current)); + QVERIFY (!captured.hasSameFt8PendingIdentity (current)); +} + +void TestDecodeOperatingContext::ft8PendingIdentityRejectsOtherModes () +{ + auto captured = context (); + auto current = context (); + captured.mode = "Q65"; + current.mode = "Q65"; + ++current.ft8ThreadCount; + + QVERIFY (captured.hasSameDecodeIdentity (current)); + QVERIFY (!captured.hasSameFt8PendingIdentity (current)); +} + +QTEST_GUILESS_MAIN (TestDecodeOperatingContext) + +#include "test_decode_operating_context.moc" diff --git a/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp b/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp new file mode 100644 index 00000000..85a414fa --- /dev/null +++ b/tests/unit/decoder_ipc/test_decoder_ipc_protocol.cpp @@ -0,0 +1,396 @@ +#include <QtTest> + +#include <cstring> +#include <limits> +#include <memory> +#include <thread> +#include <vector> + +#include "DecoderIpc.hpp" +#include "lib/decoder_ipc_control.h" + +extern "C" +{ + void decoder_ipc_fortran_probe (void *, int[10]); +} + +class TestDecoderIpcProtocol final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void layoutMatchesFortran (); + void sharedMemorySizeAllowsPlatformRounding (); + void publicationAndClaimValidateControl (); + void compactFt8MtdPublicationCopiesRequiredPayload (); + void compactFt8MtdPublicationRejectsInvalidRequests (); + void transitionsRequireMatchingGeneration (); + void sharedProgressTracksActiveGeneration (); + void delayedCompletionCannotClobberNextRequest (); + void compatibleShutdownReleasesWorkers (); + void shutdownReplacesAnyState_data (); + void shutdownReplacesAnyState (); + void generationWrapsWithoutUsingZero (); + void startMarkerParsing (); + void startMarkerRejections_data (); + void startMarkerRejections (); + void completionMarkerParsing (); + void completionMarkerRejections_data (); + void completionMarkerRejections (); +}; + +void TestDecoderIpcProtocol::layoutMatchesFortran () +{ + struct CompatibleSharedData + { + int ipc[4]; + dec_data_t payload; + }; + + QCOMPARE (sizeof (decoder_ipc_control_t), size_t {16}); + QCOMPARE (offsetof (decoder_ipc_control_t, state), size_t {4}); + QCOMPARE (offsetof (shared_dec_data_t, payload), size_t {16}); + QCOMPARE (sizeof (shared_dec_data_t), + sizeof (decoder_ipc_control_t) + sizeof (dec_data_t)); + QCOMPARE (sizeof (shared_dec_data_t), sizeof (CompatibleSharedData)); + QCOMPARE (offsetof (CompatibleSharedData, ipc) + sizeof (int), + offsetof (decoder_ipc_control_t, state)); + QCOMPARE (offsetof (CompatibleSharedData, payload), + offsetof (shared_dec_data_t, payload)); + + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + shared->control.generation = 41; + int values[10] {}; + decoder_ipc_fortran_probe (shared.get (), values); + + QCOMPARE (values[0], static_cast<int> (sizeof (decoder_ipc_control_t))); + QCOMPARE (values[1], static_cast<int> (sizeof (decoder_params_t))); + QCOMPARE (values[2], static_cast<int> (sizeof (dec_data_t))); + QCOMPARE (values[3], static_cast<int> (sizeof (shared_dec_data_t))); + QCOMPARE (values[4], int {DECODER_IPC_VERSION}); + QCOMPARE (values[5], int {DECODER_IPC_IDLE}); + QCOMPARE (values[6], int {DECODER_IPC_READY}); + QCOMPARE (values[7], int {DECODER_IPC_DECODING}); + QCOMPARE (values[8], int {DECODER_IPC_COMPLETE}); + QCOMPARE (values[9], int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (shared->control.generation, 42); + QCOMPARE (shared->payload.d2[0], short {1234}); +} + +void TestDecoderIpcProtocol::sharedMemorySizeAllowsPlatformRounding () +{ + auto const required = static_cast<qint64> (sizeof (shared_dec_data_t)); + auto const shutdownRequired = static_cast<qint64> ( + offsetof (decoder_ipc_control_t, progress)); + QVERIFY (!DecoderIpc::hasShutdownControlSize (shutdownRequired - 1)); + QVERIFY (DecoderIpc::hasShutdownControlSize (shutdownRequired)); + QVERIFY (!DecoderIpc::hasUsableSize (required - 1)); + QVERIFY (DecoderIpc::hasUsableSize (required)); + QVERIFY (DecoderIpc::hasUsableSize (required + 80)); + + int compatibleControl[3] {17, DECODER_IPC_DECODING, 0}; + DecoderIpc::shutdownControl (compatibleControl); + QCOMPARE (compatibleControl[0], 17); + QCOMPARE (compatibleControl[1], int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (compatibleControl[2], 1); +} + +void TestDecoderIpcProtocol::publicationAndClaimValidateControl () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<dec_data_t> payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + + QVERIFY (!DecoderIpc::publish (*shared, *payload, false, 0)); + QCOMPARE (shared->control.state, int {DECODER_IPC_IDLE}); + + shared->control.version = DECODER_IPC_VERSION + 1; + QVERIFY (!DecoderIpc::publish (*shared, *payload, false, 1)); + QCOMPARE (shared->control.state, int {DECODER_IPC_IDLE}); + + shared->control.version = DECODER_IPC_VERSION; + shared->control.generation = 0; + shared->control.state = DECODER_IPC_READY; + qint32 generation {0}; + QVERIFY (!DecoderIpc::claim (*shared, generation)); + QCOMPARE (shared->control.state, int {DECODER_IPC_READY}); +} + +void TestDecoderIpcProtocol::compactFt8MtdPublicationCopiesRequiredPayload () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<DecoderIpc::Ft8MtdPayload> payload {new DecoderIpc::Ft8MtdPayload}; + DecoderIpc::initialize (*shared); + shared->payload.ss[0] = 3.5F; + shared->payload.savg[0] = 4.5F; + shared->payload.sred[0] = 5.5F; + shared->payload.d2[DecoderIpc::Ft8SampleCount] = 61; + shared->payload.d2[NTMAX * RX_SAMPLE_RATE - 1] = 62; + payload->params.nmode = 8; + payload->params.lmultift8 = true; + payload->params.nutc = 123456; + payload->samples.front () = 17; + payload->samples.back () = 29; + + QVERIFY (DecoderIpc::publishFt8Mtd (*shared, *payload, 7)); + + QCOMPARE (shared->control.state, int {DECODER_IPC_READY}); + QCOMPARE (shared->control.generation, 7); + QCOMPARE (shared->payload.params.nutc, 123456); + QCOMPARE (shared->payload.d2[0], short {17}); + QCOMPARE (shared->payload.d2[DecoderIpc::Ft8SampleCount - 1], short {29}); + QCOMPARE (shared->payload.d2[DecoderIpc::Ft8SampleCount], short {61}); + QCOMPARE (shared->payload.d2[NTMAX * RX_SAMPLE_RATE - 1], short {62}); + QCOMPARE (shared->payload.ss[0], 3.5F); + QCOMPARE (shared->payload.savg[0], 4.5F); + QCOMPARE (shared->payload.sred[0], 5.5F); +} + +void TestDecoderIpcProtocol::compactFt8MtdPublicationRejectsInvalidRequests () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<DecoderIpc::Ft8MtdPayload> payload {new DecoderIpc::Ft8MtdPayload}; + DecoderIpc::initialize (*shared); + shared->payload.params.nutc = 111111; + shared->payload.d2[0] = 11; + payload->params.nmode = 9; + payload->params.lmultift8 = true; + payload->params.nutc = 222222; + payload->samples[0] = 22; + + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 1)); + QCOMPARE (shared->control.state, int {DECODER_IPC_IDLE}); + QCOMPARE (shared->payload.params.nutc, 111111); + QCOMPARE (shared->payload.d2[0], short {11}); + + payload->params.nmode = 8; + payload->params.lmultift8 = false; + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 1)); + QCOMPARE (shared->control.state, int {DECODER_IPC_IDLE}); + QCOMPARE (shared->payload.params.nutc, 111111); + QCOMPARE (shared->payload.d2[0], short {11}); + + payload->params.lmultift8 = true; + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 0)); + shared->control.version = DECODER_IPC_VERSION + 1; + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 1)); + shared->control.version = DECODER_IPC_VERSION; + QVERIFY (DecoderIpc::publishFt8Mtd (*shared, *payload, 1)); + payload->params.nutc = 333333; + payload->samples[0] = 33; + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 2)); + QCOMPARE (shared->payload.params.nutc, 222222); + QCOMPARE (shared->payload.d2[0], short {22}); + + qint32 generation {0}; + QVERIFY (DecoderIpc::claim (*shared, generation)); + QVERIFY (!DecoderIpc::publishFt8Mtd (*shared, *payload, 2)); + QCOMPARE (shared->payload.params.nutc, 222222); + QCOMPARE (shared->payload.d2[0], short {22}); +} + +void TestDecoderIpcProtocol::transitionsRequireMatchingGeneration () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<dec_data_t> payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + payload->params.nutc = 123456; + payload->d2[0] = 17; + + QVERIFY (DecoderIpc::publish (*shared, *payload, true, 7)); + QCOMPARE (shared->control.state, int {DECODER_IPC_READY}); + QCOMPARE (shared->control.generation, 7); + QCOMPARE (shared->payload.params.nutc, 123456); + QCOMPARE (shared->payload.d2[0], short {17}); + + payload->params.nutc = 654321; + payload->d2[0] = 99; + QVERIFY (!DecoderIpc::publish (*shared, *payload, true, 8)); + QCOMPARE (shared->payload.params.nutc, 123456); + QCOMPARE (shared->payload.d2[0], short {17}); + + qint32 claimed {0}; + QVERIFY (DecoderIpc::claim (*shared, claimed)); + QCOMPARE (claimed, qint32 {7}); + QVERIFY (!DecoderIpc::publish (*shared, *payload, true, 8)); + QCOMPARE (shared->payload.params.nutc, 123456); + QCOMPARE (shared->payload.d2[0], short {17}); + QVERIFY (!DecoderIpc::consume (*shared, 6)); + QCOMPARE (shared->control.state, int {DECODER_IPC_DECODING}); + QVERIFY (!DecoderIpc::consume (*shared, 7)); + QCOMPARE (shared->control.state, int {DECODER_IPC_DECODING}); + QVERIFY (DecoderIpc::finish (*shared, 7)); + QVERIFY (DecoderIpc::consume (*shared, 7)); + QCOMPARE (shared->control.state, int {DECODER_IPC_IDLE}); + QVERIFY (!DecoderIpc::consume (*shared, 7)); + + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 8)); + QCOMPARE (shared->payload.params.nutc, 654321); + QCOMPARE (shared->control.generation, 8); + QCOMPARE (shared->payload.d2[0], short {17}); + QVERIFY (!DecoderIpc::consume (*shared, 8)); + DecoderIpc::shutdown (*shared); +} + +void TestDecoderIpcProtocol::sharedProgressTracksActiveGeneration () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<dec_data_t> payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 7)); + qint32 claimed {0}; + QVERIFY (DecoderIpc::claim (*shared, claimed)); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {0}); + + decoder_ipc_progress_bind (&shared->control.generation, + &shared->control.state, + &shared->control.version, + &shared->control.progress); + decoder_ipc_progress_report (6); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {0}); + std::vector<std::thread> workers; + for (int worker = 0; worker < 4; ++worker) + { + workers.emplace_back ([] { + for (int report = 0; report < 1000; ++report) + { + decoder_ipc_progress_report (7); + } + }); + } + for (auto& worker: workers) worker.join (); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {4000}); + + QVERIFY (DecoderIpc::finish (*shared, 7)); + decoder_ipc_progress_report (7); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {4000}); + QVERIFY (DecoderIpc::consume (*shared, 7)); + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 8)); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {0}); + + decoder_ipc_progress_unbind (); + decoder_ipc_progress_report (8); + QCOMPARE (DecoderIpc::progress (*shared), qint32 {0}); +} + +void TestDecoderIpcProtocol::delayedCompletionCannotClobberNextRequest () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<dec_data_t> payload {new dec_data_t}; + DecoderIpc::initialize (*shared); + payload->params = {}; + + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 10)); + qint32 claimed {0}; + QVERIFY (DecoderIpc::claim (*shared, claimed)); + QVERIFY (DecoderIpc::finish (*shared, 10)); + QVERIFY (DecoderIpc::consume (*shared, 10)); + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 11)); + + QVERIFY (!DecoderIpc::finish (*shared, 10)); + QCOMPARE (shared->control.generation, 11); + QCOMPARE (shared->control.state, int {DECODER_IPC_READY}); + + DecoderIpc::shutdown (*shared); + QCOMPARE (shared->control.state, int {DECODER_IPC_SHUTDOWN}); +} + +void TestDecoderIpcProtocol::compatibleShutdownReleasesWorkers () +{ + decoder_ipc_control_t control {17, 0, DECODER_IPC_VERSION, 4}; + DecoderIpc::shutdown (control); + + QCOMPARE (control.generation, 17); + QCOMPARE (control.state, int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (control.version, 1); + QCOMPARE (control.progress, 4); +} + +void TestDecoderIpcProtocol::shutdownReplacesAnyState_data () +{ + QTest::addColumn<int> ("state"); + QTest::newRow ("idle") << int {DECODER_IPC_IDLE}; + QTest::newRow ("ready") << int {DECODER_IPC_READY}; + QTest::newRow ("decoding") << int {DECODER_IPC_DECODING}; + QTest::newRow ("complete") << int {DECODER_IPC_COMPLETE}; +} + +void TestDecoderIpcProtocol::shutdownReplacesAnyState () +{ + QFETCH (int, state); + decoder_ipc_control_t control {17, state, DECODER_IPC_VERSION, 0}; + + DecoderIpc::shutdown (control); + + QCOMPARE (control.generation, 17); + QCOMPARE (control.state, int {DECODER_IPC_SHUTDOWN}); + QCOMPARE (control.version, 1); +} + +void TestDecoderIpcProtocol::generationWrapsWithoutUsingZero () +{ + QCOMPARE (DecoderIpc::nextGeneration (0), qint32 {1}); + QCOMPARE (DecoderIpc::nextGeneration (-1), qint32 {1}); + QCOMPARE (DecoderIpc::nextGeneration (41), qint32 {42}); + QCOMPARE (DecoderIpc::nextGeneration (std::numeric_limits<qint32>::max ()), qint32 {1}); +} + +void TestDecoderIpcProtocol::startMarkerParsing () +{ + qint32 generation {0}; + QVERIFY (DecoderIpc::parseStart ("<DecodeStarted> gen=42\r\n", &generation)); + QCOMPARE (generation, qint32 {42}); +} + +void TestDecoderIpcProtocol::startMarkerRejections_data () +{ + QTest::addColumn<QByteArray> ("line"); + QTest::newRow ("embedded") << QByteArray {"noise <DecodeStarted> gen=42"}; + QTest::newRow ("missing generation") << QByteArray {"<DecodeStarted>"}; + QTest::newRow ("zero generation") << QByteArray {"<DecodeStarted> gen=0"}; + QTest::newRow ("negative generation") << QByteArray {"<DecodeStarted> gen=-1"}; + QTest::newRow ("overflow generation") << QByteArray {"<DecodeStarted> gen=2147483648"}; + QTest::newRow ("trailing garbage") << QByteArray {"<DecodeStarted> gen=42 extra"}; +} + +void TestDecoderIpcProtocol::startMarkerRejections () +{ + QFETCH (QByteArray, line); + qint32 generation {0}; + QVERIFY (!DecoderIpc::parseStart (line, &generation)); +} + +void TestDecoderIpcProtocol::completionMarkerParsing () +{ + DecoderIpc::Completion completion {}; + QVERIFY (DecoderIpc::parseCompletion ( + "<DecodeFinished> 2 17 123456 gen=42\r\n", &completion)); + QCOMPARE (completion.synchronized, qint32 {2}); + QCOMPARE (completion.decoded, qint32 {17}); + QCOMPARE (completion.average, qint32 {123456}); + QCOMPARE (completion.generation, qint32 {42}); +} + +void TestDecoderIpcProtocol::completionMarkerRejections_data () +{ + QTest::addColumn<QByteArray> ("line"); + QTest::newRow ("embedded") << QByteArray {"noise <DecodeFinished> 2 17 123456 gen=42"}; + QTest::newRow ("legacy") << QByteArray {"<DecodeFinished> 2 17 123456"}; + QTest::newRow ("zero generation") << QByteArray {"<DecodeFinished> 2 17 123456 gen=0"}; + QTest::newRow ("negative generation") << QByteArray {"<DecodeFinished> 2 17 123456 gen=-1"}; + QTest::newRow ("overflow generation") << QByteArray {"<DecodeFinished> 2 17 123456 gen=2147483648"}; + QTest::newRow ("overflow field") << QByteArray {"<DecodeFinished>**** 17 123456 gen=42"}; + QTest::newRow ("trailing garbage") << QByteArray {"<DecodeFinished> 2 17 123456 gen=42 extra"}; +} + +void TestDecoderIpcProtocol::completionMarkerRejections () +{ + QFETCH (QByteArray, line); + DecoderIpc::Completion completion {}; + QVERIFY (!DecoderIpc::parseCompletion (line, &completion)); +} + +QTEST_GUILESS_MAIN (TestDecoderIpcProtocol) + +#include "test_decoder_ipc_protocol.moc" diff --git a/tests/unit/decoder_ipc/test_decoder_output_framer.cpp b/tests/unit/decoder_ipc/test_decoder_output_framer.cpp new file mode 100644 index 00000000..5fbb2698 --- /dev/null +++ b/tests/unit/decoder_ipc/test_decoder_output_framer.cpp @@ -0,0 +1,281 @@ +#include <QtTest> + +#include <QCoreApplication> +#include <QBuffer> +#include <QFile> +#include <QProcess> +#include <QVector> + +#include <cstdio> +#include <memory> + +#ifdef Q_OS_WIN +#include <fcntl.h> +#include <io.h> +#endif + +#include "DecoderOutputFramer.hpp" + +namespace +{ + char const fixtureOption[] = "--decoder-output-fixture"; + + int runFixture (QStringList const& arguments) + { + if (arguments.size () < 3) return 2; + + auto const payload = QByteArray::fromBase64 (arguments[2].toLatin1 ()); +#ifdef Q_OS_WIN + if (-1 == _setmode (_fileno (stdout), _O_BINARY)) return 3; +#endif + QFile output; + if (!output.open (stdout, QIODevice::WriteOnly, QFileDevice::DontCloseHandle)) + { + return 4; + } + if (output.write (payload) != payload.size () || !output.flush ()) return 5; + return arguments.contains ("--hold") ? QCoreApplication::exec () : 0; + } +} + +class TestDecoderOutputFramer final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void rejectedRecordDoesNotStopDrain (); + void staleFramesRemainAssociatedWithTheirGeneration (); + void completeStateWaitsForStdoutDrain (); + void recordTerminatorsArePreserved (); + void malformedFramesAreReported (); + void killedFrameCanBeReplaced (); +}; + +void TestDecoderOutputFramer::rejectedRecordDoesNotStopDrain () +{ + QByteArray const output { + "<DecodeStarted> gen=7\n" + "record rejected by policy\n" + "<DecodeFinished> 2 17 123456 gen=7\n"}; + DecoderOutputFramer framer; + int started {0}; + int records {0}; + int finished {0}; + DecoderOutputFramer::EventHandler handler { + [&] (DecoderOutputFramer::Event const& event) { + if (DecoderOutputFramer::EventType::Started == event.type) ++started; + if (DecoderOutputFramer::EventType::Record == event.type) + { + ++records; + return; + } + if (DecoderOutputFramer::EventType::Finished == event.type) ++finished; + }}; + + QProcess process; + connect (&process, &QProcess::readyReadStandardOutput, this, [&] { + framer.drain (process, handler); + }); + process.start (QCoreApplication::applicationFilePath (), + {fixtureOption, QString::fromLatin1 (output.toBase64 ())}); + QVERIFY (process.waitForStarted ()); + QVERIFY (process.waitForFinished ()); + framer.drain (process, handler); + + QCOMPARE (started, 1); + QCOMPARE (records, 1); + QCOMPARE (finished, 1); + QCOMPARE (framer.currentGeneration (), qint32 {0}); +} + +void TestDecoderOutputFramer::staleFramesRemainAssociatedWithTheirGeneration () +{ + QByteArray const output { + "<DecodeStarted> gen=7\n" + "stale record\n" + "<DecodeFinished> 0 0 0 gen=7\n" + "<DecodeStarted> gen=8\n" + "current record\n" + "<DecodeFinished> 0 1 0 gen=8\n"}; + DecoderOutputFramer framer; + QVector<qint32> recordGenerations; + QVector<QByteArray> acceptedRecords; + QVector<qint32> finishedGenerations; + qint32 const activeGeneration {8}; + DecoderOutputFramer::EventHandler handler { + [&] (DecoderOutputFramer::Event const& event) { + if (DecoderOutputFramer::EventType::Record == event.type) + { + recordGenerations.append (event.generation); + if (activeGeneration == event.generation) + { + acceptedRecords.append (event.rawLine); + } + } + else if (DecoderOutputFramer::EventType::Finished == event.type) + { + finishedGenerations.append (event.generation); + } + }}; + + QProcess process; + process.start (QCoreApplication::applicationFilePath (), + {fixtureOption, QString::fromLatin1 (output.toBase64 ())}); + QVERIFY (process.waitForStarted ()); + QVERIFY (process.waitForFinished ()); + framer.drain (process, handler); + + QCOMPARE (recordGenerations, QVector<qint32> ({7, 8})); + QCOMPARE (acceptedRecords, QVector<QByteArray> ({"current record\n"})); + QCOMPARE (finishedGenerations, QVector<qint32> ({7, 8})); +} + +void TestDecoderOutputFramer::completeStateWaitsForStdoutDrain () +{ + std::unique_ptr<shared_dec_data_t> shared {new shared_dec_data_t}; + std::unique_ptr<dec_data_t> payload {new dec_data_t {}}; + DecoderIpc::initialize (*shared); + QVERIFY (DecoderIpc::publish (*shared, *payload, false, 21)); + qint32 generation {0}; + QVERIFY (DecoderIpc::claim (*shared, generation)); + QVERIFY (DecoderIpc::finish (*shared, generation)); + + QByteArray output { + "<DecodeStarted> gen=21\n" + "buffered record\n" + "<DecodeFinished> 0 1 0 gen=21\n"}; + QBuffer buffer {&output}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + QCOMPARE (DecoderIpc::state (*shared), qint32 {DECODER_IPC_COMPLETE}); + + DecoderOutputFramer framer; + int records {0}; + bool consumed {false}; + framer.drain (buffer, [&] (DecoderOutputFramer::Event const& event) { + if (DecoderOutputFramer::EventType::Record == event.type) ++records; + if (DecoderOutputFramer::EventType::Finished == event.type) + { + consumed = DecoderIpc::consume (*shared, event.generation); + } + }); + + QCOMPARE (records, 1); + QVERIFY (consumed); + QCOMPARE (DecoderIpc::state (*shared), qint32 {DECODER_IPC_IDLE}); +} + +void TestDecoderOutputFramer::recordTerminatorsArePreserved () +{ + QByteArray const output { + "<DecodeStarted> gen=9\r\n" + "first record\r\n" + "second record\n" + "<DecodeFinished> 0 2 0 gen=9\r\n"}; + DecoderOutputFramer framer; + QVector<QByteArray> records; + + QProcess process; + process.start (QCoreApplication::applicationFilePath (), + {fixtureOption, QString::fromLatin1 (output.toBase64 ())}); + QVERIFY (process.waitForStarted ()); + QVERIFY (process.waitForFinished ()); + framer.drain (process, [&] (DecoderOutputFramer::Event const& event) { + if (DecoderOutputFramer::EventType::Record == event.type) + { + records.append (event.rawLine); + } + }); + + QCOMPARE (records, QVector<QByteArray> ({"first record\r\n", + "second record\n"})); +} + +void TestDecoderOutputFramer::malformedFramesAreReported () +{ + QByteArray output { + "unframed record\n" + "<DecodeStarted> gen=0\n" + "<DecodeStarted> gen=14\n" + "<DecodeFinished> 0 0 0 gen=15\n" + "<DecodeFinished> 0 0 0 gen=14\n"}; + QBuffer buffer {&output}; + QVERIFY (buffer.open (QIODevice::ReadOnly)); + + DecoderOutputFramer framer; + QVector<DecoderOutputFramer::EventType> eventTypes; + framer.drain (buffer, [&] (DecoderOutputFramer::Event const& event) { + eventTypes.append (event.type); + }); + + QCOMPARE (eventTypes, QVector<DecoderOutputFramer::EventType> ({ + DecoderOutputFramer::EventType::Malformed, + DecoderOutputFramer::EventType::Malformed, + DecoderOutputFramer::EventType::Started, + DecoderOutputFramer::EventType::Malformed, + DecoderOutputFramer::EventType::Finished})); + QCOMPARE (framer.currentGeneration (), qint32 {0}); +} + +void TestDecoderOutputFramer::killedFrameCanBeReplaced () +{ + DecoderOutputFramer framer; + QVector<DecoderOutputFramer::Event> events; + DecoderOutputFramer::EventHandler handler { + [&] (DecoderOutputFramer::Event const& event) {events.append (event);}}; + + QProcess abandoned; + connect (&abandoned, &QProcess::readyReadStandardOutput, this, [&] { + framer.drain (abandoned, handler); + }); + QByteArray const abandonedOutput { + "<DecodeStarted> gen=11\n" + "abandoned record\n"}; + abandoned.start (QCoreApplication::applicationFilePath (), + {fixtureOption, + QString::fromLatin1 (abandonedOutput.toBase64 ()), + "--hold"}); + QVERIFY (abandoned.waitForStarted ()); + QVERIFY (abandoned.waitForReadyRead ()); + framer.drain (abandoned, handler); + QCOMPARE (framer.currentGeneration (), qint32 {11}); + + abandoned.kill (); + QTRY_COMPARE_WITH_TIMEOUT (abandoned.state (), QProcess::NotRunning, 2000); + framer.reset (); + events.clear (); + + QByteArray const replacementOutput { + "<DecodeStarted> gen=12\n" + "replacement record\n" + "<DecodeFinished> 0 1 0 gen=12\n"}; + QProcess replacement; + connect (&replacement, &QProcess::readyReadStandardOutput, this, [&] { + framer.drain (replacement, handler); + }); + replacement.start (QCoreApplication::applicationFilePath (), + {fixtureOption, + QString::fromLatin1 (replacementOutput.toBase64 ())}); + QVERIFY (replacement.waitForStarted ()); + QVERIFY (replacement.waitForFinished ()); + framer.drain (replacement, handler); + + QCOMPARE (events.size (), 3); + QCOMPARE (events[0].type, DecoderOutputFramer::EventType::Started); + QCOMPARE (events[0].generation, qint32 {12}); + QCOMPARE (events[1].type, DecoderOutputFramer::EventType::Record); + QCOMPARE (events[1].rawLine, QByteArray {"replacement record\n"}); + QCOMPARE (events[2].type, DecoderOutputFramer::EventType::Finished); + QCOMPARE (events[2].generation, qint32 {12}); +} + +int main (int argc, char ** argv) +{ + QCoreApplication application {argc, argv}; + auto const arguments = application.arguments (); + if (arguments.contains (fixtureOption)) return runFixture (arguments); + + TestDecoderOutputFramer test; + return QTest::qExec (&test, argc, argv); +} + +#include "test_decoder_output_framer.moc" diff --git a/tests/unit/echo/CMakeLists.txt b/tests/unit/echo/CMakeLists.txt new file mode 100644 index 00000000..e526c873 --- /dev/null +++ b/tests/unit/echo/CMakeLists.txt @@ -0,0 +1,16 @@ +add_executable (test_echo_morse test_echo_morse.f90) +wsjt_link_common_fortran (test_echo_morse) + +add_test (NAME test_echo_morse COMMAND test_echo_morse) + +add_executable (test_avecho_disk_metadata test_avecho_disk_metadata.f90) +wsjt_link_common_fortran (test_avecho_disk_metadata) + +add_test (NAME test_avecho_disk_metadata COMMAND test_avecho_disk_metadata) +set_tests_properties (test_avecho_disk_metadata PROPERTIES + PASS_REGULAR_EXPRESSION "Echo disk metadata test passed") + +add_executable (test_avecho_silence test_avecho_silence.f90) +wsjt_link_common_fortran (test_avecho_silence) + +add_test (NAME test_avecho_silence COMMAND test_avecho_silence) diff --git a/tests/unit/echo/test_avecho_disk_metadata.f90 b/tests/unit/echo/test_avecho_disk_metadata.f90 new file mode 100644 index 00000000..5885ae6b --- /dev/null +++ b/tests/unit/echo/test_avecho_disk_metadata.f90 @@ -0,0 +1,52 @@ +program test_avecho_disk_metadata + + implicit none + + integer, parameter :: ntx=6*4096 + integer*2 id2(ntx+4096) + integer*4 itone(6) + integer idir,nauto,navg,ndf,ndop,ndop_total,nfrit,nqual + integer nclearave,nsum + real db_err,dfreq,f1,fspread_self,fspread_dx,snrdb,width,xlevel + real blue(4096),red(4096) + logical*1 disk_data,echo_call + character*6 rxcall,txcall + common/echocom/nclearave,nsum,blue,red + common/echocom2/fspread_self,fspread_dx + + id2=0 + id2(16:ntx)=1 + itone=0 + ndop_total=0 + ndop=0 + nfrit=10000 + f1=1500. + width=1. + ndf=-999 + idir=1 + call save_echo_params(ndop_total,ndop,nfrit,f1,width,ndf,itone,id2,idir) + + ndf=0 + idir=-1 + call save_echo_params(ndop_total,ndop,nfrit,f1,width,ndf,itone,id2,idir) + if(ndf.ne.-999) error stop 1 + + nauto=0 + navg=1 + nqual=0 + nclearave=1 + nsum=0 + fspread_self=1. + fspread_dx=1. + disk_data=.true. + echo_call=.false. + txcall=' ' + rxcall='BADBAD' + + call avecho(id2,ndop,nfrit,nauto,navg,nqual,f1,xlevel,snrdb,db_err,dfreq, & + width,disk_data,echo_call,txcall,rxcall) + if(rxcall.ne.' ') error stop 2 + + print*,'Echo disk metadata test passed' + +end program test_avecho_disk_metadata diff --git a/tests/unit/echo/test_avecho_silence.f90 b/tests/unit/echo/test_avecho_silence.f90 new file mode 100644 index 00000000..e0da549a --- /dev/null +++ b/tests/unit/echo/test_avecho_silence.f90 @@ -0,0 +1,53 @@ +program test_avecho_silence + + use, intrinsic :: ieee_arithmetic + implicit none + + integer, parameter :: ntx=6*4096 + integer*2 id2(ntx+4096) + integer nauto,navg,ndop,nfrit,nqual + integer nclearave,nsum + real blue(4096),db_err,dfreq,f1,fspread_dx,fspread_self + real red(4096),snrdb,width,xlevel + logical*1 disk_data,echo_call + character*6 rxcall,txcall + common/echocom/nclearave,nsum,blue,red + common/echocom2/fspread_self,fspread_dx + + id2=0 + ndop=0 + nfrit=0 + nauto=0 + navg=1 + nqual=-1 + nclearave=1 + nsum=0 + f1=1500. + fspread_self=1. + fspread_dx=1. + width=1. + disk_data=.false. + echo_call=.false. + txcall=' ' + rxcall='STALE!' + blue=1. + red=1. + + call avecho(id2,ndop,nfrit,nauto,navg,nqual,f1,xlevel,snrdb,db_err,dfreq, & + width,disk_data,echo_call,txcall,rxcall) + + if(.not.ieee_is_finite(xlevel)) error stop 1 + if(.not.ieee_is_finite(snrdb)) error stop 1 + if(.not.ieee_is_finite(db_err)) error stop 1 + if(.not.ieee_is_finite(dfreq)) error stop 1 + if(abs(xlevel+99.).gt.0.01) error stop 1 + if(abs(snrdb+99.).gt.0.01) error stop 1 + if(abs(dfreq).gt.0.01) error stop 1 + if(nqual.ne.0) error stop 1 + if(any(.not.ieee_is_finite(blue))) error stop 1 + if(any(.not.ieee_is_finite(red))) error stop 1 + if(any(blue.ne.0.) .or. any(red.ne.0.)) error stop 1 + + print*,'Silent Echo input test passed' + +end program test_avecho_silence diff --git a/tests/unit/echo/test_echo_morse.f90 b/tests/unit/echo/test_echo_morse.f90 new file mode 100644 index 00000000..fec95b3f --- /dev/null +++ b/tests/unit/echo/test_echo_morse.f90 @@ -0,0 +1,89 @@ +program test_echo_morse + + use, intrinsic :: ieee_arithmetic + use morse_encoder, only: encode_morse + implicit none + + integer cwsim_bits(500),ncwsim,ntests + + ntests=0 + call expect_valid_morse('0Az/ ',ntests) + call expect_invalid_morse('Z???',ntests) + call expect_valid_morse(repeat('E',59)//'T',ntests,246) + cwsim_bits=-1 + call encode_morse(repeat('0',22)//'EE',cwsim_bits,ncwsim) + call expect_valid_bits(cwsim_bits,ncwsim,ntests,498) + call expect_silent_wave(' ',ntests) + call expect_silent_wave('?',ntests) + call expect_signal_wave('O',ntests) + + write(*,1000) ntests +1000 format('Echo Morse tests passed: ',i0) + +contains + + subroutine expect_valid_morse(message,ntests,expected_n) + character(len=*), intent(in) :: message + integer, intent(inout) :: ntests + integer, intent(in), optional :: expected_n + integer bits(250),n + + bits=-1 + call morse(message,bits,n) + + call expect_valid_bits(bits,n,ntests,expected_n) + end subroutine expect_valid_morse + + subroutine expect_invalid_morse(message,ntests) + character(len=*), intent(in) :: message + integer, intent(inout) :: ntests + integer bits(250),n + + bits=-1 + call morse(message,bits,n) + + if(n.ne.0 .or. any(bits.ne.0)) error stop 1 + ntests=ntests+1 + end subroutine expect_invalid_morse + + subroutine expect_valid_bits(bits,n,ntests,expected_n) + integer, intent(in) :: bits(:),n + integer, intent(inout) :: ntests + integer, intent(in), optional :: expected_n + + if(n.le.0 .or. n.gt.size(bits)) error stop 1 + if(any(bits(1:n).lt.0) .or. any(bits(1:n).gt.1)) error stop 1 + if(present(expected_n)) then + if(n.ne.expected_n) error stop 1 + endif + ntests=ntests+1 + end subroutine expect_valid_bits + + subroutine expect_silent_wave(message,ntests) + character(len=*), intent(in) :: message + integer, intent(inout) :: ntests + real*4, allocatable :: wave(:) + + allocate(wave(98304)) + wave=1. + call gen_cw_wave(message,1500,wave) + + if(any(wave.ne.0.)) error stop 1 + ntests=ntests+1 + end subroutine expect_silent_wave + + subroutine expect_signal_wave(message,ntests) + character(len=*), intent(in) :: message + integer, intent(inout) :: ntests + real*4, allocatable :: wave(:) + + allocate(wave(98304)) + wave=0. + call gen_cw_wave(message,1500,wave) + + if(.not.all(ieee_is_finite(wave))) error stop 1 + if(maxval(abs(wave)).le.0.) error stop 1 + ntests=ntests+1 + end subroutine expect_signal_wave + +end program test_echo_morse diff --git a/tests/unit/echo/test_echocall_input.cmake b/tests/unit/echo/test_echocall_input.cmake new file mode 100644 index 00000000..1a88dd3a --- /dev/null +++ b/tests/unit/echo/test_echocall_input.cmake @@ -0,0 +1,131 @@ +if (NOT DEFINED ECHOCALLSIM OR NOT DEFINED TESTECHOCALL OR NOT DEFINED TEST_DIR) + message (FATAL_ERROR "EchoCall filename test is missing a required path") +endif () + +file (MAKE_DIRECTORY "${TEST_DIR}") +set (source_wav "${TEST_DIR}/000000_000000.wav") +file (REMOVE "${source_wav}") + +execute_process ( + COMMAND "${TESTECHOCALL}" + RESULT_VARIABLE no_argument_result + OUTPUT_VARIABLE no_argument_output + ERROR_VARIABLE no_argument_error +) +if (no_argument_result EQUAL 0) + message (FATAL_ERROR "testEchoCall accepted a missing input filename") +endif () +set (no_argument_output "${no_argument_output}${no_argument_error}") +if (NOT no_argument_output MATCHES "Usage: testEchoCall") + message (FATAL_ERROR + "testEchoCall missing-input output was unexpected:\n${no_argument_output}") +endif () + +execute_process ( + COMMAND "${ECHOCALLSIM}" K1JT 1500 0 0 10 1 99 + WORKING_DIRECTORY "${TEST_DIR}" + RESULT_VARIABLE simulator_result + OUTPUT_VARIABLE simulator_output + ERROR_VARIABLE simulator_error +) +if (NOT simulator_result EQUAL 0) + message (FATAL_ERROR + "EchoCallSim failed (${simulator_result}):\n${simulator_output}${simulator_error}") +endif () +if (NOT EXISTS "${source_wav}") + message (FATAL_ERROR "EchoCallSim did not create ${source_wav}") +endif () + +function (expect_accepted filename expected_timestamp) + configure_file ("${source_wav}" "${TEST_DIR}/${filename}" COPYONLY) + execute_process ( + COMMAND "${TESTECHOCALL}" "${TEST_DIR}/${filename}" + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + ) + if (NOT result EQUAL 0) + message (FATAL_ERROR + "testEchoCall rejected ${filename} (${result}):\n${output}${error}") + endif () + if (NOT output MATCHES "${expected_timestamp}.*K1JT") + message (FATAL_ERROR + "testEchoCall output was unexpected for ${filename}:\n${output}") + endif () +endfunction () + +function (expect_rejected filename) + configure_file ("${source_wav}" "${TEST_DIR}/${filename}" COPYONLY) + execute_process ( + COMMAND "${TESTECHOCALL}" "${TEST_DIR}/${filename}" + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + ) + if (result EQUAL 0) + message (FATAL_ERROR "testEchoCall accepted invalid filename ${filename}") + endif () + set (combined_output "${output}${error}") + if (NOT combined_output MATCHES + "filename must end with a valid HHMMSS\\.wav timestamp") + message (FATAL_ERROR + "testEchoCall rejection was unexpected for ${filename}:\n${combined_output}") + endif () + if (combined_output MATCHES "Fortran runtime error") + message (FATAL_ERROR + "testEchoCall raised a runtime error for ${filename}:\n${combined_output}") + endif () +endfunction () + +function (expect_io_failure filename expected_message) + execute_process ( + COMMAND "${TESTECHOCALL}" "${TEST_DIR}/${filename}" + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + ) + if (result EQUAL 0) + message (FATAL_ERROR "testEchoCall accepted unreadable input ${filename}") + endif () + set (combined_output "${output}${error}") + if (NOT combined_output MATCHES "${expected_message}") + message (FATAL_ERROR + "testEchoCall I/O rejection was unexpected for ${filename}:\n${combined_output}") + endif () + if (combined_output MATCHES "Fortran runtime error") + message (FATAL_ERROR + "testEchoCall raised a runtime error for ${filename}:\n${combined_output}") + endif () +endfunction () + +expect_accepted ("123456.wav" "123456") +expect_accepted ("235959.WAV" "235959") + +set (long_path_component + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") +file (MAKE_DIRECTORY "${TEST_DIR}/${long_path_component}") +expect_accepted ("${long_path_component}/123456.wav" "123456") + +expect_rejected ("badname") +expect_rejected ("abc.wav") +expect_rejected ("abcdef.wav") +expect_rejected ("240000.wav") +expect_rejected ("126000.wav") +expect_rejected ("125960.wav") + +set (missing_wav "${TEST_DIR}/010203.wav") +file (REMOVE "${missing_wav}") +expect_io_failure ("010203.wav" "testEchoCall: cannot open") +if (EXISTS "${missing_wav}") + message (FATAL_ERROR "testEchoCall created missing input ${missing_wav}") +endif () + +file (WRITE "${TEST_DIR}/010204.wav" "truncated") +expect_io_failure ("010204.wav" "testEchoCall: cannot read") + +set (invalid_wav_payload "not a RIFF/WAVE file") +foreach (iteration RANGE 1 12) + set (invalid_wav_payload "${invalid_wav_payload}${invalid_wav_payload}") +endforeach () +file (WRITE "${TEST_DIR}/010205.wav" "${invalid_wav_payload}") +expect_io_failure ("010205.wav" "not a RIFF/WAVE file") diff --git a/tests/unit/fst4/CMakeLists.txt b/tests/unit/fst4/CMakeLists.txt new file mode 100644 index 00000000..afd3f8e8 --- /dev/null +++ b/tests/unit/fst4/CMakeLists.txt @@ -0,0 +1,13 @@ +add_executable (test_fst4_generator + test_fst4_generator.f90) +target_include_directories (test_fst4_generator PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_fst4_generator) + +add_test (NAME test_fst4_generator COMMAND test_fst4_generator) + +add_executable (test_fst4_osd_depth + test_fst4_osd_depth.f90) +target_include_directories (test_fst4_osd_depth PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_fst4_osd_depth) + +add_test (NAME test_fst4_osd_depth COMMAND test_fst4_osd_depth) diff --git a/tests/unit/fst4/test_fst4_generator.f90 b/tests/unit/fst4/test_fst4_generator.f90 new file mode 100644 index 00000000..8fdd4cf8 --- /dev/null +++ b/tests/unit/fst4/test_fst4_generator.f90 @@ -0,0 +1,140 @@ +program test_fst4_generator + + implicit none + + integer :: ntests + + ntests=0 + + call expect_good_fst4w('K1ABC FN42 37',ntests) + call expect_bad_fst4w('<PJ4/K1ABC> FK52A!',ntests) + call expect_bad_fst4w('K1ABC FN42 55',ntests) + call expect_bad_fst4w('K1ABC FN42 03',ntests) + call expect_bad_fst4w('K1ABC FN42 5!',ntests) + call expect_fst4_lossy_free_text('ABCDEFGHIJKLMN','ABCDEFGHIJKLM',ntests) + + write(*,1000) ntests +1000 format('FST4 generator tests passed: ',i0) + +contains + + subroutine expect_good_fst4w(input,ntests) + character(len=*), intent(in) :: input + integer, intent(inout) :: ntests + character(len=37) :: msg,msgsent + integer*1 :: msgbits(101) + integer*4 :: itone(160) + integer :: iwspr + + msg=' ' + msg=input + msgsent='sentinel' + msgbits=0 + itone=0 + iwspr=1 + + call genfst4(msg,0,msgsent,msgbits,itone,iwspr) + + if(trim(msgsent).ne.input) then + write(*,1080) trim(input), trim(msgsent) +1080 format('FST4W valid input "',a,'" returned "',a,'"') + error stop 1 + endif + if(iwspr.ne.1) then + write(*,1090) trim(input), iwspr +1090 format('FST4W valid input "',a,'" changed iwspr to ',i0) + error stop 1 + endif + if(all(itone.eq.0)) then + write(*,1100) trim(input) +1100 format('FST4W valid input "',a,'" produced all-zero tones') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_good_fst4w + + subroutine expect_bad_fst4w(input,ntests) + character(len=*), intent(in) :: input + integer, intent(inout) :: ntests + character(len=37) :: msg,msgsent + integer*1 :: msgbits(101) + integer*4 :: itone(160) + integer :: iwspr + + msg=' ' + msg=input + msgsent='sentinel' + msgbits=1 + itone=3 + iwspr=1 + + call genfst4(msg,0,msgsent,msgbits,itone,iwspr) + + if(trim(msgsent).ne.'*** bad message ***') then + write(*,1010) trim(input), trim(msgsent) +1010 format('FST4W invalid input "',a,'" returned "',a,'"') + error stop 1 + endif + if(any(msgbits.ne.0)) then + write(*,1020) trim(input) +1020 format('FST4W invalid input "',a,'" left nonzero message bits') + error stop 1 + endif + if(any(itone.ne.0)) then + write(*,1030) trim(input) +1030 format('FST4W invalid input "',a,'" left nonzero tones') + error stop 1 + endif + if(iwspr.ne.1) then + write(*,1040) trim(input), iwspr +1040 format('FST4W invalid input "',a,'" changed iwspr to ',i0) + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_bad_fst4w + + subroutine expect_fst4_lossy_free_text(input,expected,ntests) + character(len=*), intent(in) :: input + character(len=*), intent(in) :: expected + integer, intent(inout) :: ntests + character(len=37) :: msg,msgsent + integer*1 :: msgbits(101) + integer*4 :: itone(160) + integer :: iwspr + + msg=' ' + msg=input + msgsent='sentinel' + msgbits=0 + itone=0 + iwspr=0 + + call genfst4(msg,0,msgsent,msgbits,itone,iwspr) + + if(trim(msgsent).eq.'*** bad message ***') then + write(*,1050) trim(input) +1050 format('FST4 lossy input "',a,'" was rejected') + error stop 1 + endif + if(trim(msgsent).ne.expected) then + write(*,1055) trim(input), trim(msgsent), trim(expected) +1055 format('FST4 lossy input "',a,'" returned "',a,'" expected "',a,'"') + error stop 1 + endif + if(iwspr.ne.0) then + write(*,1060) trim(input), iwspr +1060 format('FST4 lossy input "',a,'" changed iwspr to ',i0) + error stop 1 + endif + if(all(itone.eq.0)) then + write(*,1070) trim(input) +1070 format('FST4 lossy input "',a,'" produced all-zero tones') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_fst4_lossy_free_text + +end program test_fst4_generator diff --git a/tests/unit/fst4/test_fst4_osd_depth.f90 b/tests/unit/fst4/test_fst4_osd_depth.f90 new file mode 100644 index 00000000..dc41ccdf --- /dev/null +++ b/tests/unit/fst4/test_fst4_osd_depth.f90 @@ -0,0 +1,78 @@ +program test_fst4_osd_depth + + implicit none + + integer, parameter :: n = 240 + real :: llr(n) + integer(kind=1) :: apmask(n) + integer(kind=1) :: message_zero(74), message_negative(74) + integer(kind=1) :: message101_zero(101), message101_negative(101) + integer(kind=1) :: cw_zero(n), cw_negative(n) + real :: llr128(128) + integer(kind=1) :: apmask128(128) + integer(kind=1) :: message77_zero(77), message77_negative(77) + integer(kind=1) :: cw128_zero(128), cw128_negative(128) + integer :: nhard_zero, nhard_negative + real :: dmin_zero, dmin_negative + integer :: i + integer :: nhard128_zero, nhard128_negative + real :: dmin128_zero, dmin128_negative + external :: osd240_74, osd240_101, osd128_90 + + do i = 1, n + llr(i) = real(mod(7*i, 23) - 11) + end do + apmask = 0 + + call osd240_74(llr, 50, apmask, 0, message_zero, cw_zero, nhard_zero, dmin_zero) + call osd240_74(llr, 50, apmask, -1, message_negative, cw_negative, & + nhard_negative, dmin_negative) + call require(all(message_zero == message_negative), & + 'negative (240,74) OSD depth matches zero depth') + call require(all(cw_zero == cw_negative), & + 'negative (240,74) OSD depth preserves the codeword') + call require(nhard_zero == nhard_negative .and. dmin_zero == dmin_negative, & + 'negative (240,74) OSD depth preserves metrics') + + call osd240_101(llr, 77, apmask, 0, message101_zero, cw_zero, & + nhard_zero, dmin_zero) + call osd240_101(llr, 77, apmask, -1, message101_negative, cw_negative, & + nhard_negative, dmin_negative) + call require(all(message101_zero == message101_negative), & + 'negative (240,101) OSD depth matches zero depth') + call require(all(cw_zero == cw_negative), & + 'negative (240,101) OSD depth preserves the codeword') + call require(nhard_zero == nhard_negative .and. dmin_zero == dmin_negative, & + 'negative (240,101) OSD depth preserves metrics') + + do i = 1, 128 + llr128(i) = real(mod(11*i, 29) - 14) + end do + apmask128 = 0 + call osd128_90(llr128, apmask128, 0, message77_zero, cw128_zero, & + nhard128_zero, dmin128_zero) + call osd128_90(llr128, apmask128, -1, message77_negative, cw128_negative, & + nhard128_negative, dmin128_negative) + call require(all(message77_zero == message77_negative), & + 'negative (128,90) OSD depth matches zero depth') + call require(all(cw128_zero == cw128_negative), & + 'negative (128,90) OSD depth preserves the codeword') + call require(nhard128_zero == nhard128_negative .and. & + dmin128_zero == dmin128_negative, & + 'negative (128,90) OSD depth preserves metrics') + + print '(a)', 'FST4 OSD depth tests passed' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + +end program test_fst4_osd_depth diff --git a/tests/unit/ft8/CMakeLists.txt b/tests/unit/ft8/CMakeLists.txt new file mode 100644 index 00000000..18eb4557 --- /dev/null +++ b/tests/unit/ft8/CMakeLists.txt @@ -0,0 +1,51 @@ +add_executable (test_ft8_mtd_decode_scheduler + test_ft8_mtd_decode_scheduler.cpp + ${CMAKE_SOURCE_DIR}/Ft8MtdDecodeScheduler.cpp +) +target_include_directories (test_ft8_mtd_decode_scheduler PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_ft8_mtd_decode_scheduler Qt5::Test) +add_test (NAME test_ft8_mtd_decode_scheduler COMMAND test_ft8_mtd_decode_scheduler) + +add_executable (test_ft8_mtd_decode_coordinator + test_ft8_mtd_decode_coordinator.cpp + ${CMAKE_SOURCE_DIR}/Ft8MtdDecodeCoordinator.cpp + ${CMAKE_SOURCE_DIR}/Ft8MtdDecodeScheduler.cpp + ${CMAKE_SOURCE_DIR}/DecoderIpc.cpp + ${CMAKE_SOURCE_DIR}/lib/decoder_ipc_control.cpp +) +target_include_directories (test_ft8_mtd_decode_coordinator PRIVATE + ${CMAKE_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/lib +) +target_link_libraries (test_ft8_mtd_decode_coordinator Qt5::Test) +add_test (NAME test_ft8_mtd_decode_coordinator COMMAND test_ft8_mtd_decode_coordinator) + +add_executable (test_ft8_decode_ranges + test_ft8_decode_ranges.f90) +target_include_directories (test_ft8_decode_ranges PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_ft8_decode_ranges) + +add_test (NAME test_ft8_decode_ranges COMMAND test_ft8_decode_ranges) + +add_executable (test_ft8_mtd_residual + test_ft8_mtd_residual.f90) +target_include_directories (test_ft8_mtd_residual PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_ft8_mtd_residual) + +add_test (NAME test_ft8_mtd_residual COMMAND test_ft8_mtd_residual) + +if (TARGET wsjt_fort_omp) + add_executable (test_ft8_mtd_transaction_concurrent + test_ft8_mtd_transaction_concurrent.f90) + target_include_directories (test_ft8_mtd_transaction_concurrent PRIVATE + ${WSJT_FORTRAN_OPENMP_MODULE_DIR}) + target_link_libraries (test_ft8_mtd_transaction_concurrent PRIVATE + wsjt_fort_omp wsjt_fortran_openmp) + + add_test (NAME test_ft8_mtd_transaction_concurrent + COMMAND test_ft8_mtd_transaction_concurrent) + set_tests_properties (test_ft8_mtd_transaction_concurrent PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=4;OMP_THREAD_LIMIT=4" + PROCESSORS 4 + TIMEOUT 30) +endif () diff --git a/tests/unit/ft8/test_ft8_decode_ranges.f90 b/tests/unit/ft8/test_ft8_decode_ranges.f90 new file mode 100644 index 00000000..9f6f2466 --- /dev/null +++ b/tests/unit/ft8/test_ft8_decode_ranges.f90 @@ -0,0 +1,68 @@ +program test_ft8_decode_ranges + use ft8_decode_ranges, only: max_ft8_decode_ranges, partition_ft8_decode_range + implicit none + + integer :: requested_ranges + + do requested_ranges=1,max_ft8_decode_ranges + call assert_partition(200,1000,requested_ranges,requested_ranges) + enddo + + call assert_empty_partition(4900,1000,12) + call assert_partition(1000,1000,12,1) + call assert_partition(999,1000,12,2) + call assert_partition(4900,5000,12,12) + call assert_upper_bounds(200,1000,11, & + [272,345,418,491,564,637,710,783,856,928,1000]) + call assert_upper_bounds(200,1000,12, & + [266,333,400,467,534,601,668,735,802,868,934,1000]) + +contains + + subroutine assert_empty_partition(nfa,nfb,requested_ranges) + integer, intent(in) :: nfa,nfb,requested_ranges + integer :: range_low(max_ft8_decode_ranges) + integer :: range_high(max_ft8_decode_ranges) + integer :: nranges + + call partition_ft8_decode_range(nfa,nfb,requested_ranges,range_low,range_high,nranges) + if(nranges.ne.0) error stop 'reversed range must produce no partitions' + end subroutine assert_empty_partition + + subroutine assert_upper_bounds(nfa,nfb,requested_ranges,expected_high) + integer, intent(in) :: nfa,nfb,requested_ranges + integer, intent(in) :: expected_high(:) + integer :: range_low(max_ft8_decode_ranges) + integer :: range_high(max_ft8_decode_ranges) + integer :: nranges + + call partition_ft8_decode_range(nfa,nfb,requested_ranges,range_low,range_high,nranges) + if(nranges.ne.size(expected_high)) error stop 'unexpected exact partition count' + if(any(range_high(1:nranges).ne.expected_high)) error stop 'unexpected partition boundary' + end subroutine assert_upper_bounds + + subroutine assert_partition(nfa,nfb,requested_ranges,expected_ranges) + integer, intent(in) :: nfa,nfb,requested_ranges,expected_ranges + integer :: i,max_width,min_width,nranges + integer :: range_low(max_ft8_decode_ranges) + integer :: range_high(max_ft8_decode_ranges) + + call partition_ft8_decode_range(nfa,nfb,requested_ranges,range_low,range_high,nranges) + + if(nranges.ne.expected_ranges) error stop 'unexpected partition count' + if(range_low(1).ne.nfa) error stop 'partitioning changed the lower bound' + if(range_high(nranges).ne.nfb) error stop 'partitioning changed the upper bound' + + do i=1,nranges + if(range_low(i).gt.range_high(i)) error stop 'partition is reversed' + if(i.gt.1) then + if(range_low(i).ne.range_high(i-1)+1) error stop 'partitions are not contiguous' + endif + enddo + + min_width=minval(range_high(1:nranges)-range_low(1:nranges)+1) + max_width=maxval(range_high(1:nranges)-range_low(1:nranges)+1) + if(max_width-min_width.gt.1) error stop 'partitions are not balanced' + end subroutine assert_partition + +end program test_ft8_decode_ranges diff --git a/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp b/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp new file mode 100644 index 00000000..2debacb3 --- /dev/null +++ b/tests/unit/ft8/test_ft8_mtd_decode_coordinator.cpp @@ -0,0 +1,327 @@ +#include <QtTest> + +#include <memory> +#include <vector> + +#include "Ft8MtdDecodeCoordinator.hpp" + +namespace +{ + using Stage = Ft8MtdDecodeCoordinator::Stage; + using Action = Ft8MtdDecodeCoordinator::Action; + using DrainResult = Ft8MtdDecodeCoordinator::DrainResult; + using PendingPublishResult = Ft8MtdDecodeCoordinator::PendingPublishResult; + + std::unique_ptr<Ft8MtdDecodeCoordinator::PendingMtdDecode> pendingDecode ( + qint64 period, int nutc, short firstSample) + { + auto pending = std::make_unique<Ft8MtdDecodeCoordinator::PendingMtdDecode> (); + pending->period = period; + pending->payload.params.nmode = 8; + pending->payload.params.lmultift8 = true; + pending->payload.params.nutc = nutc; + pending->payload.samples[0] = firstSample; + pending->context.mode = "FT8"; + pending->context.periodFrequency = 14074000; + pending->context.band = "20m"; + pending->context.multithreadFt8 = true; + pending->context.ft8ThreadCount = 4; + pending->context.decodeDepth = 3; + return pending; + } + + class FakeBackend + { + public: + void startEarly (Stage stage, qint64 period, int earlyStageCount) + { + auto const decision = coordinator.request ( + stage, period, earlyStageCount, active); + QCOMPARE (decision.action, Action::Publish); + active = true; + activeStage = stage; + activePeriod = period; + coordinator.published (stage, period); + publishedPeriods.push_back (period); + } + + Action submitFinal (qint64 period, int nutc, short firstSample, + int earlyStageCount = 1) + { + auto const decision = coordinator.request ( + Stage::Final, period, earlyStageCount, + active || coordinator.hasPending ()); + if (Action::Publish == decision.action) + { + active = true; + activeStage = Stage::Final; + activePeriod = period; + coordinator.published (Stage::Final, period); + publishedPeriods.push_back (period); + publishedNutcs.push_back (nutc); + return decision.action; + } + + return coordinator.deferFinal ( + pendingDecode (period, nutc, firstSample)); + } + + void completeAndDrain () + { + QVERIFY (active); + coordinator.completed (activeStage, activePeriod); + active = false; + activeStage = Stage::None; + activePeriod = -1; + if (!coordinator.hasPending ()) return; + + auto const outcome = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [this] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + active = true; + activeStage = Stage::Final; + activePeriod = pending.period; + publishedPeriods.push_back (pending.period); + publishedNutcs.push_back (pending.payload.params.nutc); + publishedFirstSamples.push_back (pending.payload.samples[0]); + publishedContext = pending.context; + return PendingPublishResult::Published; + }); + QCOMPARE (outcome.result, DrainResult::Published); + } + + bool externallyBusy () const + { + return active || coordinator.hasPending (); + } + + Ft8MtdDecodeCoordinator coordinator; + bool active {false}; + Stage activeStage {Stage::None}; + qint64 activePeriod {-1}; + std::vector<qint64> publishedPeriods; + std::vector<int> publishedNutcs; + std::vector<short> publishedFirstSamples; + DecodeOperatingContext publishedContext; + }; +} + +class TestFt8MtdDecodeCoordinator final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void slowEarlyDecodeRetainsAndPublishesFinalOnce (); + void unrelatedCompletionDoesNotPublishPendingFinal (); + void multiPeriodOverrunPublishesOnlyNewestFinal (); + void pendingSnapshotIsImmutable (); + void pendingContextReachesFinalPublication (); + void pendingCountsAsBusyUntilDrain (); + void temporaryBackendFailurePreservesPending (); + void fatalBackendFailureDropsPending (); + void publicationFailureLeavesPendingForRestart (); + void changedContextDropsPendingWithoutPublishing (); + void cancellationDropsPendingAndSchedulingState (); +}; + +void TestFt8MtdDecodeCoordinator::slowEarlyDecodeRetainsAndPublishesFinalOnce () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 100, 1); + + QCOMPARE (backend.submitFinal (100, 120000, 17), Action::DeferFinal); + QVERIFY (backend.externallyBusy ()); + backend.completeAndDrain (); + + QVERIFY (backend.publishedPeriods == std::vector<qint64> ({100, 100})); + QVERIFY (backend.publishedNutcs == std::vector<int> ({120000})); + QCOMPARE (backend.activeStage, Stage::Final); + QCOMPARE (backend.activePeriod, qint64 {100}); + QVERIFY (backend.active); + QVERIFY (!backend.coordinator.hasPending ()); +} + +void TestFt8MtdDecodeCoordinator::unrelatedCompletionDoesNotPublishPendingFinal () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 150, 1); + backend.submitFinal (150, 120015, 18); + + backend.coordinator.completed (Stage::EarlyOne, 149); + + QVERIFY (backend.coordinator.hasPending ()); + QVERIFY (backend.publishedPeriods == std::vector<qint64> ({150})); + + backend.completeAndDrain (); + QVERIFY (backend.publishedPeriods == std::vector<qint64> ({150, 150})); +} + +void TestFt8MtdDecodeCoordinator::multiPeriodOverrunPublishesOnlyNewestFinal () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 200, 1); + QCOMPARE (backend.submitFinal (200, 130000, 20), Action::DeferFinal); + QCOMPARE (backend.submitFinal (201, 130015, 21), Action::ReplaceFinal); + QCOMPARE (backend.submitFinal (202, 130030, 22), Action::ReplaceFinal); + + backend.completeAndDrain (); + + QVERIFY (backend.publishedPeriods == std::vector<qint64> ({200, 202})); + QVERIFY (backend.publishedNutcs == std::vector<int> ({130030})); + QVERIFY (backend.publishedFirstSamples == std::vector<short> ({22})); +} + +void TestFt8MtdDecodeCoordinator::pendingSnapshotIsImmutable () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 300, 1); + int sourceNutC {140000}; + short sourceSample {31}; + backend.submitFinal (300, sourceNutC, sourceSample); + sourceNutC = 140015; + sourceSample = 32; + + backend.completeAndDrain (); + + QCOMPARE (backend.publishedNutcs.back (), 140000); + QCOMPARE (backend.publishedFirstSamples.back (), short {31}); +} + +void TestFt8MtdDecodeCoordinator::pendingContextReachesFinalPublication () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 350, 1); + backend.submitFinal (350, 140015, 35); + + backend.completeAndDrain (); + + auto const& context = backend.publishedContext; + QCOMPARE (context.mode, QStringLiteral ("FT8")); + QCOMPARE (context.periodFrequency, Radio::Frequency {14074000}); + QCOMPARE (context.band, QStringLiteral ("20m")); + QVERIFY (context.multithreadFt8); + QCOMPARE (context.ft8ThreadCount, 4); + QCOMPARE (context.decodeDepth, 3); +} + +void TestFt8MtdDecodeCoordinator::pendingCountsAsBusyUntilDrain () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 400, 1); + backend.submitFinal (400, 150000, 41); + + backend.active = false; + QVERIFY (backend.coordinator.hasPending ()); + QVERIFY (backend.externallyBusy ()); + backend.active = true; + backend.completeAndDrain (); + QVERIFY (backend.externallyBusy ()); +} + +void TestFt8MtdDecodeCoordinator::temporaryBackendFailurePreservesPending () +{ + Ft8MtdDecodeCoordinator coordinator; + coordinator.deferFinal (pendingDecode (500, 160000, 51)); + + auto const unavailable = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) { + return PendingPublishResult::Unavailable; + }); + QCOMPARE (unavailable.result, DrainResult::Retained); + QVERIFY (coordinator.hasPending ()); + + auto shared = std::make_unique<shared_dec_data_t> (); + DecoderIpc::initialize (*shared); + int publishCalls {0}; + auto const published = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [&] (Ft8MtdDecodeCoordinator::PendingMtdDecode const& pending) { + ++publishCalls; + return DecoderIpc::publishFt8Mtd (*shared, pending.payload, 1) + ? PendingPublishResult::Published : PendingPublishResult::Failed; + }); + + QCOMPARE (published.result, DrainResult::Published); + QCOMPARE (publishCalls, 1); + QVERIFY (!coordinator.hasPending ()); + QCOMPARE (shared->payload.params.nutc, 160000); + QCOMPARE (shared->payload.d2[0], short {51}); + + auto const empty = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [&] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) { + ++publishCalls; + return PendingPublishResult::Published; + }); + QCOMPARE (empty.result, DrainResult::NoPending); + QCOMPARE (publishCalls, 1); +} + +void TestFt8MtdDecodeCoordinator::fatalBackendFailureDropsPending () +{ + Ft8MtdDecodeCoordinator coordinator; + coordinator.deferFinal (pendingDecode (510, 160015, 52)); + + auto const outcome = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return true;}, + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) { + return PendingPublishResult::Failed; + }); + + QCOMPARE (outcome.result, DrainResult::Failed); + QVERIFY (!coordinator.hasPending ()); +} + +void TestFt8MtdDecodeCoordinator::publicationFailureLeavesPendingForRestart () +{ + FakeBackend backend; + backend.startEarly (Stage::EarlyOne, 515, 1); + backend.submitFinal (515, 160020, 52); + + backend.coordinator.publicationFailed (Stage::EarlyOne, 515); + QVERIFY (backend.coordinator.hasPending ()); + + backend.completeAndDrain (); + + QVERIFY (backend.publishedPeriods == std::vector<qint64> ({515, 515})); + QVERIFY (!backend.coordinator.hasPending ()); +} + +void TestFt8MtdDecodeCoordinator::changedContextDropsPendingWithoutPublishing () +{ + Ft8MtdDecodeCoordinator coordinator; + coordinator.request (Stage::Final, 520, 1, true); + coordinator.deferFinal (pendingDecode (520, 160030, 53)); + int publishCalls {0}; + + auto const outcome = coordinator.drainPending ( + [] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) {return false;}, + [&] (Ft8MtdDecodeCoordinator::PendingMtdDecode const&) { + ++publishCalls; + return PendingPublishResult::Published; + }); + + QCOMPARE (outcome.result, DrainResult::Obsolete); + QCOMPARE (publishCalls, 0); + QVERIFY (!coordinator.hasPending ()); + QVERIFY (!coordinator.degraded ()); +} + +void TestFt8MtdDecodeCoordinator::cancellationDropsPendingAndSchedulingState () +{ + Ft8MtdDecodeCoordinator coordinator; + coordinator.request (Stage::Final, 600, 1, true); + coordinator.deferFinal (pendingDecode (600, 170000, 61)); + QVERIFY (coordinator.degraded ()); + + coordinator.cancel (); + + QVERIFY (!coordinator.hasPending ()); + QVERIFY (!coordinator.degraded ()); + QCOMPARE (coordinator.nextProbePeriod (), qint64 {0}); +} + +QTEST_GUILESS_MAIN (TestFt8MtdDecodeCoordinator) + +#include "test_ft8_mtd_decode_coordinator.moc" diff --git a/tests/unit/ft8/test_ft8_mtd_decode_scheduler.cpp b/tests/unit/ft8/test_ft8_mtd_decode_scheduler.cpp new file mode 100644 index 00000000..13b96ce5 --- /dev/null +++ b/tests/unit/ft8/test_ft8_mtd_decode_scheduler.cpp @@ -0,0 +1,137 @@ +#include <QtTest> + +#include "Ft8MtdDecodeScheduler.hpp" + +class TestFt8MtdDecodeScheduler final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void eligibilityRequiresIndependentMtdFinal (); + void idleRequestsPublishImmediately (); + void earlyRequestsNeverQueue (); + void finalRequestsDeferOrReplace (); + void failedProbesBackOffExponentially (); + void oneEarlyPassMtdConfigurationRecovers (); + void twoEarlyPassMtdConfigurationRequiresBothEarlyPasses (); + void cancelRestoresBoundedInitialState (); +}; + +using Stage = Ft8MtdDecodeScheduler::Stage; +using Action = Ft8MtdDecodeScheduler::Action; + +void TestFt8MtdDecodeScheduler::eligibilityRequiresIndependentMtdFinal () +{ + QVERIFY (!Ft8MtdDecodeScheduler::supportsBackpressure (false, false)); + QVERIFY (Ft8MtdDecodeScheduler::supportsBackpressure (true, false)); + QVERIFY (!Ft8MtdDecodeScheduler::supportsBackpressure (true, true)); +} + +void TestFt8MtdDecodeScheduler::idleRequestsPublishImmediately () +{ + Ft8MtdDecodeScheduler scheduler; + QCOMPARE (scheduler.request (Stage::EarlyOne, 10, 1, false, false).action, + Action::Publish); + QCOMPARE (scheduler.request (Stage::Final, 10, 1, false, false).action, + Action::Publish); + QVERIFY (!scheduler.degraded ()); +} + +void TestFt8MtdDecodeScheduler::earlyRequestsNeverQueue () +{ + Ft8MtdDecodeScheduler scheduler; + auto const decision = scheduler.request (Stage::EarlyOne, 20, 1, true, false); + QCOMPARE (decision.action, Action::SkipEarly); + QVERIFY (decision.enteredDegraded); + QVERIFY (scheduler.degraded ()); +} + +void TestFt8MtdDecodeScheduler::finalRequestsDeferOrReplace () +{ + Ft8MtdDecodeScheduler scheduler; + QCOMPARE (scheduler.request (Stage::Final, 30, 1, true, false).action, + Action::DeferFinal); + QCOMPARE (scheduler.request (Stage::Final, 31, 1, true, true).action, + Action::ReplaceFinal); +} + +void TestFt8MtdDecodeScheduler::failedProbesBackOffExponentially () +{ + Ft8MtdDecodeScheduler scheduler; + auto result = scheduler.request (Stage::EarlyOne, 40, 1, true, false); + QCOMPARE (result.skippedPeriods, 1); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {42}); + QCOMPARE (scheduler.request (Stage::EarlyOne, 41, 1, false, false).action, + Action::SkipEarly); + + result = scheduler.request (Stage::EarlyOne, 42, 1, true, false); + QCOMPARE (result.skippedPeriods, 2); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {45}); + result = scheduler.request (Stage::EarlyOne, 45, 1, true, false); + QCOMPARE (result.skippedPeriods, 4); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {50}); + result = scheduler.request (Stage::EarlyOne, 50, 1, true, false); + QCOMPARE (result.skippedPeriods, 8); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {59}); + result = scheduler.request (Stage::EarlyOne, 59, 1, true, false); + QCOMPARE (result.skippedPeriods, 8); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {68}); +} + +void TestFt8MtdDecodeScheduler::oneEarlyPassMtdConfigurationRecovers () +{ + Ft8MtdDecodeScheduler scheduler; + scheduler.request (Stage::Final, 60, 1, true, false); + QCOMPARE (scheduler.request (Stage::EarlyOne, 62, 1, false, false).action, + Action::Publish); + scheduler.published (Stage::EarlyOne, 62); + scheduler.completed (Stage::EarlyOne, 62); + QCOMPARE (scheduler.request (Stage::Final, 62, 1, false, false).action, + Action::Publish); + QVERIFY (scheduler.published (Stage::Final, 62)); + QVERIFY (!scheduler.degraded ()); +} + +void TestFt8MtdDecodeScheduler::twoEarlyPassMtdConfigurationRequiresBothEarlyPasses () +{ + Ft8MtdDecodeScheduler complete; + complete.request (Stage::Final, 70, 2, true, false); + complete.request (Stage::EarlyOne, 72, 2, false, false); + complete.published (Stage::EarlyOne, 72); + complete.completed (Stage::EarlyOne, 72); + QCOMPARE (complete.request (Stage::EarlyTwo, 72, 2, false, false).action, + Action::Publish); + complete.published (Stage::EarlyTwo, 72); + complete.completed (Stage::EarlyTwo, 72); + QCOMPARE (complete.request (Stage::Final, 72, 2, false, false).action, + Action::Publish); + QVERIFY (complete.published (Stage::Final, 72)); + QVERIFY (!complete.degraded ()); + + Ft8MtdDecodeScheduler incomplete; + incomplete.request (Stage::Final, 80, 2, true, false); + incomplete.request (Stage::EarlyOne, 82, 2, false, false); + incomplete.published (Stage::EarlyOne, 82); + incomplete.completed (Stage::EarlyOne, 82); + incomplete.request (Stage::EarlyTwo, 82, 2, false, false); + incomplete.published (Stage::EarlyTwo, 82); + QCOMPARE (incomplete.request (Stage::Final, 82, 2, true, false).action, + Action::DeferFinal); + QVERIFY (incomplete.degraded ()); +} + +void TestFt8MtdDecodeScheduler::cancelRestoresBoundedInitialState () +{ + Ft8MtdDecodeScheduler scheduler; + scheduler.request (Stage::Final, 80, 1, true, true); + QVERIFY (scheduler.degraded ()); + scheduler.cancel (); + QVERIFY (!scheduler.degraded ()); + QCOMPARE (scheduler.nextProbePeriod (), qint64 {0}); + QCOMPARE (scheduler.request (Stage::EarlyOne, 81, 1, false, false).action, + Action::Publish); +} + +QTEST_GUILESS_MAIN (TestFt8MtdDecodeScheduler) + +#include "test_ft8_mtd_decode_scheduler.moc" diff --git a/tests/unit/ft8/test_ft8_mtd_residual.f90 b/tests/unit/ft8/test_ft8_mtd_residual.f90 new file mode 100644 index 00000000..c71957fb --- /dev/null +++ b/tests/unit/ft8/test_ft8_mtd_residual.f90 @@ -0,0 +1,281 @@ +program test_ft8_mtd_residual + use iso_fortran_env, only : int64 + use ft8_mtd_residual + use ft8_mod1, only : cw,endcorr + implicit none + + integer, parameter :: frame_samples=151680 + + call test_interaction_boundary() + call test_independent_delta_commits() + call test_conflict_and_duplicate() + call test_candidate_refresh() + call test_real_subtractor_equivalence() + call test_phase_epoch_conflict() + call test_half_sample_endpoints() + call test_pass7_restore() + +contains + + subroutine test_interaction_boundary() + type(ft8_subtraction_descriptor) :: left,right + integer :: tones(79) + + tones=1 + call mtd_prepare(spread(0.0,1,mtd_residual_samples),1) + call mtd_make_descriptor(left,1,tones,1000.0,0.5) + call mtd_make_descriptor(right,1,tones,1049.999,0.5) + if(.not.mtd_descriptors_conflict(left,right)) error stop & + 'frequencies less than 50 Hz apart must interact' + call mtd_make_descriptor(right,1,tones,1050.0,0.5) + if(mtd_descriptors_conflict(left,right)) error stop & + 'frequencies exactly 50 Hz apart must be independent' + call mtd_make_descriptor(left,1,tones,1000.0,-12.5) + call mtd_make_descriptor(right,1,tones,1000.0,14.9) + if(mtd_descriptors_conflict(left,right)) error stop & + 'disjoint subtraction supports must be independent' + if(mtd_start_sample(0.00005).ne.1) error stop & + 'positive fractional start samples must truncate toward zero' + if(mtd_start_sample(-0.00023333333).ne.-1) error stop & + 'negative fractional start samples must truncate toward zero' + end subroutine test_interaction_boundary + + subroutine test_independent_delta_commits() + type(ft8_subtraction_descriptor) :: first,second + real, allocatable :: source(:),worker_one(:),worker_two(:),actual(:) + real, allocatable :: first_delta(:),second_delta(:) + integer(int64) :: first_epoch,first_generation,second_epoch,second_generation + integer :: tones(79),outcome + + allocate(source(mtd_residual_samples),worker_one(mtd_residual_samples), & + worker_two(mtd_residual_samples),actual(mtd_residual_samples), & + first_delta(frame_samples),second_delta(frame_samples)) + source=0.0 + first_delta=0.0 + second_delta=0.0 + first_delta(1)=-1.0 + second_delta(1)=-2.0 + tones=1 + + call mtd_prepare(source,2) + call mtd_publish_worker(1) + call mtd_publish_worker(2) + worker_one=mtd_worker_residual(:,1) + worker_two=mtd_worker_residual(:,2) + call mtd_capture_generation(1,first_epoch,first_generation) + call mtd_capture_generation(2,second_epoch,second_generation) + call mtd_make_descriptor(first,1,tones,1000.0,0.0) + call mtd_make_descriptor(second,1,tones,1100.0,0.0) + + worker_one(1)=worker_one(1)+first_delta(1) + call mtd_try_commit_delta(1,worker_one,first,first_epoch,first_generation, & + first_delta,outcome) + if(outcome.ne.mtd_commit_current) error stop 'first commit was not current' + worker_two(1)=worker_two(1)+second_delta(1) + call mtd_try_commit_delta(2,worker_two,second,second_epoch,second_generation, & + second_delta,outcome) + if(outcome.ne.mtd_commit_independent) error stop & + 'stale independent commit did not use the fast path' + call mtd_finish(actual) + if(actual(1).ne.-3.0) error stop 'independent updates were not both preserved' + if(worker_two(1).ne.-3.0) error stop 'stale worker did not receive canonical state' + end subroutine test_independent_delta_commits + + subroutine test_conflict_and_duplicate() + type(ft8_subtraction_descriptor) :: first,second,duplicate + real, allocatable :: source(:),worker_one(:),worker_two(:),actual(:) + real, allocatable :: delta(:) + integer(int64) :: epoch_one,generation_one,epoch_two,generation_two + integer :: tones(79),outcome + + allocate(source(mtd_residual_samples),worker_one(mtd_residual_samples), & + worker_two(mtd_residual_samples),actual(mtd_residual_samples), & + delta(frame_samples)) + source=0.0 + delta=0.0 + delta(1)=-1.0 + tones=2 + call mtd_prepare(source,2) + call mtd_publish_worker(1) + call mtd_publish_worker(2) + worker_one=mtd_worker_residual(:,1) + worker_two=mtd_worker_residual(:,2) + call mtd_capture_generation(1,epoch_one,generation_one) + call mtd_capture_generation(2,epoch_two,generation_two) + call mtd_make_descriptor(first,1,tones,1000.0,0.0) + call mtd_make_descriptor(second,1,tones,1025.0,0.0) + worker_one(1)=worker_one(1)+delta(1) + call mtd_try_commit_delta(1,worker_one,first,epoch_one,generation_one,delta,outcome) + worker_two(1)=worker_two(1)+delta(1) + call mtd_try_commit_delta(2,worker_two,second,epoch_two,generation_two,delta,outcome) + if(outcome.ne.mtd_commit_conflict) error stop & + 'interacting stale commit must request a refit' + + call mtd_capture_generation(2,epoch_two,generation_two) + worker_two(1)=worker_two(1)+delta(1) + call mtd_try_commit_delta(2,worker_two,second,epoch_two,generation_two,delta,outcome) + if(outcome.ne.mtd_commit_current) error stop 'refitted commit was not published' + + duplicate=second + call mtd_capture_generation(1,epoch_one,generation_one) + worker_one(1)=worker_one(1)+delta(1) + call mtd_try_commit_delta(1,worker_one,duplicate,epoch_one,generation_one, & + delta,outcome) + if(outcome.ne.mtd_commit_duplicate) error stop 'duplicate subtraction was repeated' + call mtd_finish(actual) + if(actual(1).ne.-2.0) error stop 'conflict or duplicate lost transaction state' + end subroutine test_conflict_and_duplicate + + subroutine test_candidate_refresh() + type(ft8_subtraction_descriptor) :: descriptor + real, allocatable :: source(:),worker_one(:) + real, allocatable :: delta(:) + integer(int64) :: epoch,generation + integer :: tones(79),outcome + logical :: newdat1,rebuild + + allocate(source(mtd_residual_samples),worker_one(mtd_residual_samples), & + delta(frame_samples)) + source=0.0 + delta=0.0 + delta(1)=-1.0 + tones=3 + call mtd_prepare(source,2) + call mtd_publish_worker(1) + call mtd_publish_worker(2) + call mtd_mark_spectrum_current(2) + worker_one=mtd_worker_residual(:,1) + call mtd_capture_generation(1,epoch,generation) + call mtd_make_descriptor(descriptor,1,tones,1100.0,0.0) + worker_one(1)=worker_one(1)+delta(1) + call mtd_try_commit_delta(1,worker_one,descriptor,epoch,generation,delta,outcome) + + newdat1=.false. + call mtd_refresh_candidate(2,1000.0,newdat1,rebuild) + if(rebuild) error stop 'far publication unnecessarily invalidated the spectrum' + call mtd_refresh_candidate(2,1100.0,newdat1,rebuild) + if(.not.rebuild) error stop 'near publication did not invalidate the spectrum' + if(mtd_worker_residual(1,2).ne.-1.0) error stop & + 'near publication did not refresh the worker residual' + call mtd_mark_spectrum_current(2) + newdat1=.false. + call mtd_refresh_candidate(2,1100.0,newdat1,rebuild) + if(rebuild) error stop 'current spectrum was invalidated again' + end subroutine test_candidate_refresh + + subroutine test_real_subtractor_equivalence() + real, allocatable :: source(:),expected(:),actual(:) + integer :: i,tones(79),outcome + + allocate(source(mtd_residual_samples),expected(mtd_residual_samples), & + actual(mtd_residual_samples)) + do i=1,mtd_residual_samples + source(i)=0.01*sin(real(i)/300.0) + enddo + tones=0 + cw=cmplx(1.0,0.0) + endcorr=1.0 + expected=source + call subtractft8var(expected,tones,1000.0,0.5) + + call mtd_prepare(source,1) + call mtd_publish_worker(1) + call mtd_commit_subtraction(1,1,tones,1000.0,0.5, & + mtd_worker_residual(:,1),outcome) + call mtd_finish(actual) + if(outcome.ne.mtd_commit_current) error stop & + 'uncontended real subtraction did not use the current path' + if(any(actual.ne.expected)) error stop & + 'prepared delta publication differs from serial subtraction' + end subroutine test_real_subtractor_equivalence + + subroutine test_phase_epoch_conflict() + type(ft8_subtraction_descriptor) :: descriptor + real, allocatable :: source(:),delta(:),worker_residual(:) + integer(int64) :: epoch,generation + integer :: tones(79),outcome + + allocate(source(mtd_residual_samples),delta(frame_samples), & + worker_residual(mtd_residual_samples)) + source=0.0 + delta=0.0 + delta(1)=-1.0 + tones=4 + call mtd_prepare(source,1) + call mtd_publish_worker(1) + worker_residual=mtd_worker_residual(:,1) + call mtd_capture_generation(1,epoch,generation) + call mtd_make_descriptor(descriptor,3,tones,1000.0,0.0) + call mtd_transform_phase(4) + worker_residual(1)=worker_residual(1)+delta(1) + call mtd_try_commit_delta(1,worker_residual,descriptor,epoch,generation, & + delta,outcome) + if(outcome.ne.mtd_commit_conflict) error stop & + 'pre-transform transaction was not rejected' + call mtd_capture_generation(1,epoch,generation) + worker_residual(1)=worker_residual(1)+delta(1) + call mtd_try_commit_delta(1,worker_residual,descriptor,epoch,generation, & + delta,outcome) + if(outcome.ne.mtd_commit_conflict) error stop & + 'stale descriptor epoch was accepted after refresh' + end subroutine test_phase_epoch_conflict + + subroutine test_half_sample_endpoints() + real, allocatable :: residual(:) + + allocate(residual(mtd_residual_samples)) + residual=0.0 + residual(1:3)=[2.0,4.0,8.0] + residual(mtd_residual_samples)=16.0 + call mtd_forward_half_sample(residual) + if(residual(1).ne.3.0 .or. residual(2).ne.6.0) error stop & + 'forward half-sample transform changed interior behavior' + if(residual(mtd_residual_samples).ne.16.0) error stop & + 'forward half-sample transform changed the trailing endpoint' + + residual=0.0 + residual(1:3)=[2.0,4.0,8.0] + call mtd_backward_half_sample(residual) + if(residual(1).ne.2.0) error stop & + 'backward half-sample transform changed the leading endpoint' + if(residual(2).ne.3.0 .or. residual(3).ne.6.0) error stop & + 'backward half-sample transform changed interior behavior' + end subroutine test_half_sample_endpoints + + subroutine test_pass7_restore() + type(ft8_subtraction_descriptor) :: descriptor + real, allocatable :: source(:),expected(:),forward(:),actual(:),delta(:) + integer(int64) :: epoch,generation + integer :: i,tones(79),outcome + + allocate(source(mtd_residual_samples),expected(mtd_residual_samples), & + forward(mtd_residual_samples),actual(mtd_residual_samples), & + delta(frame_samples)) + do i=1,mtd_residual_samples + source(i)=real(mod(i,101)) + enddo + expected=source + call mtd_backward_half_sample(expected) + forward=source + call mtd_forward_half_sample(forward) + delta=0.0 + delta(1)=-1.0 + tones=5 + call mtd_prepare(source,1) + call mtd_transform_phase(4) + call mtd_publish_worker(1) + call mtd_capture_generation(1,epoch,generation) + call mtd_make_descriptor(descriptor,4,tones,1000.0,0.0) + mtd_worker_residual(1,1)=mtd_worker_residual(1,1)+delta(1) + call mtd_try_commit_delta(1,mtd_worker_residual(:,1),descriptor,epoch, & + generation,delta,outcome) + call mtd_finish(actual) + if(all(actual.eq.forward)) error stop & + 'cycle-two transaction did not mutate the forward residual' + call mtd_transform_phase(7) + call mtd_finish(actual) + if(any(actual.ne.expected)) error stop & + 'pass 7 must restore and shift the saved post-pass-3 residual' + end subroutine test_pass7_restore + +end program test_ft8_mtd_residual diff --git a/tests/unit/ft8/test_ft8_mtd_transaction_concurrent.f90 b/tests/unit/ft8/test_ft8_mtd_transaction_concurrent.f90 new file mode 100644 index 00000000..a69b8531 --- /dev/null +++ b/tests/unit/ft8/test_ft8_mtd_transaction_concurrent.f90 @@ -0,0 +1,195 @@ +program test_ft8_mtd_transaction_concurrent + use iso_fortran_env, only : int64 + use omp_lib + use ft8_mtd_residual + implicit none + + integer, parameter :: frame_samples=151680 + + if(omp_get_max_threads().lt.4) error stop 'four OpenMP workers are required' + call test_independent_publishers() + call test_duplicate_publishers() + call test_coherent_snapshots() + +contains + + subroutine test_independent_publishers() + real, allocatable :: source(:),actual(:) + integer :: outcomes(4),worker,tones(79) + integer(int64) :: epoch,generation + type(ft8_subtraction_descriptor) :: descriptor + + allocate(source(mtd_residual_samples),actual(mtd_residual_samples)) + source=0.0 + call mtd_prepare(source,4) + +!$omp parallel num_threads(4) private(worker,tones,epoch,generation,descriptor) + block + real, allocatable :: delta(:) + allocate(delta(frame_samples)) + worker=omp_get_thread_num()+1 + delta=0.0 + delta(1)=-real(worker) + tones=worker + call mtd_publish_worker(worker) + call mtd_capture_generation(worker,epoch,generation) + call mtd_make_descriptor(descriptor,1,tones, & + 800.0+100.0*real(worker),0.0) + mtd_worker_residual(1,worker)=mtd_worker_residual(1,worker)+delta(1) +!$omp barrier + call mtd_try_commit_delta(worker,mtd_worker_residual(:,worker),descriptor, & + epoch,generation,delta,outcomes(worker)) + deallocate(delta) + end block +!$omp end parallel + + call mtd_finish(actual) + if(actual(1).ne.-10.0) error stop 'parallel independent updates were lost' + if(count(outcomes.eq.mtd_commit_current).ne.1) error stop & + 'exactly one same-generation transaction must commit first' + if(count(outcomes.eq.mtd_commit_independent).ne.3) error stop & + 'stale independent transactions did not use the fast path' + end subroutine test_independent_publishers + + subroutine test_duplicate_publishers() + real, allocatable :: source(:),actual(:) + integer :: outcomes(4),worker,tones(79) + integer(int64) :: epoch,generation + type(ft8_subtraction_descriptor) :: descriptor + + allocate(source(mtd_residual_samples),actual(mtd_residual_samples)) + source=0.0 + call mtd_prepare(source,4) + +!$omp parallel num_threads(4) private(worker,epoch,generation,descriptor,tones) + block + real, allocatable :: delta(:) + allocate(delta(frame_samples)) + worker=omp_get_thread_num()+1 + delta=0.0 + delta(1)=-1.0 + tones=7 + call mtd_publish_worker(worker) + call mtd_capture_generation(worker,epoch,generation) + call mtd_make_descriptor(descriptor,1,tones,1000.0,0.0) + mtd_worker_residual(1,worker)=mtd_worker_residual(1,worker)+delta(1) +!$omp barrier + call mtd_try_commit_delta(worker,mtd_worker_residual(:,worker),descriptor, & + epoch,generation,delta,outcomes(worker)) + deallocate(delta) + end block +!$omp end parallel + + call mtd_finish(actual) + if(actual(1).ne.-1.0) error stop 'duplicate transaction was applied more than once' + if(count(outcomes.eq.mtd_commit_current).ne.1) error stop & + 'duplicate race did not produce one winner' + if(count(outcomes.eq.mtd_commit_duplicate).ne.3) error stop & + 'duplicate race did not reject all later publishers' + end subroutine test_duplicate_publishers + + subroutine test_coherent_snapshots() + integer, parameter :: writer_iterations=50,reader_iterations=500 + real, allocatable :: source(:),actual(:) + real :: snapshot_value + integer :: worker,iteration,tones(79),outcome,writers_started,reader_ready, & + first_commits,reader_observed + integer(int64) :: epoch,generation + logical :: torn_snapshot,intermediate_observed + type(ft8_subtraction_descriptor) :: descriptor + + allocate(source(mtd_residual_samples),actual(mtd_residual_samples)) + source=0.0 + torn_snapshot=.false. + intermediate_observed=.false. + writers_started=0 + reader_ready=0 + first_commits=0 + reader_observed=0 + call mtd_prepare(source,4) + +!$omp parallel num_threads(4) private(worker,iteration,tones,outcome,epoch, & +!$omp generation,descriptor,snapshot_value) & +!$omp shared(torn_snapshot,intermediate_observed,writers_started,reader_ready, & +!$omp first_commits,reader_observed) + block + real, allocatable :: delta(:) + allocate(delta(frame_samples)) + worker=omp_get_thread_num()+1 + call mtd_publish_worker(worker) +!$omp barrier + if(worker.le.3) then + delta=-1.0 +!$omp atomic update + writers_started=writers_started+1 + do +!$omp atomic read + outcome=reader_ready + if(outcome.eq.1) exit + enddo + do iteration=1,writer_iterations + tones=0 + tones(1)=iteration + tones(2)=worker + call mtd_make_descriptor(descriptor,1,tones, & + 700.0+100.0*real(worker),0.0) + do + call mtd_capture_generation(worker,epoch,generation) + mtd_worker_residual(1:frame_samples,worker)= & + mtd_worker_residual(1:frame_samples,worker)+delta + call mtd_try_commit_delta(worker,mtd_worker_residual(:,worker), & + descriptor,epoch,generation,delta,outcome) + if(outcome.ne.mtd_commit_conflict) exit + enddo + if(iteration.eq.1) then +!$omp atomic update + first_commits=first_commits+1 + do +!$omp atomic read + outcome=reader_observed + if(outcome.eq.1) exit + enddo + endif + enddo + else + do +!$omp atomic read + outcome=writers_started + if(outcome.eq.3) exit + enddo +!$omp atomic write + reader_ready=1 + do +!$omp atomic read + outcome=first_commits + if(outcome.eq.3) exit + enddo + call mtd_publish_worker(worker) + snapshot_value=-mtd_worker_residual(1,worker) + intermediate_observed=snapshot_value.eq.3.0 +!$omp atomic write + reader_observed=1 + do iteration=1,reader_iterations + call mtd_publish_worker(worker) + if(minval(mtd_worker_residual(1:frame_samples,worker)).ne. & + maxval(mtd_worker_residual(1:frame_samples,worker))) & + torn_snapshot=.true. + snapshot_value=-mtd_worker_residual(1,worker) + if(snapshot_value.gt.0.0 .and. & + snapshot_value.lt.real(3*writer_iterations)) & + intermediate_observed=.true. + enddo + endif + deallocate(delta) + end block +!$omp end parallel + + if(torn_snapshot) error stop 'reader observed a torn canonical snapshot' + if(.not.intermediate_observed) error stop & + 'coherence reader did not overlap the publishers' + call mtd_finish(actual) + if(actual(1).ne.-real(3*writer_iterations)) error stop & + 'coherence stress did not publish every transaction' + end subroutine test_coherent_snapshots + +end program test_ft8_mtd_transaction_concurrent diff --git a/tests/unit/hash/CMakeLists.txt b/tests/unit/hash/CMakeLists.txt new file mode 100644 index 00000000..79dfd8c0 --- /dev/null +++ b/tests/unit/hash/CMakeLists.txt @@ -0,0 +1,8 @@ +add_executable (test_lookup3 + test_lookup3.c + ${CMAKE_SOURCE_DIR}/lib/lookup3.c + ${CMAKE_SOURCE_DIR}/lib/wsprd/nhash.c + ${CMAKE_SOURCE_DIR}/lib/wsprcode/nhash.c + ${CMAKE_SOURCE_DIR}/lib/superfox/qpc/nhash2.c) + +add_test (NAME test_lookup3 COMMAND test_lookup3) diff --git a/tests/unit/hash/test_lookup3.c b/tests/unit/hash/test_lookup3.c new file mode 100644 index 00000000..11ea1ac8 --- /dev/null +++ b/tests/unit/hash/test_lookup3.c @@ -0,0 +1,111 @@ +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> + +#include "lib/lookup3.h" +#include "lib/superfox/qpc/nhash2.h" +#include "lib/wsprd/nhash.h" + +uint32_t nhash_(const void *key, int *length, uint32_t *initval); + +static const uint32_t expected_hashes[] = { + UINT32_C(0xdeadc12a), UINT32_C(0x1b94435d), UINT32_C(0xd2deb219), + UINT32_C(0x6155e046), UINT32_C(0xf9db3ff3), UINT32_C(0x999875df), + UINT32_C(0xcf4a698e), UINT32_C(0x11d73cee), UINT32_C(0x06349a85), + UINT32_C(0x434bac56), UINT32_C(0x11ead3ab), UINT32_C(0x4c191765), + UINT32_C(0xf4195417), UINT32_C(0xe8d7137c), UINT32_C(0x2e8d5a88), + UINT32_C(0xb0414d93), UINT32_C(0x07c55374), UINT32_C(0x110c468c), + UINT32_C(0x4afa5bbc), UINT32_C(0x4944bccc), UINT32_C(0x4cbb7a1b), + UINT32_C(0x18516846), UINT32_C(0x3b97ae23), UINT32_C(0x44867164), + UINT32_C(0x3002d5f9), UINT32_C(0x595cdc5d), UINT32_C(0xec15a036), + UINT32_C(0xc0d1e3b0), UINT32_C(0x7f471a40), UINT32_C(0x04391f70), + UINT32_C(0xbceebda2), UINT32_C(0xa5721abb), UINT32_C(0x365f9634), + UINT32_C(0x086509a4), UINT32_C(0xc87ed5da), UINT32_C(0xd16fd5fd), + UINT32_C(0xa7ca90d1), UINT32_C(0xfe888aa0), UINT32_C(0xab82ce67), + UINT32_C(0xbd2683b1), UINT32_C(0x5ce3f5eb), UINT32_C(0xe526881b), + UINT32_C(0x4f2ad0bc), UINT32_C(0x083f24ee), UINT32_C(0xee9ebcad), + UINT32_C(0x7b890b41), UINT32_C(0x5f600c7a), UINT32_C(0xf9307a08), + UINT32_C(0x9025c6d7), UINT32_C(0x8bf9cd5c), UINT32_C(0x5e7fc68f), + UINT32_C(0x980ec2aa), UINT32_C(0xcfef4469), UINT32_C(0x51df097b), + UINT32_C(0xf716bb46), UINT32_C(0x5ccbf75a), UINT32_C(0x2b345185), + UINT32_C(0x6a53fdc1), UINT32_C(0x4b3f9153), UINT32_C(0x0c5cb07a), + UINT32_C(0xcdad2a44), UINT32_C(0x434b9089), UINT32_C(0x08a090f3), + UINT32_C(0x504ccef9), UINT32_C(0x8183308b) +}; + +static int failures; + +static void expect_hash(const char *api, size_t offset, size_t length, + uint32_t actual, uint32_t expected) +{ + if (actual != expected) { + fprintf(stderr, + "%s offset %zu length %zu: expected %08x, got %08x\n", + api, offset, length, expected, actual); + ++failures; + } +} + +static unsigned char test_byte(size_t index, size_t length) +{ + return (unsigned char)(index * 37U + length * 11U); +} + +int main(void) +{ + const uint32_t seed = UINT32_C(571); + + for (size_t offset = 0; offset < 4; ++offset) { + for (size_t length = 0; length < sizeof expected_hashes / sizeof *expected_hashes; + ++length) { + size_t allocation_size = offset + length; + if (allocation_size == 0) allocation_size = 1; + unsigned char *allocation = malloc(allocation_size); + if (allocation == NULL) { + fputs("allocation failed\n", stderr); + return 2; + } + + unsigned char *key = allocation + offset; + for (size_t i = 0; i < length; ++i) key[i] = test_byte(i, length); + + uint32_t expected = expected_hashes[length]; + expect_hash("wsjt_hashlittle", offset, length, + wsjt_hashlittle(key, length, seed), expected); + expect_hash("nhash2", offset, length, + nhash2(key, length, seed), expected); + + uint32_t wspr_expected = length == 0 ? expected : expected & UINT32_C(0x7fff); + expect_hash("nhash", offset, length, + nhash(key, length, seed), wspr_expected); + + int legacy_length = (int)length; + uint32_t legacy_seed = seed; + expect_hash("nhash_", offset, length, + nhash_(key, &legacy_length, &legacy_seed), expected); + free(allocation); + } + } + + unsigned char superfox_symbols[47]; + for (size_t i = 0; i < sizeof superfox_symbols; ++i) { + superfox_symbols[i] = (unsigned char)i; + } + uint32_t superfox_crc = nhash2(superfox_symbols, sizeof superfox_symbols, + seed) & UINT32_C(0x1fffff); + expect_hash("SuperFox CRC21", 0, sizeof superfox_symbols, + superfox_crc, UINT32_C(0x14d1ab)); + + unsigned char abc[] = {'a', 'b', 'c'}; + expect_hash("seed 146 empty", 0, 0, + wsjt_hashlittle(abc, 0, UINT32_C(146)), UINT32_C(0xdeadbf81)); + expect_hash("seed 146 abc", 0, sizeof abc, + wsjt_hashlittle(abc, sizeof abc, UINT32_C(146)), + UINT32_C(0x3f227c14)); + expect_hash("WSPR seed 146 abc", 0, sizeof abc, + nhash(abc, sizeof abc, UINT32_C(146)), UINT32_C(0x7c14)); + + if (failures != 0) return 1; + puts("lookup3 tests passed: 260 aligned and unaligned vectors"); + return 0; +} diff --git a/tests/unit/hrd/CMakeLists.txt b/tests/unit/hrd/CMakeLists.txt new file mode 100644 index 00000000..4981b132 --- /dev/null +++ b/tests/unit/hrd/CMakeLists.txt @@ -0,0 +1,6 @@ +add_executable (test_hrd_message + test_hrd_message.cpp + ${CMAKE_SOURCE_DIR}/Transceiver/HRDMessage.cpp +) +target_link_libraries (test_hrd_message Qt5::Test) +add_test (NAME test_hrd_message COMMAND test_hrd_message) diff --git a/tests/unit/hrd/test_hrd_message.cpp b/tests/unit/hrd/test_hrd_message.cpp new file mode 100644 index 00000000..741355b4 --- /dev/null +++ b/tests/unit/hrd/test_hrd_message.cpp @@ -0,0 +1,168 @@ +#include <QtTest> + +#include "Transceiver/HRDMessage.hpp" + +namespace +{ + quint32 u32le (QByteArray const& bytes, int offset) + { + return static_cast<quint32> (static_cast<quint8> (bytes[offset])) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 1])) << 8) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 2])) << 16) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 3])) << 24); + } + + void write_u32le (QByteArray * bytes, int offset, quint32 value) + { + (*bytes)[offset] = static_cast<char> (value & 0xffu); + (*bytes)[offset + 1] = static_cast<char> ((value >> 8) & 0xffu); + (*bytes)[offset + 2] = static_cast<char> ((value >> 16) & 0xffu); + (*bytes)[offset + 3] = static_cast<char> ((value >> 24) & 0xffu); + } +} + +class TestHRDMessage final + : public QObject +{ + Q_OBJECT + +private slots: + void buildsBinaryMessage () + { + auto const message = HRDMessage::make ("get radio"); + + QCOMPARE (u32le (message, 0), static_cast<quint32> (message.size ())); + QCOMPARE (u32le (message, 4), quint32 (0x1234ABCD)); + QCOMPARE (u32le (message, 8), quint32 (0xABCD1234)); + QCOMPARE (u32le (message, 12), quint32 (0)); + QCOMPARE (message.size (), HRDMessage::header_size () + (QString {"get radio"}.size () + 1) * 2); + QCOMPARE (static_cast<quint8> (message[message.size () - 2]), quint8 (0)); + QCOMPARE (static_cast<quint8> (message[message.size () - 1]), quint8 (0)); + } + + void parsesValidMessage () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("FTDX-3000")); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {"FTDX-3000"}); + } + + void preservesUtf16Payload () + { + QString payload {"Rig "}; + payload.append (QChar {0x00d8}); + + auto const parsed = HRDMessage::parse (HRDMessage::make (payload)); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, payload); + } + + void usesDeclaredSizeForPayload () + { + auto message = HRDMessage::make ("OK"); + message.append ("ignored"); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {"OK"}); + QCOMPARE (parsed.required_size, HRDMessage::make ("OK").size ()); + } + + void roundTripsEmptyPayload () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("")); + + QVERIFY (parsed.valid); + QVERIFY (parsed.complete); + QCOMPARE (parsed.payload, QString {}); + } + + void reportsPartialHeader () + { + auto const parsed = HRDMessage::parse (HRDMessage::make ("OK").left (8)); + + QVERIFY (parsed.valid); + QVERIFY (!parsed.complete); + QCOMPARE (parsed.required_size, HRDMessage::header_size ()); + } + + void reportsPartialBody () + { + auto const message = HRDMessage::make ("OK"); + auto const parsed = HRDMessage::parse (message.left (message.size () - 1)); + + QVERIFY (parsed.valid); + QVERIFY (!parsed.complete); + QCOMPARE (parsed.required_size, message.size ()); + } + + void rejectsInvalidMagic1 () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 4, 0); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsInvalidMagic2 () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 8, 0); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsHeaderSize () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, HRDMessage::header_size () - 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsOversizedMessage () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, HRDMessage::max_message_size () + 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsOddUtf16Payload () + { + auto message = HRDMessage::make ("OK"); + write_u32le (&message, 0, message.size () - 1); + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } + + void rejectsMissingTerminator () + { + auto message = HRDMessage::make ("OK"); + message[message.size () - 2] = 'X'; + + auto const parsed = HRDMessage::parse (message); + + QVERIFY (!parsed.valid); + } +}; + +QTEST_MAIN (TestHRDMessage) + +#include "test_hrd_message.moc" diff --git a/tests/unit/jpl/CMakeLists.txt b/tests/unit/jpl/CMakeLists.txt new file mode 100644 index 00000000..afaf718f --- /dev/null +++ b/tests/unit/jpl/CMakeLists.txt @@ -0,0 +1,48 @@ +add_executable (test_jpl_setup test_jpl_setup.f90) +wsjt_link_common_fortran (test_jpl_setup) + +add_test (NAME test_jpl_setup COMMAND test_jpl_setup) + +add_executable (test_emedop ../../../lib/emedop.f90) +wsjt_link_common_fortran (test_emedop) + +add_test (NAME test_emedop_invalid_start + COMMAND test_emedop emedop_invalid_start.txt) +set_tests_properties (test_emedop_invalid_start PROPERTIES + PASS_REGULAR_EXPRESSION "Invalid date or time in input file" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + +add_test (NAME test_emedop_cross_date + COMMAND test_emedop emedop_cross_date.txt) +set_tests_properties (test_emedop_cross_date PROPERTIES + PASS_REGULAR_EXPRESSION "Start and stop dates must be the same" + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) + +add_executable (test_jpl_resilience test_jpl_resilience.f90) +wsjt_link_common_fortran (test_jpl_resilience) + +set (jpl_ephemeris_file "${CMAKE_SOURCE_DIR}/contrib/Ephemeris/JPLEPH") +set (jpl_resilience_scenarios + valid_reference + unit_collision + missing_fallback + analytic_failure + truncated_header + truncated_coefficients + absurd_coefficients + invalid_header + out_of_range + nonfinite_epoch + invalid_input + blank_grid_compatibility + optional_sections + source_transition) + +foreach (scenario IN LISTS jpl_resilience_scenarios) + set (test_name "test_jpl_resilience_${scenario}") + add_test (NAME ${test_name} + COMMAND test_jpl_resilience ${scenario} ${jpl_ephemeris_file}) + set_tests_properties (${test_name} PROPERTIES + PASS_REGULAR_EXPRESSION "PASS ${scenario}" + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}) +endforeach () diff --git a/tests/unit/jpl/emedop_cross_date.txt b/tests/unit/jpl/emedop_cross_date.txt new file mode 100644 index 00000000..d30f109c --- /dev/null +++ b/tests/unit/jpl/emedop_cross_date.txt @@ -0,0 +1,8 @@ + 40 + 105 + 41 + 75 + 144000000 + 20240101 12 00 00 + 20240102 12 01 00 + 60 diff --git a/tests/unit/jpl/emedop_invalid_start.txt b/tests/unit/jpl/emedop_invalid_start.txt new file mode 100644 index 00000000..587a6889 --- /dev/null +++ b/tests/unit/jpl/emedop_invalid_start.txt @@ -0,0 +1,8 @@ + 40 + 105 + 41 + 75 + 144000000 + 20240230 12 00 00 + 20240230 12 01 00 + 60 diff --git a/tests/unit/jpl/test_jpl_resilience.f90 b/tests/unit/jpl/test_jpl_resilience.f90 new file mode 100644 index 00000000..b37cd470 --- /dev/null +++ b/tests/unit/jpl/test_jpl_resilience.f90 @@ -0,0 +1,693 @@ +program test_jpl_resilience + use iso_c_binding, only: c_bool, c_char, c_double, c_int, c_loc, & + c_null_char + use iso_fortran_env, only: int8, real64 + use ieee_arithmetic, only: ieee_is_finite, ieee_value, & + ieee_quiet_nan, ieee_positive_inf + use astro_module, only: astrosub + use jpl_ephemeris_status + implicit none + + character(len=64) :: scenario + character(len=1024) :: source_path + + call get_command_argument(1,scenario) + call get_command_argument(2,source_path) + if(len_trim(scenario).eq.0 .or. len_trim(source_path).eq.0) error stop 1 + + select case(trim(scenario)) + case('valid_reference') + call test_valid_reference(trim(source_path)) + case('unit_collision') + call test_unit_collision(trim(source_path)) + case('missing_fallback') + call test_missing_fallback() + case('analytic_failure') + call test_analytic_failure() + case('truncated_header') + call test_truncated_header(trim(source_path)) + case('truncated_coefficients') + call test_truncated_coefficients(trim(source_path)) + case('absurd_coefficients') + call test_absurd_coefficients(trim(source_path)) + case('invalid_header') + call test_invalid_header(trim(source_path)) + case('out_of_range') + call test_out_of_range(trim(source_path)) + case('nonfinite_epoch') + call test_nonfinite_epoch(trim(source_path)) + case('invalid_input') + call test_invalid_input() + case('blank_grid_compatibility') + call test_blank_grid_compatibility(trim(source_path)) + case('optional_sections') + call test_optional_sections(trim(source_path)) + case('source_transition') + call test_source_transition(trim(source_path)) + case default + error stop 2 + end select + + print '(a)', 'PASS '//trim(scenario) + +contains + + subroutine test_valid_reference(path) + character(len=*), intent(in) :: path + real(real64) :: vector(6) + real(real64), parameter :: expected(6) = [ & + -6.141033948345347e-4_real64,-2.105916028962251e-3_real64, & + -9.713000936360162e-4_real64, 6.128034786394336e-4_real64, & + -1.145724331397477e-4_real64,-1.097685197949237e-4_real64] + integer :: status + + call configure(path) + call pleph(2459580.5_real64,10,3,vector,status) + call require(status.eq.JPL_STATUS_OK,'valid JPL status') + call require(maxval(abs(vector-expected)).lt.1.0e-14_real64, & + 'fixed reference vector') + end subroutine test_valid_reference + + subroutine test_unit_collision(path) + character(len=*), intent(in) :: path + real(real64) :: vector(6) + integer :: status + logical :: opened + + open(12,status='scratch',action='readwrite') + call configure(path) + call pleph(2459580.5_real64,10,3,vector,status) + inquire(unit=12,opened=opened) + call require(status.eq.JPL_STATUS_OK,'JPL with occupied unit 12') + call require(opened,'unit 12 preserved') + close(12) + end subroutine test_unit_collision + + subroutine test_missing_fallback() + real(real64) :: fallback(8),forced(8) + real(real64) :: vector(6),pvsun(6) + integer :: result,status + logical :: km,bary + common/stcomx/km,bary,pvsun + + call configure('missing-jpleph') + call ephem_values(60310.5_real64,0,fallback,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'missing file fallback status') + call ephem_values(60310.5_real64,8,forced,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'forced analytic status') + call require(maxval(abs(fallback-forced)).lt.1.0e-10_real64, & + 'missing file matches analytic calculation') + + bary=.false. + km=.false. + call configure('another-missing-jpleph') + call pleph(2459580.5_real64,10,3,vector,status) + call require(status.eq.JPL_STATUS_IO_ERROR,'missing file status') + call require(all(vector.eq.0.0_real64),'failed PLEPH zero output') + call require(.not.bary,'failed PLEPH restores BARY') + end subroutine test_missing_fallback + + subroutine test_analytic_failure() + real(real64) :: outputs(8) + integer :: result + + call configure('missing-analytic-failure.jpl') + call ephem_values(1.0e200_real64,0,outputs,result) + call require(result.eq.EPHEMERIS_UNAVAILABLE, & + 'analytic failure status') + call require(all(outputs.eq.0.0_real64), & + 'analytic failure zero outputs') + end subroutine test_analytic_failure + + subroutine test_truncated_header(path) + character(len=*), intent(in) :: path + integer(int8) :: bytes(128) + integer :: input,output,ios,result + real(real64) :: values(8) + + open(newunit=input,file=path,access='stream',form='unformatted', & + status='old',action='read') + read(input,iostat=ios) bytes + call require(ios.eq.0,'read source header prefix') + close(input) + open(newunit=output,file='truncated-header.jpl',access='stream', & + form='unformatted',status='replace',action='write') + write(output) bytes + close(output) + call configure('truncated-header.jpl') + call ephem_values(60310.5_real64,0,values,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'truncated header fallback') + end subroutine test_truncated_header + + subroutine test_truncated_coefficients(path) + character(len=*), intent(in) :: path + character(len=6) :: names(1000) + integer :: result,status,n + real(real64) :: values(8),constants(1000),range(3),vector(6) + + call copy_records(path,'header-only.jpl',2) + call configure('header-only.jpl') + call ephem_values(60310.5_real64,0,values,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'missing coefficient record fallback') + + call configure(path) + call const(names,constants,range,n) + call require(n.gt.0,'read source ephemeris range') + call copy_records(path,'truncated-coefficients.jpl',3) + call truncate_last_record('truncated-coefficients.jpl') + call configure('truncated-coefficients.jpl') + call pleph(range(1)+0.5_real64*range(3),10,3,vector,status) + call require(status.eq.JPL_STATUS_IO_ERROR, & + 'partial third coefficient record status') + call require(all(vector.eq.0.0_real64), & + 'partial coefficient read zero output') + end subroutine test_truncated_coefficients + + subroutine test_absurd_coefficients(path) + character(len=*), intent(in) :: path + real(real64) :: fallback(8),forced(8),mjd + integer :: result + + call copy_records(path,'absurd-coefficients.jpl',3) + call rewrite_absurd_lunar_coefficients('absurd-coefficients.jpl',mjd) + call configure('absurd-coefficients.jpl') + call ephem_values(mjd,0,fallback,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'absurd finite coefficients trigger fallback') + call require(all(ieee_is_finite(fallback)), & + 'absurd coefficient fallback remains finite') + call ephem_values(mjd,8,forced,result) + call require(maxval(abs(fallback-forced)).lt.1.0e-10_real64, & + 'absurd coefficient fallback is atomic') + end subroutine test_absurd_coefficients + + subroutine test_invalid_header(path) + character(len=*), intent(in) :: path + integer :: result,status + real(real64) :: values(8),vector(6),record_epoch + + call copy_records(path,'invalid-header.jpl',3) + call rewrite_header('invalid-header.jpl',.true.,.false.,.false.) + call configure('invalid-header.jpl') + call ephem_values(60310.5_real64,0,values,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'invalid header fallback') + + call copy_records(path,'invalid-ncon.jpl',3) + call rewrite_ncon('invalid-ncon.jpl') + call configure('invalid-ncon.jpl') + call ephem_values(60310.5_real64,0,values,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'oversized constant count fallback') + + call copy_records(path,'invalid-coefficient-count.jpl',3) + call rewrite_header('invalid-coefficient-count.jpl',.false., & + .false.,.true.) + call configure('invalid-coefficient-count.jpl') + call ephem_values(60310.5_real64,0,values,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'oversized interpolation coefficient count fallback') + + call copy_records(path,'invalid-record-step.jpl',3) + call rewrite_header('invalid-record-step.jpl',.false.,.false., & + .false.,.true.,record_epoch) + call configure('invalid-record-step.jpl') + call pleph(record_epoch,10,3,vector,status) + call require(status.eq.JPL_STATUS_INVALID_HEADER, & + 'unrepresentable record index status') + call require(all(vector.eq.0.0_real64), & + 'unrepresentable record index zero output') + end subroutine test_invalid_header + + subroutine test_out_of_range(path) + character(len=*), intent(in) :: path + real(real64) :: vector(6) + integer :: status + + call configure(path) + call pleph(1.0_real64,10,3,vector,status) + call require(status.eq.JPL_STATUS_OUT_OF_RANGE,'early range status') + call pleph(1.0e9_real64,10,3,vector,status) + call require(status.eq.JPL_STATUS_OUT_OF_RANGE,'late range status') + call pleph(2459580.5_real64,16,3,vector,status) + call require(status.eq.JPL_STATUS_INVALID_REQUEST, & + 'invalid target status') + call require(all(vector.eq.0.0_real64),'invalid target zero output') + call pleph(2459580.5_real64,16,16,vector,status) + call require(status.eq.JPL_STATUS_INVALID_REQUEST, & + 'equal invalid target status') + end subroutine test_out_of_range + + subroutine test_nonfinite_epoch(path) + character(len=*), intent(in) :: path + real(real64) :: vector(6),epoch + integer :: status + + call configure(path) + epoch=ieee_value(0.0_real64,ieee_quiet_nan) + call pleph(epoch,10,3,vector,status) + call require(status.eq.JPL_STATUS_INVALID_REQUEST,'NaN epoch status') + call require(all(vector.eq.0.0_real64),'NaN epoch zero output') + + epoch=ieee_value(0.0_real64,ieee_positive_inf) + call pleph(epoch,10,3,vector,status) + call require(status.eq.JPL_STATUS_INVALID_REQUEST, & + 'infinite epoch status') + call require(all(vector.eq.0.0_real64),'infinite epoch zero output') + end subroutine test_nonfinite_epoch + + subroutine test_invalid_input() + real :: outputs(8),astro_outputs(19) + real :: uth + integer :: result,values(8),year,month,day,ntsky + + call moon_values(2024,2,30,12.0,outputs,result) + call require(result.eq.EPHEMERIS_INVALID_INPUT,'invalid date status') + call require(all(outputs.eq.0.0),'invalid date zero outputs') + call moon_values(2024,1,1,24.0,outputs,result) + call require(result.eq.EPHEMERIS_INVALID_INPUT,'invalid UT status') + call require(all(outputs.eq.0.0),'invalid UT zero outputs') + call direct_astro_values(24.0,astro_outputs,ntsky,result) + call require(result.eq.EPHEMERIS_INVALID_INPUT, & + 'astro propagates integer invalid status') + call require(ntsky.eq.0 .and. all(astro_outputs.eq.0.0), & + 'astro clears invalid derived outputs') + + values=[2024,1,1,60,0,15,0,0] + call normalize_utc_calendar(values,year,month,day,uth) + call require(year.eq.2023 .and. month.eq.12 .and. day.eq.31, & + 'UTC calendar borrows across year') + call require(abs(uth-23.25).lt.1.0e-5,'UTC hour after borrow') + + values=[2023,12,31,-60,23,45,0,0] + call normalize_utc_calendar(values,year,month,day,uth) + call require(year.eq.2024 .and. month.eq.1 .and. day.eq.1, & + 'UTC calendar carries across year') + call require(abs(uth-0.75).lt.1.0e-5,'UTC hour after carry') + + values=[2024,3,1,60,0,30,0,0] + call normalize_utc_calendar(values,year,month,day,uth) + call require(year.eq.2024 .and. month.eq.2 .and. day.eq.29, & + 'UTC calendar handles leap day') + end subroutine test_invalid_input + + subroutine test_blank_grid_compatibility(path) + character(len=*), intent(in) :: path + character(len=6) :: blank_grid=' ' + character(len=6) :: legacy_grid='BB44mm' + character(len=6) :: valid_grid='FN20qi' + character(len=6) :: dx_grid='JN18du' + real(real64) :: blank_values(20),legacy_values(20),blank_dx_values(20) + real(real64) :: both_blank_values(20) + real(c_double) :: blank_sub_values(14),legacy_sub_values(14) + real(c_double) :: blank_dx_sub_values(14) + integer :: blank_integers(3),legacy_integers(3),blank_dx_integers(3) + integer :: both_blank_integers(3),result + integer(c_int) :: blank_sub_integers(3),legacy_sub_integers(3) + integer(c_int) :: blank_dx_sub_integers(3),sub_result + + call configure(path) + call grid_astro_values(blank_grid,dx_grid,blank_values, & + blank_integers,result) + call require(result.eq.EPHEMERIS_JPL,'blank local grid status') + + call grid_astro_values(legacy_grid,dx_grid,legacy_values, & + legacy_integers,result) + call require(result.eq.EPHEMERIS_JPL,'legacy local grid status') + call require(maxval(abs(blank_values(1:15)- & + legacy_values(1:15))).lt.1.0e-10_real64, & + 'blank local grid legacy values') + call require(maxval(abs(blank_values(17:20)- & + legacy_values(17:20))).lt.1.0e-10_real64, & + 'blank local grid legacy widths and delay') + call require(all(blank_integers.eq.legacy_integers), & + 'blank local grid legacy integer values') + + call astrosub_values(blank_grid,dx_grid,path,blank_sub_values, & + blank_sub_integers,sub_result) + call require(sub_result.eq.EPHEMERIS_JPL, & + 'blank local grid astrosub status') + call astrosub_values(legacy_grid,dx_grid,path,legacy_sub_values, & + legacy_sub_integers,sub_result) + call require(sub_result.eq.EPHEMERIS_JPL, & + 'legacy local grid astrosub status') + call require(maxval(abs(blank_sub_values-legacy_sub_values)).lt. & + 1.0e-10_real64,'blank local grid astrosub legacy values') + call require(all(blank_sub_integers.eq.legacy_sub_integers), & + 'blank local grid astrosub legacy integer values') + + call grid_astro_values(valid_grid,blank_grid,blank_dx_values, & + blank_dx_integers,result) + call require(result.eq.EPHEMERIS_JPL,'blank DX grid status') + call require(blank_dx_values(18).eq.blank_dx_values(17), & + 'blank DX grid uses self width') + call require(blank_dx_values(14).eq.0.0_real64, & + 'blank DX grid clears MNR') + + call astrosub_values(valid_grid,blank_grid,path, & + blank_dx_sub_values,blank_dx_sub_integers,sub_result) + call require(sub_result.eq.EPHEMERIS_JPL, & + 'blank DX grid astrosub status') + call require(all(blank_dx_sub_values([5,6,11,14]).eq. & + 0.0_real64),'blank DX grid clears astrosub DX values') + call require(blank_dx_sub_integers(2).eq.0, & + 'blank DX grid clears astrosub Doppler') + call require(maxval(abs(blank_dx_sub_values(1:4)- & + blank_dx_values(1:4))).lt.1.0e-10_real64, & + 'blank DX grid preserves local azimuth and elevation') + call require(blank_dx_sub_values(13).eq.blank_dx_values(17), & + 'blank DX grid preserves self width') + call require(blank_dx_sub_integers(1).eq.blank_dx_integers(1) & + .and. blank_dx_sub_integers(3).eq.blank_dx_integers(3), & + 'blank DX grid preserves local integer values') + + call grid_astro_values(blank_grid,blank_grid,both_blank_values, & + both_blank_integers,result) + call require(result.eq.EPHEMERIS_JPL,'both grids blank status') + call require(all(ieee_is_finite(both_blank_values)), & + 'both grids blank finite values') + call require(both_blank_values(20).gt.0.0_real64, & + 'both grids blank echo delay') + + call configure('missing-blank-grid.jpl') + call grid_astro_values(blank_grid,blank_grid,both_blank_values, & + both_blank_integers,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'blank grids preserve analytic fallback') + call astrosub_values(blank_grid,blank_grid, & + 'missing-blank-grid.jpl',blank_dx_sub_values, & + blank_dx_sub_integers,sub_result) + call require(sub_result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'blank grids preserve astrosub analytic fallback') + call require(all(blank_dx_sub_values([5,6,11,14]).eq. & + 0.0_real64) .and. blank_dx_sub_integers(2).eq.0, & + 'blank grids preserve astrosub DX clearing') + end subroutine test_blank_grid_compatibility + + subroutine test_optional_sections(path) + character(len=*), intent(in) :: path + real(real64) :: vector(6) + integer :: status + + call copy_records(path,'no-optional-sections.jpl',3) + call rewrite_header('no-optional-sections.jpl',.false.,.true., & + .false.) + call configure('no-optional-sections.jpl') + call pleph(2459580.5_real64,14,0,vector,status) + call require(status.eq.JPL_STATUS_NOT_AVAILABLE, & + 'absent nutation status') + call pleph(2459580.5_real64,15,0,vector,status) + call require(status.eq.JPL_STATUS_NOT_AVAILABLE, & + 'absent libration status') + end subroutine test_optional_sections + + subroutine test_source_transition(path) + character(len=*), intent(in) :: path + real(real64) :: dfdt,dfdt0 + integer :: result + real :: fspread_self,fspread_dx + common/echocom2/fspread_self,fspread_dx + + call configure(path) + call astro_values(12.0_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_JPL,'transition starts with JPL') + call astro_values(12.001_real64,dfdt,dfdt0,result) + call require(abs(dfdt)+abs(dfdt0).gt.0.0_real64, & + 'transition establishes derivative history') + call configure(path) + call astro_values(12.002_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_JPL,'reader reset retains JPL') + call require(dfdt.eq.0.0_real64 .and. dfdt0.eq.0.0_real64, & + 'reader generation resets derivative') + call astro_values(24.0_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_INVALID_INPUT, & + 'transition rejects invalid input') + call require(fspread_self.eq.0.0 .and. fspread_dx.eq.0.0, & + 'invalid input clears saved echo spreads') + call astro_values(12.003_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_JPL,'transition recovers JPL') + call require(dfdt.eq.0.0_real64 .and. dfdt0.eq.0.0_real64, & + 'invalid input resets derivative history') + call configure('missing-transition.jpl') + call astro_values(12.004_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'transition enters fallback') + call require(dfdt.eq.0.0_real64 .and. dfdt0.eq.0.0_real64, & + 'source transition resets derivative') + call astro_values(12.005_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_ANALYTIC_FALLBACK, & + 'failed configuration remains in fallback') + call configure(path) + call astro_values(12.006_real64,dfdt,dfdt0,result) + call require(result.eq.EPHEMERIS_JPL, & + 'configuration reset retries JPL') + call require(dfdt.eq.0.0_real64 .and. dfdt0.eq.0.0_real64, & + 'configuration reset clears derivative history') + end subroutine test_source_transition + + subroutine configure(path) + character(len=*), intent(in) :: path + character(len=256) :: configured + + configured=path + call jpl_setup(configured) + end subroutine configure + + subroutine ephem_values(mjd,nspecial,values,result) + real(real64), intent(in) :: mjd + integer, intent(in) :: nspecial + real(real64), intent(out) :: values(8) + integer, intent(out) :: result + + call ephem(mjd,-0.460_real64,-1.8326_real64,0.7106_real64, & + 40.0_real64,nspecial,values(1),values(2),values(3), & + values(4),values(5),values(6),values(7),values(8),result) + end subroutine ephem_values + + subroutine moon_values(year,month,day,uth,outputs,result) + integer, intent(in) :: year,month,day + real, intent(in) :: uth + real, intent(out) :: outputs(8) + integer, intent(out) :: result + + call MoonDopJPL(year,month,day,uth,-105.0,40.0,outputs(1), & + outputs(2),outputs(3),outputs(4),outputs(5),outputs(6), & + outputs(7),outputs(8),result) + end subroutine moon_values + + subroutine direct_astro_values(uth,outputs,ntsky,result) + real, intent(in) :: uth + real, intent(out) :: outputs(19) + integer, intent(out) :: ntsky,result + character(len=6) :: grid='FN20qi' + + call astro(2024,1,1,uth,144000000.0_real64,grid,1,1, & + outputs(1),outputs(2),outputs(3),outputs(4),ntsky, & + outputs(5),outputs(6),outputs(7),outputs(8),outputs(9), & + outputs(10),outputs(11),outputs(12),outputs(13), & + outputs(14),outputs(15),outputs(16),outputs(17), & + outputs(18),outputs(19),result) + end subroutine direct_astro_values + + subroutine astro_values(uth,dfdt,dfdt0,result) + real(real64), intent(in) :: uth + real(real64), intent(out) :: dfdt,dfdt0 + integer, intent(out) :: result + real(real64) :: output(17),width1,width2,techo + integer :: ntsky,ndop,ndop00 + character(len=6) :: mygrid='FN20qi',hisgrid='JN18du' + + call astro0(2024,1,1,uth,144000000.0_real64,mygrid,hisgrid, & + output(1),output(2),output(3),output(4),output(5), & + output(6),ntsky,ndop,ndop00,output(7),output(8),output(9), & + output(10),output(11),output(12),output(13),output(14), & + dfdt,dfdt0,width1,width2,output(15),techo,result) + end subroutine astro_values + + subroutine grid_astro_values(mygrid,hisgrid,values,integer_values, & + result) + character(len=6), intent(in) :: mygrid,hisgrid + real(real64), intent(out) :: values(20) + integer, intent(out) :: integer_values(3),result + + call astro0(2024,1,1,12.0_real64,144000000.0_real64,mygrid, & + hisgrid,values(1),values(2),values(3),values(4),values(5), & + values(6),integer_values(1),integer_values(2), & + integer_values(3),values(7),values(8),values(9),values(10),& + values(11),values(12),values(13),values(14),values(15), & + values(16),values(17),values(18),values(19),values(20), & + result) + end subroutine grid_astro_values + + subroutine astrosub_values(mygrid,hisgrid,jpl_path,values, & + integer_values,result) + character(len=*), intent(in) :: mygrid,hisgrid,jpl_path + real(c_double), intent(out) :: values(14) + integer(c_int), intent(out) :: integer_values(3),result + character(kind=c_char), target :: mygrid_c(7),hisgrid_c(7) + character(kind=c_char), target :: azel_file_c(64),jpl_path_c(1025) + + call assign_c_string(mygrid,mygrid_c) + call assign_c_string(hisgrid,hisgrid_c) + call assign_c_string('blank-grid-azel.dat',azel_file_c) + call assign_c_string(jpl_path,jpl_path_c) + call astrosub(2024_c_int,1_c_int,1_c_int,12.0_c_double, & + 144000000.0_c_double,c_loc(mygrid_c),c_loc(hisgrid_c), & + values(1),values(2),values(3),values(4),values(5), & + values(6),integer_values(1),integer_values(2), & + integer_values(3),values(7),values(8),values(9),values(10),& + values(11),.false._c_bool,values(12),values(13),values(14), & + .false._c_bool,c_loc(azel_file_c),c_loc(jpl_path_c),result) + end subroutine astrosub_values + + subroutine assign_c_string(value,buffer) + character(len=*), intent(in) :: value + character(kind=c_char), intent(out) :: buffer(:) + integer :: i,count + + buffer=c_null_char + count=min(len_trim(value),size(buffer)-1) + do i=1,count + buffer(i)=value(i:i) + enddo + end subroutine assign_c_string + + subroutine copy_records(source,destination,count) + character(len=*), intent(in) :: source,destination + integer, intent(in) :: count + integer(int8) :: record(8144) + integer :: input,output,index,ios + + open(newunit=input,file=source,access='stream',form='unformatted',& + status='old',action='read') + open(newunit=output,file=destination,access='stream', & + form='unformatted',status='replace',action='write') + do index=1,count + read(input,iostat=ios) record + call require(ios.eq.0,'copy source record') + write(output) record + enddo + close(input) + close(output) + end subroutine copy_records + + subroutine truncate_last_record(path) + character(len=*), intent(in) :: path + integer(int8) :: bytes(2*8144+256) + integer :: input,output,ios + + open(newunit=input,file=path,access='stream',form='unformatted', & + status='old',action='read') + read(input,iostat=ios) bytes + call require(ios.eq.0,'read truncated coefficient prefix') + close(input) + open(newunit=output,file=path,access='stream',form='unformatted',& + status='replace',action='write') + write(output) bytes + close(output) + end subroutine truncate_last_record + + subroutine rewrite_absurd_lunar_coefficients(path,mjd) + character(len=*), intent(in) :: path + real(real64), intent(out) :: mjd + character(len=6) :: ttl(14,3),cnam(1000) + real(real64) :: ss(3),au,emrat,coefficients(1018) + integer :: unit,ios,ncon,numde,ipt(3,13),index,j,set_index,first,ncf + + open(newunit=unit,file=path,access='direct',form='unformatted', & + recl=8144,status='old',action='readwrite') + read(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss, & + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3) + call require(ios.eq.0,'read absurd coefficient header') + read(unit,rec=3,iostat=ios) coefficients + call require(ios.eq.0,'read coefficient record for corruption') + ncf=ipt(2,10) + do set_index=1,ipt(3,10) + first=ipt(1,10)+(set_index-1)*3*ncf + coefficients(first:first+3*ncf-1)=0.0_real64 + coefficients(first)=1.0e200_real64 + coefficients(first+ncf)=1.0e200_real64 + coefficients(first+2*ncf)=1.0e200_real64 + enddo + write(unit,rec=3,iostat=ios) coefficients + call require(ios.eq.0,'write absurd lunar coefficients') + close(unit) + mjd=ss(1)+0.5_real64*ss(3)-2400000.5_real64 + end subroutine rewrite_absurd_lunar_coefficients + + subroutine rewrite_header(path,invalid_range,remove_optional, & + invalid_coefficient_count,tiny_record_step,record_epoch) + character(len=*), intent(in) :: path + logical, intent(in) :: invalid_range,remove_optional + logical, intent(in) :: invalid_coefficient_count + logical, intent(in), optional :: tiny_record_step + real(real64), intent(out), optional :: record_epoch + character(len=6) :: ttl(14,3),cnam(1000) + real(real64) :: ss(3),au,emrat + integer :: unit,ios,ncon,numde,ipt(3,13),index,j + + open(newunit=unit,file=path,access='direct',form='unformatted', & + recl=8144,status='old',action='readwrite') + read(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss, & + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3) + call require(ios.eq.0,'read structured header') + if(invalid_range) ss(3)=0.0_real64 + if(present(tiny_record_step)) then + if(tiny_record_step) then + ss(3)=0.25_real64/(4.0_real64*real(huge(0),real64)) + if(present(record_epoch)) record_epoch=ss(1)+0.25_real64 + endif + endif + if(remove_optional) ipt(:,12:13)=0 + if(invalid_coefficient_count) ipt(2,1)=19 + if(ncon.le.400) then + write(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss,& + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3) + else + write(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss,& + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3), & + (cnam(index),index=401,ncon) + endif + call require(ios.eq.0,'write structured header') + close(unit) + end subroutine rewrite_header + + subroutine rewrite_ncon(path) + character(len=*), intent(in) :: path + character(len=6) :: ttl(14,3),cnam(400) + real(real64) :: ss(3),au,emrat + integer :: unit,ios,ncon,numde,ipt(3,13),index,j + + open(newunit=unit,file=path,access='direct',form='unformatted', & + recl=8144,status='old',action='readwrite') + read(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss, & + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3) + call require(ios.eq.0,'read constant count header') + ncon=1001 + write(unit,rec=1,iostat=ios) ttl,(cnam(index),index=1,400),ss, & + ncon,au,emrat,((ipt(index,j),index=1,3),j=1,12),numde, & + (ipt(index,13),index=1,3) + call require(ios.eq.0,'write oversized constant count') + close(unit) + end subroutine rewrite_ncon + + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + print '(a)', 'FAIL '//trim(message) + error stop 1 + endif + end subroutine require + +end program test_jpl_resilience diff --git a/tests/unit/jpl/test_jpl_setup.f90 b/tests/unit/jpl/test_jpl_setup.f90 new file mode 100644 index 00000000..d640f778 --- /dev/null +++ b/tests/unit/jpl/test_jpl_setup.f90 @@ -0,0 +1,18 @@ +program test_jpl_setup + + implicit none + + character*256 fname,jpleph_file_name + common/jplcom/jpleph_file_name + + fname=repeat('x',len(fname)) + call jpl_setup(fname) + if(jpleph_file_name.ne.fname) error stop 1 + + fname='short/path'//char(0) + call jpl_setup(fname) + if(jpleph_file_name.ne.'short/path') error stop 2 + + print*,'JPLEPH path setup test passed' + +end program test_jpl_setup diff --git a/tests/unit/jt65/CMakeLists.txt b/tests/unit/jt65/CMakeLists.txt new file mode 100644 index 00000000..e718d200 --- /dev/null +++ b/tests/unit/jt65/CMakeLists.txt @@ -0,0 +1,33 @@ +# Compile the shared vectors once so parallel test builds have one producer +# for the Fortran module interface. +add_library (jt65_test_vectors STATIC jt65_test_vectors.f90) +set_target_properties (jt65_test_vectors PROPERTIES + Fortran_MODULE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/jt65_test_vectors") +target_include_directories (jt65_test_vectors PUBLIC + "${CMAKE_CURRENT_BINARY_DIR}/jt65_test_vectors") + +add_executable (test_jt65_source_encoding + test_jt65_source_encoding.f90) +wsjt_link_common_fortran (test_jt65_source_encoding) +target_link_libraries (test_jt65_source_encoding PRIVATE jt65_test_vectors) + +add_test (NAME test_jt65_source_encoding COMMAND test_jt65_source_encoding) + +add_executable (test_jt65_decode_pipeline + jt65_test_fixture.f90 + test_jt65_decode_pipeline.f90) +set_source_files_properties (test_jt65_decode_pipeline.f90 PROPERTIES + COMPILE_FLAGS "-Wno-unused-dummy-argument") +wsjt_link_common_fortran (test_jt65_decode_pipeline) +target_link_libraries (test_jt65_decode_pipeline PRIVATE jt65_test_vectors) + +add_test (NAME test_jt65_decode_pipeline COMMAND test_jt65_decode_pipeline) +set_tests_properties (test_jt65_decode_pipeline PROPERTIES + COST 18 + TIMEOUT 180) + +add_executable (test_jt65_xcor_silence + test_jt65_xcor_silence.f90) +wsjt_link_common_fortran (test_jt65_xcor_silence) + +add_test (NAME test_jt65_xcor_silence COMMAND test_jt65_xcor_silence) diff --git a/tests/unit/jt65/jt65_test_fixture.f90 b/tests/unit/jt65/jt65_test_fixture.f90 new file mode 100644 index 00000000..a317f706 --- /dev/null +++ b/tests/unit/jt65/jt65_test_fixture.f90 @@ -0,0 +1,82 @@ +module jt65_test_fixture + + use iso_fortran_env, only: int64, real32, real64 + implicit none + + integer, parameter :: jt65_sample_rate = 12000 + integer, parameter :: jt65_sample_count = 60 * jt65_sample_rate + integer, parameter :: jt65_symbol_count = 126 + real(real64), parameter :: jt65_baud = 11025.0_real64 / 4096.0_real64 + real(real64), parameter :: jt65_pi = 3.1415926535897932384626433832795_real64 + real(real64), parameter :: jt65_amplitude = 28000.0_real64 + +contains + + subroutine make_jt65_wave(samples, tones, mode65, f0, amplitude, noise_amplitude, noise_seed) + real(real32), intent(out) :: samples(:) + integer, intent(in) :: tones(jt65_symbol_count) + integer, intent(in) :: mode65 + real(real64), intent(in) :: f0 + real(real64), intent(in), optional :: amplitude + real(real64), intent(in), optional :: noise_amplitude + integer, intent(in), optional :: noise_seed + real(real64) :: signal_amplitude + real(real64) :: noise_scale, sample_noise, u1, u2 + real(real64) :: phase, frequency, samples_per_symbol + integer(int64) :: noise_state + integer :: sample, signal_sample, output_sample, symbol + + signal_amplitude = jt65_amplitude + if (present(amplitude)) signal_amplitude = amplitude + noise_scale = 0.0_real64 + if (present(noise_amplitude)) noise_scale = noise_amplitude + noise_state = 104729_int64 + if (present(noise_seed)) noise_state = 104729_int64 + int(noise_seed, int64) + if (noise_scale == 0.0_real64) then + samples = 0.0_real32 + else + do sample = 1, size(samples) + noise_state = modulo(16807_int64 * noise_state, 2147483647_int64) + u1 = max(real(noise_state, real64) / 2147483647.0_real64, tiny(1.0_real64)) + noise_state = modulo(16807_int64 * noise_state, 2147483647_int64) + u2 = real(noise_state, real64) / 2147483647.0_real64 + sample_noise = sqrt(-2.0_real64 * log(u1)) * cos(2.0_real64 * jt65_pi * u2) + samples(sample) = real(noise_scale * sample_noise, real32) + end do + end if + phase = 0.0_real64 + samples_per_symbol = real(jt65_sample_rate, real64) / jt65_baud + do signal_sample = 1, size(samples) - jt65_sample_rate + symbol = int(floor(real(signal_sample, real64) / samples_per_symbol)) + 1 + if (symbol > jt65_symbol_count) exit + frequency = f0 + real(tones(symbol), real64) * jt65_baud * real(mode65, real64) + phase = phase + 2.0_real64 * jt65_pi * frequency / real(jt65_sample_rate, real64) + output_sample = jt65_sample_rate + signal_sample + samples(output_sample) = samples(output_sample) + real(signal_amplitude * sin(phase), real32) + end do + end subroutine make_jt65_wave + + subroutine make_map65_wave(dd, tones, mode65, f0) + real(real32), intent(out) :: dd(:,:) + integer, intent(in) :: tones(jt65_symbol_count) + integer, intent(in) :: mode65 + real(real64), intent(in) :: f0 + real(real64) :: phase, frequency, samples_per_symbol + integer :: signal_sample, output_sample, symbol + integer, parameter :: map65_sample_rate = 96000 + + dd = 0.0_real32 + phase = 0.0_real64 + samples_per_symbol = real(map65_sample_rate, real64) / jt65_baud + do signal_sample = 1, size(dd, 2) - map65_sample_rate + symbol = int(floor(real(signal_sample, real64) / samples_per_symbol)) + 1 + if (symbol > jt65_symbol_count) exit + frequency = f0 + real(tones(symbol), real64) * jt65_baud * real(mode65, real64) + phase = phase + 2.0_real64 * jt65_pi * frequency / real(map65_sample_rate, real64) + output_sample = map65_sample_rate + signal_sample + dd(1, output_sample) = real(jt65_amplitude * cos(phase), real32) + dd(2, output_sample) = real(-jt65_amplitude * sin(phase), real32) + end do + end subroutine make_map65_wave + +end module jt65_test_fixture diff --git a/tests/unit/jt65/jt65_test_vectors.f90 b/tests/unit/jt65/jt65_test_vectors.f90 new file mode 100644 index 00000000..ab1ac1e8 --- /dev/null +++ b/tests/unit/jt65/jt65_test_vectors.f90 @@ -0,0 +1,43 @@ +module jt65_test_vectors + implicit none + + integer, parameter :: jt65_symbol_count = 126 + + integer, parameter :: standard_tones(jt65_symbol_count) = [ & + 0, 3, 62, 0, 0, 50, 13, 40, 0, 0, 0, 0, & + 0, 0, 23, 0, 52, 0, 10, 39, 13, 0, 15, 0, & + 0, 3, 58, 0, 26, 47, 63, 0, 0, 0, 62, 21, & + 0, 0, 0, 0, 20, 0, 0, 4, 0, 0, 0, 0, & + 21, 24, 60, 0, 0, 56, 0, 46, 0, 37, 0, 0, & + 46, 30, 0, 0, 30, 0, 53, 0, 13, 0, 6, 17, & + 0, 62, 42, 59, 31, 44, 17, 0, 0, 56, 43, 48, & + 8, 42, 49, 40, 0, 0, 59, 0, 15, 3, 0, 37, & + 0, 0, 31, 0, 20, 0, 52, 0, 51, 35, 0, 0, & + 20, 19, 0, 10, 9, 0, 59, 56, 52, 62, 0, 0, & + 0, 0, 0, 0, 0, 0 ] + + integer, parameter :: ooo_tones(jt65_symbol_count) = [ & + 3, 0, 0, 62, 50, 0, 0, 0, 13, 40, 23, 52, & + 10, 39, 0, 13, 0, 15, 0, 0, 0, 3, 0, 58, & + 26, 0, 0, 47, 0, 0, 0, 63, 62, 21, 0, 0, & + 20, 4, 21, 24, 0, 60, 56, 0, 46, 37, 46, 30, & + 0, 0, 0, 30, 53, 0, 13, 0, 6, 0, 17, 62, & + 0, 0, 42, 59, 0, 31, 0, 44, 0, 17, 0, 0, & + 56, 0, 0, 0, 0, 0, 0, 43, 48, 0, 0, 0, & + 0, 0, 0, 0, 8, 42, 0, 49, 0, 0, 40, 0, & + 59, 15, 0, 3, 0, 37, 0, 31, 0, 0, 20, 52, & + 0, 0, 51, 0, 0, 35, 0, 0, 0, 0, 20, 19, & + 10, 9, 59, 56, 52, 62 ] + +contains + + pure function padded_message(text) result(message) + character(len=*), intent(in) :: text + character(len=22) :: message + + message = ' ' + message(1:min(len_trim(text), len(message))) = & + text(1:min(len_trim(text), len(message))) + end function padded_message + +end module jt65_test_vectors diff --git a/tests/unit/jt65/test_ccf65_correlator.f90 b/tests/unit/jt65/test_ccf65_correlator.f90 new file mode 100644 index 00000000..3dd8917c --- /dev/null +++ b/tests/unit/jt65/test_ccf65_correlator.f90 @@ -0,0 +1,118 @@ +program test_ccf65_correlator + + use ccf65_legacy_mod, only: ccf65 + use four2a_legacy_wrap_mod, only: c2r_legacy, r2c_legacy, JT65_NFFT, JT65_NH + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite, ieee_quiet_nan, ieee_value + implicit none + + integer, parameter :: nhsym = 254 + real, parameter :: expected_sync = 25.8397 + real :: ss(4,322) + integer :: i + real :: sync1, dt, flipk, syncshort, snr2, dt2 + integer :: ipol1, ipol2 + + call test_fft_roundtrip() + + call make_sync_plane(ss, 1.0) + call ccf65(ss, nhsym, 1.0e30, sync1, ipol1, 1, dt, flipk, syncshort, snr2, ipol2, dt2) + call require(sync1 > 0.0, 'normal JT65 sync is detected') + call require(abs(sync1 - expected_sync) < 0.05, 'normal JT65 sync strength') + call require(flipk > 0.0, 'normal JT65 polarity') + call require(ipol1 == 1, 'normal JT65 polarization') + call require(abs(dt + 2.5) < 0.02, 'normal JT65 timing') + call require(syncshort < 0.0, 'normal JT65 is not shorthand') + + call make_sync_plane(ss, -1.0) + call ccf65(ss, nhsym, 1.0e30, sync1, ipol1, 1, dt, flipk, syncshort, snr2, ipol2, dt2) + call require(sync1 > 0.0, 'inverted JT65 sync is detected') + call require(abs(sync1 - expected_sync) < 0.05, 'inverted JT65 sync strength') + call require(flipk < 0.0, 'inverted JT65 polarity') + call require(ipol1 == 1, 'inverted JT65 polarization') + call require(abs(dt + 2.5) < 0.02, 'inverted JT65 timing') + call require(syncshort < 0.0, 'inverted JT65 is not shorthand') + + ss = 0.0 + sync1 = -99.0 + do i = 1, nhsym - 1 + ss(1,i) = 0.01 * real(mod(i,3) - 1) + end do + call ccf65(ss, nhsym, 1.0e30, sync1, ipol1, 1, dt, flipk, syncshort, snr2, ipol2, dt2) + call require(sync1 < 0.0, 'low-signal input is rejected') + call require(syncshort < 0.0, 'low-signal input is not shorthand') + + ss = 0.0 + call ccf65(ss, nhsym, 1.0e30, sync1, ipol1, 1, dt, flipk, syncshort, snr2, ipol2, dt2) + call require(sync1 == -4.0 .and. syncshort == -4.0, 'zero signal has explicit sync defaults') + call require(all_finite(sync1, dt, flipk, syncshort, snr2, dt2), 'zero signal outputs are finite') + + call make_sync_plane(ss, 1.0) + ss(2:4,:) = ieee_value(0.0, ieee_quiet_nan) + call ccf65(ss, nhsym, 1.0e30, sync1, ipol1, 1, dt, flipk, syncshort, snr2, ipol2, dt2) + call require(sync1 > 0.0, 'inactive polarization data does not affect JT65 detection') + call require(all_finite(sync1, dt, flipk, syncshort, snr2, dt2), & + 'inactive polarization data produces finite correlator outputs') + print '(a)', 'ccf65 correlator tests passed' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + + subroutine test_fft_roundtrip() + real :: input(JT65_NFFT), output(JT65_NFFT) + complex :: spectrum(0:JT65_NH) + integer :: k + + do k = 1, JT65_NFFT + input(k) = sin(0.013*real(k)) + 0.25*cos(0.071*real(k)) + end do + + call r2c_legacy(input, spectrum) + call c2r_legacy(spectrum, output) + call require(maxval(abs(output/JT65_NFFT - input)) < 1.0e-5, & + 'legacy packed FFT round trip preserves real samples') + end subroutine test_fft_roundtrip + + logical function all_finite(v1, v2, v3, v4, v5, v6) + real, intent(in) :: v1, v2, v3, v4, v5, v6 + + all_finite = ieee_is_finite(v1) .and. ieee_is_finite(v2) .and. & + ieee_is_finite(v3) .and. ieee_is_finite(v4) .and. & + ieee_is_finite(v5) .and. ieee_is_finite(v6) + end function all_finite + + subroutine make_sync_plane(ss_plane, polarity) + real, intent(out) :: ss_plane(4,322) + real, intent(in) :: polarity + integer, parameter :: npr(126) = [ & + 1,0,0,1,1,0,0,0,1,1,1,1,1,1,0,1,0,1,0,0, & + 0,1,0,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1, & + 0,1,1,0,1,1,1,1,0,0,0,1,1,0,1,0,1,0,1,1, & + 0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1, & + 1,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1, & + 0,1,0,1,0,0,1,1,0,0,1,0,0,1,0,0,0,0,1,1, & + 1,1,1,1,1,1] + integer :: i + real :: target_sum + + ! Build a non-negative spectrum whose adjacent-bin sums have one lag only. + ss_plane = 0.0 + ss_plane(1,1) = 2.0 + do i = 1, nhsym - 1 + target_sum = 4.0 + if (mod(i,2) == 1 .and. (i+1)/2 <= size(npr)) then + target_sum = target_sum + polarity * real(2*npr((i+1)/2) - 1) + endif + ss_plane(1,i+1) = target_sum - ss_plane(1,i) + end do + end subroutine make_sync_plane + +end program test_ccf65_correlator diff --git a/tests/unit/jt65/test_jt65_decode_pipeline.f90 b/tests/unit/jt65/test_jt65_decode_pipeline.f90 new file mode 100644 index 00000000..414b6f80 --- /dev/null +++ b/tests/unit/jt65/test_jt65_decode_pipeline.f90 @@ -0,0 +1,293 @@ +module jt65_pipeline_callback + + use jt65_decode + use jt65_mod, only: s1, s3a + use jt65_test_vectors, only: padded_message + implicit none + + integer :: callback_count + integer :: callback_snr, callback_freq, callback_drift, callback_nflip + integer :: callback_ft, callback_qual, callback_nsmo, callback_nsum, callback_minsync + integer :: callback_message_count, callback_max_nsum + real :: callback_sync, callback_dt, callback_width + character(len=22) :: callback_message + +contains + + subroutine capture_callback(this, sync, snr, dt, freq, drift, nflip, width, & + decoded, ft, qual, nsmo, nsum, minsync) + class(jt65_decoder), intent(inout) :: this + real, intent(in) :: sync, dt, width + integer, intent(in) :: snr, freq, drift, nflip, ft, qual, nsmo, nsum, minsync + character(len=22), intent(in) :: decoded + + callback_count = callback_count + 1 + callback_sync = sync + callback_snr = snr + callback_dt = dt + callback_freq = freq + callback_drift = drift + callback_nflip = nflip + callback_width = width + callback_message = decoded + callback_ft = ft + callback_qual = qual + callback_nsmo = nsmo + callback_nsum = nsum + callback_minsync = minsync + callback_max_nsum = max(callback_max_nsum, nsum) + if (decoded /= padded_message('')) callback_message_count = callback_message_count + 1 + end subroutine capture_callback + +end module jt65_pipeline_callback + +program test_jt65_decode_pipeline + + use iso_fortran_env, only: real32 + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + use jt65_decode + use jt65_pipeline_callback + use jt65_test_fixture + use jt65_test_vectors + implicit none + + type(jt65_decoder) :: decoder + real(real32), allocatable :: samples(:) + allocate(samples(jt65_sample_count)) + call test_clean_modes(samples) + call test_ooo_signal(samples) + call test_silence_and_frequency_rejection(samples) + call test_decoder_reuse(samples, decoder) + call test_auto_clear_average(samples, decoder) + call test_duplicate_average_cursor + print '(a)', 'JT65 decoder pipeline tests passed' + +contains + + subroutine reset_capture() + callback_count = 0 + callback_snr = 0 + callback_freq = 0 + callback_drift = 0 + callback_nflip = 0 + callback_ft = 0 + callback_qual = 0 + callback_nsmo = 0 + callback_nsum = 0 + callback_minsync = 0 + callback_message_count = 0 + callback_max_nsum = 0 + callback_sync = 0.0 + callback_dt = 0.0 + callback_width = 0.0 + callback_message = ' ' + end subroutine reset_capture + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + + subroutine decode_signal(decoder_to_use, waveform, nsubmode, clearave, decode_flags, & + decode_nutc, decode_depth, decode_again) + type(jt65_decoder), intent(inout) :: decoder_to_use + real(real32), intent(in) :: waveform(:) + integer, intent(in) :: nsubmode + logical, intent(in) :: clearave + integer, intent(in), optional :: decode_flags, decode_nutc, decode_depth + logical, intent(in), optional :: decode_again + logical :: newdat, nagain, nrobust, ljt65apon + integer :: npts, nutc, nf1, nf2, nfqso, ntol, minsync, n2pass + integer :: ntrials, naggressive, ndepth, nexp_decode, nQSOProgress + real :: emedelay + character(len=12) :: mycall, hiscall + character(len=6) :: hisgrid + + npts = min(size(waveform), 52 * jt65_sample_rate) + nutc = 1 + if (present(decode_nutc)) nutc = decode_nutc + nf1 = 1300 + nf2 = 1700 + nfqso = 1500 + ntol = 100 + minsync = 0 + n2pass = 1 + ntrials = 1000 + naggressive = 5 + ndepth = 3 + if (present(decode_depth)) ndepth = decode_depth + emedelay = -999.9 + nexp_decode = 32 + if (present(decode_flags)) nexp_decode = decode_flags + nQSOProgress = 6 + newdat = .true. + nagain = .true. + if (present(decode_again)) nagain = decode_again + nrobust = .false. + ljt65apon = .false. + mycall = 'K1ABC ' + hiscall = 'W9XYZ ' + hisgrid = 'FN42 ' + + call decoder_to_use%decode(capture_callback, waveform, npts, newdat, nutc, nf1, nf2, & + nfqso, ntol, nsubmode, minsync, nagain, n2pass, nrobust, ntrials, naggressive, & + ndepth, emedelay, clearave, mycall, hiscall, hisgrid, nexp_decode, nQSOProgress, & + ljt65apon) + end subroutine decode_signal + + subroutine require_decode(expected_message, description) + character(len=*), intent(in) :: expected_message, description + character(len=22) :: expected + + expected = padded_message(expected_message) + call require(callback_count == 1, description//' emits exactly one callback') + call require(callback_message == expected, description//' message') + call require(abs(real(callback_freq) - 1500.0) <= 4.0, description//' frequency') + call require(abs(callback_dt) <= 1.0, description//' timing') + call require(callback_sync > 0.0, description//' sync metric') + call require(ieee_is_finite(callback_sync), description//' finite sync metric') + call require(ieee_is_finite(callback_dt), description//' finite timing') + call require(ieee_is_finite(callback_width), description//' finite width metric') + end subroutine require_decode + + subroutine test_clean_modes(waveform) + real(real32), intent(inout) :: waveform(:) + call reset_capture() + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) + call decode_signal(decoder, waveform, 0, .true.) + call require_decode('K1ABC W9XYZ FN42', 'JT65A clean signal') + + call reset_capture() + call make_jt65_wave(waveform, standard_tones, 4, 1500.0_real64) + call decode_signal(decoder, waveform, 2, .true.) + call require_decode('K1ABC W9XYZ FN42', 'JT65C clean signal') + + call reset_capture() + call make_jt65_wave(waveform, standard_tones, 2, 1500.0_real64) + call decode_signal(decoder, waveform, 1, .true.) + call require_decode('K1ABC W9XYZ FN42', 'JT65B clean signal') + end subroutine test_clean_modes + + subroutine test_ooo_signal(waveform) + real(real32), intent(inout) :: waveform(:) + type(jt65_decoder) :: ooo_decoder + + call reset_capture() + call make_jt65_wave(waveform, ooo_tones, 1, 1500.0_real64) + call decode_signal(ooo_decoder, waveform, 0, .true., 64) + call require_decode('K1ABC W9XYZ FN42', 'JT65A VHF OOO signal') + call require(callback_nflip < 0, 'JT65A VHF OOO signal polarity') + + call reset_capture() + call decode_signal(ooo_decoder, waveform, 0, .true.) + call require(callback_count == 0, 'JT65A HF OOO signal is rejected') + end subroutine test_ooo_signal + + subroutine test_silence_and_frequency_rejection(waveform) + real(real32), intent(inout) :: waveform(:) + + waveform = 0.0_real32 + call reset_capture() + call decode_signal(decoder, waveform, 0, .true.) + call require(callback_count == 0, 'silence produces no callback') + + call make_jt65_wave(waveform, standard_tones, 1, 3000.0_real64) + call reset_capture() + call decode_signal(decoder, waveform, 0, .true.) + call require(callback_count == 0, 'out-of-window signal produces no callback') + end subroutine test_silence_and_frequency_rejection + + subroutine test_decoder_reuse(waveform, decoder_to_use) + real(real32), intent(inout) :: waveform(:) + type(jt65_decoder), intent(inout) :: decoder_to_use + + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .true.) + call require_decode('K1ABC W9XYZ FN42', 'first reused-decoder signal') + + waveform = 0.0_real32 + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .true.) + call require(callback_count == 0, 'reused decoder silence produces no callback') + + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64) + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .true.) + call require_decode('K1ABC W9XYZ FN42', 'second reused-decoder signal') + end subroutine test_decoder_reuse + + subroutine test_auto_clear_average(waveform, decoder_to_use) + real(real32), intent(inout) :: waveform(:) + type(jt65_decoder), intent(inout) :: decoder_to_use + integer, parameter :: averaging_depth = 16 + 128 + real(real64), parameter :: weak_amplitude = 1.1_real64 + real(real64), parameter :: noise_amplitude = 25.0_real64 + + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64, weak_amplitude, & + noise_amplitude, 1) + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .true., 64, 1, averaging_depth, .false.) + call require(callback_message_count == 0, 'weak JT65 signal is saved without decoding') + + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64, weak_amplitude, & + noise_amplitude, 3) + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .false., 64, 3, averaging_depth, .false.) + call require(callback_message_count == 1, 'two weak JT65 signals produce an averaged decode') + call require(callback_max_nsum >= 2, 'averaged JT65 decode reports multiple periods') + + call make_jt65_wave(waveform, standard_tones, 1, 1500.0_real64, weak_amplitude, & + noise_amplitude, 5) + call reset_capture() + call decode_signal(decoder_to_use, waveform, 0, .false., 64, 5, averaging_depth, .false.) + call require(callback_message_count == 0, & + 'auto-clear prevents a previous JT65 average from decoding again') + end subroutine test_auto_clear_average + + subroutine test_duplicate_average_cursor + integer :: nsave, ndepth, neme, nftt, nsum, ndeepave, nQSOProgress + integer :: ntrials, naggressive + logical :: clear_avg65, ljt65apon + character(len=12) :: mycall, hiscall + character(len=6) :: hisgrid + character(len=22) :: avemsg, deepave + real :: qave + + s1=0.0 + s3a=0.0 + nsave=0 + ndepth=3 + neme=0 + nftt=-1 + nsum=-1 + ndeepave=0 + nQSOProgress=0 + ntrials=1000 + naggressive=5 + clear_avg65=.true. + ljt65apon=.false. + mycall='K1ABC ' + hiscall='W9XYZ ' + hisgrid='FN42 ' + + call avg65(1,nsave,1.0,0.0,1,1500,1,100,ndepth,.false.,ntrials, & + naggressive,clear_avg65,neme,mycall,hiscall,hisgrid,nftt,avemsg, & + qave,deepave,nsum,ndeepave,nQSOProgress,ljt65apon) + call require(nsave == 1 .and. nsum == 1, & + 'first average observation occupies the initial slot') + + nsave=2 + call avg65(1,nsave,1.0,0.0,1,1500,1,100,ndepth,.false.,ntrials, & + naggressive,clear_avg65,neme,mycall,hiscall,hisgrid,nftt,avemsg, & + qave,deepave,nsum,ndeepave,nQSOProgress,ljt65apon) + call require(nsave == 1 .and. nsum == 1 .and. nftt == 0, & + 'duplicate average observation does not advance the ring') + end subroutine test_duplicate_average_cursor + +end program test_jt65_decode_pipeline diff --git a/tests/unit/jt65/test_jt65_source_encoding.f90 b/tests/unit/jt65/test_jt65_source_encoding.f90 new file mode 100644 index 00000000..4462cbd9 --- /dev/null +++ b/tests/unit/jt65/test_jt65_source_encoding.f90 @@ -0,0 +1,201 @@ +program test_jt65_source_encoding + use iso_c_binding, only: c_char, c_int + use jt65_test_vectors + implicit none + + interface + subroutine gen65(message, ichk, sent, tones, itype) bind(C, name='gen65') + import c_char, c_int + character(kind=c_char) :: message(23), sent(23) + integer(kind=c_int) :: ichk, tones(126), itype + end subroutine gen65 + end interface + + call test_standard_message() + call test_ooo_message() + call test_message_forms() + call test_shorthand_messages() + print '(a)', 'JT65 source encoding tests passed' + +contains + + subroutine encode(text, ichk, sent, tones, itype) + character(len=*), intent(in) :: text + integer, intent(in) :: ichk + character(len=1), intent(out) :: sent(23) + integer, intent(out) :: tones(jt65_symbol_count), itype + character(len=1) :: message(23) + integer :: i + + message = char(0) + do i = 1, min(len_trim(text), 22) + message(i) = text(i:i) + end do + sent = char(0) + tones = -1 + itype = -1 + call gen65(message, ichk, sent, tones, itype) + end subroutine encode + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + + subroutine require_message(sent, expected, description) + character(len=1), intent(in) :: sent(23) + character(len=22), intent(in) :: expected + character(len=*), intent(in) :: description + character(len=22) :: actual + integer :: i + + actual = ' ' + do i = 1, 22 + actual(i:i) = sent(i) + end do + call require(actual == expected, description) + call require(ichar(sent(23)) == 0, description//' has a null terminator') + end subroutine require_message + + subroutine require_tone_domain(tones, description) + integer, intent(in) :: tones(jt65_symbol_count) + character(len=*), intent(in) :: description + + call require(all(tones == 0 .or. (tones >= 2 .and. tones <= 65)), & + description//' stays in the JT65 tone domain') + end subroutine require_tone_domain + + subroutine test_standard_message() + character(len=1) :: sent(23) + integer :: tones(jt65_symbol_count), itype + character(len=22) :: expected + + call encode('K1ABC W9XYZ FN42', 0, sent, tones, itype) + expected = padded_message('K1ABC W9XYZ FN42') + call require_message(sent, expected, 'standard message') + call require(itype == 1, 'standard message type') + call require(all(tones == standard_tones), 'standard message tone vector') + call require_tone_domain(tones, 'standard message') + call require(count(tones == 0) == 63, 'standard message sync-symbol count') + call require(count(tones /= 0) == 63, 'standard message data-symbol count') + end subroutine test_standard_message + + subroutine test_ooo_message() + character(len=1) :: sent(23), normal_sent(23) + integer :: tones(jt65_symbol_count), normal_tones(jt65_symbol_count), itype + integer :: normal_data(63), ooo_data(63) + character(len=22) :: expected + integer :: i, normal_data_index, ooo_data_index + + call encode('K1ABC W9XYZ FN42', 0, normal_sent, normal_tones, itype) + call encode('K1ABC W9XYZ FN42 OOO', 0, sent, tones, itype) + expected = padded_message('K1ABC W9XYZ FN42 OOO') + call require_message(sent, expected, 'OOO message') + call require(itype == 1, 'OOO message type') + call require(all(tones == ooo_tones), 'OOO message tone vector') + call require_tone_domain(tones, 'OOO message') + call require(count(tones == 0) == 63, 'OOO sync-symbol count') + call require(count(tones /= 0) == 63, 'OOO data-symbol count') + + normal_data_index = 0 + ooo_data_index = 0 + do i = 1, jt65_symbol_count + if (normal_tones(i) /= 0) then + normal_data_index = normal_data_index + 1 + normal_data(normal_data_index) = normal_tones(i) + call require(tones(i) == 0, 'OOO reverses the normal sync polarity') + end if + if (tones(i) /= 0) then + ooo_data_index = ooo_data_index + 1 + ooo_data(ooo_data_index) = tones(i) + call require(normal_tones(i) == 0, 'normal reverses the OOO sync polarity') + end if + end do + call require(normal_data_index == 63, 'normal data count for OOO comparison') + call require(ooo_data_index == 63, 'OOO data count for comparison') + call require(all(normal_data == ooo_data), 'OOO preserves the data codeword') + end subroutine test_ooo_message + + subroutine test_message_forms() + character(len=1) :: sent(23) + integer :: tones(jt65_symbol_count), itype + character(len=22) :: expected + + call encode('1A/KA1ABC WB9XYZ', 0, sent, tones, itype) + expected = padded_message('1A/KA1ABC WB9XYZ') + call require_message(sent, expected, 'type 1 prefix message') + call require(itype == 2, 'type 1 prefix message type') + call require_tone_domain(tones, 'type 1 prefix message') + + call encode('KA1ABC WB9XYZ/P', 0, sent, tones, itype) + expected = padded_message('KA1ABC WB9XYZ/P') + call require_message(sent, expected, 'type 1 suffix message') + call require(itype == 3, 'type 1 suffix message type') + call require_tone_domain(tones, 'type 1 suffix message') + + call encode('CQ A000/KA1ABC FM07', 0, sent, tones, itype) + expected = padded_message('CQ A000/KA1ABC FM07') + call require_message(sent, expected, 'type 2 prefix message') + call require(itype == 4, 'type 2 prefix message type') + call require_tone_domain(tones, 'type 2 prefix message') + + call encode('CQ WB9XYZ/W4 FM07', 0, sent, tones, itype) + expected = padded_message('CQ WB9XYZ/W4 FM07') + call require_message(sent, expected, 'type 2 suffix message') + call require(itype == 5, 'type 2 suffix message type') + call require_tone_domain(tones, 'type 2 suffix message') + + call encode('HELLO WORLD', 0, sent, tones, itype) + expected = padded_message('HELLO WORLD') + call require_message(sent, expected, 'free text message') + call require(itype == 6, 'free text message type') + call require_tone_domain(tones, 'free text message') + end subroutine test_message_forms + + subroutine test_shorthand_messages() + character(len=1) :: sent(23) + integer :: tones(jt65_symbol_count), itype + character(len=22) :: expected + integer :: i, group + + call encode('RO', 0, sent, tones, itype) + expected = padded_message('RO') + call require_message(sent, expected, 'RO shorthand') + call require(itype == 7, 'RO shorthand type') + do i = 1, jt65_symbol_count + group = 1 + (i - 1) / 4 + call require(tones(i) == merge(0, 20, mod(group, 2) == 1), & + 'RO shorthand symbol group') + end do + + call encode('RRR', 0, sent, tones, itype) + expected = padded_message('RRR') + call require_message(sent, expected, 'RRR shorthand') + call require(itype == 7, 'RRR shorthand type') + call require(all(tones(1:4) == 0), 'RRR shorthand first group') + call require(all(tones(5:8) == 30), 'RRR shorthand second group') + + call encode('73', 0, sent, tones, itype) + expected = padded_message('73') + call require_message(sent, expected, '73 shorthand') + call require(itype == 7, '73 shorthand type') + call require(all(tones(1:4) == 0), '73 shorthand first group') + call require(all(tones(5:8) == 40), '73 shorthand second group') + + call encode(' k1abc w9xyz fn42 ', 0, sent, tones, itype) + expected = padded_message('K1ABC W9XYZ FN42') + call require_message(sent, expected, 'message normalization') + call require(itype == 1, 'normalized message type') + + call encode('K1ABC W9XYZ FN42 OO', 0, sent, tones, itype) + expected = padded_message('K1ABC W9XYZ FN42 OOO') + call require_message(sent, expected, 'legacy OO suffix') + call require(itype == 1, 'legacy OO suffix type') + end subroutine test_shorthand_messages + +end program test_jt65_source_encoding diff --git a/tests/unit/jt65/test_jt65_xcor_silence.f90 b/tests/unit/jt65/test_jt65_xcor_silence.f90 new file mode 100644 index 00000000..d43049b2 --- /dev/null +++ b/tests/unit/jt65/test_jt65_xcor_silence.f90 @@ -0,0 +1,34 @@ +program test_jt65_xcor_silence + + implicit none + + integer, parameter :: lag1 = -32, lag2 = 82, nhmax = 3413, nsmax = 552 + real :: ss(nsmax,nhmax), ccf(lag1:lag2), ccf0, flip + integer :: lagpk + + common /sync/ ss + + call setup65 + ss = 0.0 + lagpk = huge(0) + + call xcor(1,nsmax,126,lag1,lag2,ccf,ccf0,lagpk,flip,0.0,0) + + call require(lagpk == lag1, 'silence returns the first valid lag') + call require(all(ccf == 0.0), 'silence produces zero correlation') + call require(ccf0 == 0.0, 'silence produces a zero peak') + call require(flip == 1.0, 'silence keeps normal polarity') + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + +end program test_jt65_xcor_silence diff --git a/tests/unit/jt65/test_map65_jt65_candidate_consistency.f90 b/tests/unit/jt65/test_map65_jt65_candidate_consistency.f90 new file mode 100644 index 00000000..433ce775 --- /dev/null +++ b/tests/unit/jt65/test_map65_jt65_candidate_consistency.f90 @@ -0,0 +1,39 @@ +program test_map65_jt65_candidate_consistency + use extract_mod, only: jt65_candidate_is_consistent + implicit none + + call require(jt65_candidate_is_consistent(48,79,0.806,5.509), & + 'a weak faded decode with high hard distance remains eligible') + call require(jt65_candidate_is_consistent(26,28,0.0,24.628), & + 'a strong decode with high matched power remains eligible') + call require(jt65_candidate_is_consistent(45,81,0.844,4.463), & + 'the randomized holdout decode remains eligible') + + call require(.not.jt65_candidate_is_consistent(47,83,0.829,12.700), & + 'the reproduced wideband false decode is rejected') + call require(.not.jt65_candidate_is_consistent(42,72,0.0,16.740), & + 'a high-power distant codeword is rejected') + call require(.not.jt65_candidate_is_consistent(44,81,0.844,7.819), & + 'an elevated-power high-burden codeword is rejected') + call require(.not.jt65_candidate_is_consistent(44,80,0.893,4.772), & + 'an ambiguous high-burden codeword is rejected') + + call require(jt65_candidate_is_consistent(41,79,0.0,20.0), & + 'matched power alone does not reject a nearby codeword') + call require(jt65_candidate_is_consistent(49,80,0.869,7.499), & + 'sub-threshold evidence remains eligible') + + print '(a)', 'MAP65 JT65 candidate consistency tests passed.' + +contains + + subroutine require(condition,description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if(.not.condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_map65_jt65_candidate_consistency diff --git a/tests/unit/jt65/test_map65_jt65_handoff.f90 b/tests/unit/jt65/test_map65_jt65_handoff.f90 new file mode 100644 index 00000000..d263bccd --- /dev/null +++ b/tests/unit/jt65/test_map65_jt65_handoff.f90 @@ -0,0 +1,150 @@ +program test_map65_jt65_handoff + + use iso_fortran_env, only: real32, real64 + use, intrinsic :: ieee_arithmetic, only: ieee_get_flag, ieee_invalid, ieee_is_finite, & + ieee_quiet_nan, ieee_set_flag, ieee_value + use decode1a_mod + use filbig_mod + use afc65b_mod, only: afc65b + use jt65_test_fixture + use jt65_test_vectors + use npar_ptrs_mod, only: nsmax_active + implicit none + + real(real32), allocatable :: dd(:,:) + real(real64), parameter :: map65_base_frequency = 118.0_real64 * 11025.0_real64 / 1024.0_real64 + + allocate(dd(4, nsmax_active)) + call test_mono_filter_output(dd) + call test_afc_zero_signal() + call test_mode(dd, standard_tones, 1, 1, 'JT65A MAP65 handoff') + call test_mode(dd, standard_tones, 2, 1, 'JT65B MAP65 handoff') + call test_mode(dd, standard_tones, 4, 1, 'JT65C MAP65 handoff') + call test_mode(dd, ooo_tones, 1, -1, 'JT65A OOO MAP65 handoff') + call test_mode(dd, standard_tones, 2, 1, 'JT65B xpol MAP65 handoff', .true.) + print '(a)', 'MAP65 JT65 handoff tests passed' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + + subroutine test_mono_filter_output(waveform) + real(real32), intent(inout) :: waveform(:,:) + complex(real32), allocatable :: cx(:), cy(:) + integer :: newdat, n5 + logical :: invalid_raised + + allocate(cx(nsmax_active/64), cy(nsmax_active/64)) + call make_map65_wave(waveform, standard_tones, 2, map65_base_frequency) + waveform(3:4,:) = ieee_value(0.0_real32, ieee_quiet_nan) + newdat = 1 + call ieee_set_flag(ieee_invalid, .false.) + call filbig(waveform, nsmax_active, map65_base_frequency, newdat, 96000, .false., cx, cy, n5) + call ieee_get_flag(ieee_invalid, invalid_raised) + + call require(.not. invalid_raised, 'mono filter avoids invalid inactive-channel arithmetic') + call require(all(ieee_is_finite(real(cy(:n5)))) .and. & + all(ieee_is_finite(aimag(cy(:n5)))), 'mono filter output is finite') + call require(all(abs(cy(:n5)) == 0.0), 'mono filter output is zero') + end subroutine test_mono_filter_output + + subroutine test_afc_zero_signal() + integer, parameter :: npts = 1024 + complex :: cx(npts), cy(npts) + real :: a(5), ccfbest, dtbest + integer :: ipol, nflip, ndphi + logical :: invalid_raised + + cx = (0.0, 0.0) + cy = (0.0, 0.0) + a = 0.0 + ipol = 1 + nflip = 1 + ndphi = 0 + call ieee_set_flag(ieee_invalid, .false.) + call afc65b(cx, cy, npts, 1378.125/4.0, nflip, ipol, .false., ndphi, a, ccfbest, dtbest) + call ieee_get_flag(ieee_invalid, invalid_raised) + + call require(.not. invalid_raised, 'flat AFC objective avoids invalid arithmetic') + call require(all(ieee_is_finite(a(1:4))) .and. ieee_is_finite(ccfbest) .and. & + ieee_is_finite(dtbest), 'flat AFC objective produces finite outputs') + call require(all(a(1:3) == 0.0) .and. a(4) == 0.0, & + 'flat AFC objective preserves the accepted parameter point') + call require(ccfbest == 0.0 .and. dtbest == 0.0 .and. ipol == 1, & + 'flat AFC objective has explicit detection defaults') + end subroutine test_afc_zero_signal + + subroutine test_mode(waveform, tones, mode65, polarity, description, cross_polarized) + real(real32), intent(inout) :: waveform(:,:) + integer, intent(in) :: tones(:) + integer, intent(in) :: mode65 + integer, intent(in) :: polarity + character(len=*), intent(in) :: description + logical, intent(in), optional :: cross_polarized + integer :: newdat, nflip, nfsample, neme, ndepth, nqd, ndphi + integer :: nutc, nkhz, ndf, ipol, ntol, nkv, nhist, nsum, nsave + logical :: invalid_raised, xpol + character(len=12) :: mycall, hiscall + character(len=6) :: hisgrid + character(len=22) :: decoded + real :: dphi, sync2, a(5), dt, pol, qual + + call make_map65_wave(waveform, tones, mode65, map65_base_frequency) + xpol = .false. + if (present(cross_polarized)) xpol = cross_polarized + if (xpol) then + waveform(3:4,:) = waveform(1:2,:) + else + waveform(3:4,:) = ieee_value(0.0_real32, ieee_quiet_nan) + endif + newdat = 1 + nflip = polarity + nfsample = 96000 + mycall = 'K1ABC ' + hiscall = 'W9XYZ ' + hisgrid = 'FN42 ' + neme = 0 + ndepth = 3 + nqd = 1 + dphi = 0.0 + ndphi = 0 + nutc = 1 + nkhz = 1 + ndf = 0 + ipol = 0 + ntol = 100 + sync2 = 0.0 + a = 0.0 + dt = -1.7 + pol = 0.0 + nkv = -1 + nhist = -1 + nsum = 0 + nsave = 0 + qual = -999.0 + decoded = ' ' + call ieee_set_flag(ieee_invalid, .false.) + call decode1a(waveform, newdat, map65_base_frequency, nflip, mode65, nfsample, xpol, mycall, hiscall, & + hisgrid, neme, ndepth, nqd, dphi, ndphi, nutc, nkhz, ndf, ipol, ntol, sync2, & + a, dt, pol, nkv, nhist, nsum, nsave, qual, decoded) + call ieee_get_flag(ieee_invalid, invalid_raised) + + call require(decoded == padded_message('K1ABC W9XYZ FN42'), description//' message') + call require(.not. invalid_raised, description//' avoids invalid arithmetic') + call require(newdat == 0, description//' consumes new data') + call require(ieee_is_finite(sync2), description//' finite sync metric') + call require(ieee_is_finite(dt), description//' finite timing') + call require(ieee_is_finite(pol), description//' finite polarization') + call require(ieee_is_finite(qual), description//' finite quality') + call require(ieee_is_finite(a(1)) .and. ieee_is_finite(a(2)), description//' finite AFC') + end subroutine test_mode + +end program test_map65_jt65_handoff diff --git a/tests/unit/jt65/test_map65_jt65_message_validity.f90 b/tests/unit/jt65/test_map65_jt65_message_validity.f90 new file mode 100644 index 00000000..ec1f3dff --- /dev/null +++ b/tests/unit/jt65/test_map65_jt65_message_validity.f90 @@ -0,0 +1,77 @@ +program test_map65_jt65_message_validity + use packjt, only: is_valid_jt65_codeword, packmsg, packcall, packgrid + implicit none + + integer, parameter :: NBASE = 37*36*10*27*27*27 + integer :: dat(12), itype, nc1, ng + logical :: text + character(len=4) :: grid + character(len=6) :: call + character(len=22) :: message + + message = 'K1ABC W9XYZ FN42' + call packmsg(message, dat, itype) + call require(is_valid_jt65_codeword(dat), 'a standard structured message is valid') + + message = 'THIS IS FREE TEXT' + call packmsg(message, dat, itype) + call require(is_valid_jt65_codeword(dat), 'a free-text message is valid') + + call = '498IVA' + call packcall(call, nc1, text) + grid = 'EE84' + call packgrid(grid, ng, text) + call pack_fields(nc1, 265779995, ng, dat) + call require(.not. is_valid_jt65_codeword(dat), & + 'the reproduced false decode has an impossible second callsign') + + call pack_fields(NBASE + 1, NBASE - 1, 0, dat) + call require(is_valid_jt65_codeword(dat), 'a reserved first-field message is valid') + + call pack_fields(267796945, NBASE - 1, 0, dat) + call require(is_valid_jt65_codeword(dat), 'the final JT65v2 first-field value is valid') + + call pack_fields(NBASE, 0, 0, dat) + call require(.not. is_valid_jt65_codeword(dat), & + 'the unassigned first-field value is invalid') + + call pack_fields(267796946, 0, 0, dat) + call require(.not. is_valid_jt65_codeword(dat), & + 'a first field above the JT65v2 range is invalid') + + call pack_fields(0, NBASE, 0, dat) + call require(.not. is_valid_jt65_codeword(dat), & + 'a non-callsign second field is invalid') + + print '(a)', 'MAP65 JT65 message validity tests passed.' + +contains + + subroutine pack_fields(first_call, second_call, packed_grid, symbols) + integer, intent(in) :: first_call, second_call, packed_grid + integer, intent(out) :: symbols(12) + + symbols(1) = iand(ishft(first_call,-22),63) + symbols(2) = iand(ishft(first_call,-16),63) + symbols(3) = iand(ishft(first_call,-10),63) + symbols(4) = iand(ishft(first_call,-4),63) + symbols(5) = 4*iand(first_call,15) + iand(ishft(second_call,-26),3) + symbols(6) = iand(ishft(second_call,-20),63) + symbols(7) = iand(ishft(second_call,-14),63) + symbols(8) = iand(ishft(second_call,-8),63) + symbols(9) = iand(ishft(second_call,-2),63) + symbols(10) = 16*iand(second_call,3) + iand(ishft(packed_grid,-12),15) + symbols(11) = iand(ishft(packed_grid,-6),63) + symbols(12) = iand(packed_grid,63) + end subroutine pack_fields + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require +end program test_map65_jt65_message_validity diff --git a/tests/unit/jt65/test_map65_s3avg_contracts.f90 b/tests/unit/jt65/test_map65_s3avg_contracts.f90 new file mode 100644 index 00000000..9a8b1bce --- /dev/null +++ b/tests/unit/jt65/test_map65_s3avg_contracts.f90 @@ -0,0 +1,137 @@ +program test_map65_s3avg_contracts + use encode65_mod, only: encode65 + use s3avg_mod, only: s3avg + implicit none + + call test_group_isolation_and_tolerance + call test_timing_and_duplicates + print '(a)', 'MAP65 s3avg contract tests passed.' + +contains + + subroutine test_group_isolation_and_tolerance + real :: s3(64,63) + character(len=22) :: target, decoded + integer :: code(63), nsave, nsum, nkv + + target='K1ABC W9XYZ FN42' + call make_spectrum(target,code,s3) + nsave=0 + + call next_slot(nsave) + nsum=-77 + call s3avg(nsave,1,1000,1000,0.0,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. len_trim(decoded) == 0, & + 'first frequency observation is isolated') + + call next_slot(nsave) + call s3avg(nsave,1,1002,1000,0.0,2,1,100,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'same-parity frequency observations decode as a pair') + + call next_slot(nsave) + call s3avg(nsave,1,1003,3000,0.0,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. len_trim(decoded) == 0, & + 'frequency-separated observations do not join the group') + + call next_slot(nsave) + call s3avg(nsave,1,1101,5000,0.0,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0, 'dynamic tolerance starts a new group') + + call next_slot(nsave) + call s3avg(nsave,1,1103,5050,0.0,1,1,50,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'dynamic tolerance includes its inclusive boundary') + + call next_slot(nsave) + call s3avg(nsave,1,1105,5000,0.0,1,1,10,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'dynamic tolerance excludes the saved 5050-Hz frame') + + call next_slot(nsave) + call s3avg(nsave,1,1107,5011,0.0,1,1,10,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. len_trim(decoded) == 0, & + 'dynamic tolerance rejects frequencies outside its boundary') + end subroutine test_group_isolation_and_tolerance + + subroutine test_timing_and_duplicates + real :: s3(64,63) + character(len=22) :: target, decoded + integer :: code(63), nsave, nsum, nkv, duplicate_slot + + target='K1ABC W9XYZ FN42' + call make_spectrum(target,code,s3) + nsave=7 + + call next_slot(nsave) + call s3avg(nsave,1,1200,7000,0.00,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0, 'timing fixture starts alone') + + call next_slot(nsave) + call s3avg(nsave,1,1202,7000,0.19,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'nearby timing observations join the group') + + call next_slot(nsave) + call s3avg(nsave,1,1204,7000,0.50,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. len_trim(decoded) == 0, & + 'distant timing observations remain isolated') + + call next_slot(nsave) + call s3avg(nsave,1,1300,9000,0.00,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0, 'duplicate fixture starts alone') + duplicate_slot=nsave + + call next_slot(nsave) + call s3avg(nsave,1,1300,9000,0.01,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. nsave == duplicate_slot, & + 'same-UTC duplicate is suppressed and ring position rolls back') + + call next_slot(nsave) + call s3avg(nsave,1,1302,9000,0.02,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'next same-parity observation forms exactly a pair after duplicate') + + call next_slot(nsave) + call s3avg(nsave,1,1400,11000,0.00,1,1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0, 'sync-polarity fixture starts alone') + + call next_slot(nsave) + call s3avg(nsave,1,1402,11000,0.00,1,-1,100,s3,nsum,nkv,decoded) + call require(nsum == 1 .and. nkv == 0 .and. len_trim(decoded) == 0, & + 'opposite sync polarities do not join the group') + + call next_slot(nsave) + call s3avg(nsave,1,1404,11000,0.00,1,-1,100,s3,nsum,nkv,decoded) + call require(nsum == 2 .and. nkv == 2 .and. decoded(1:len_trim(target)) == target, & + 'matching negative sync polarities decode as a pair') + end subroutine test_timing_and_duplicates + + subroutine make_spectrum(message,code,s3) + character(len=*), intent(in) :: message + integer, intent(out) :: code(63) + real, intent(out) :: s3(64,63) + integer :: j + + call encode65(message,code) + s3=1.0 + do j=1,63 + s3(code(j)+1,j)=100.0 + enddo + end subroutine make_spectrum + + subroutine next_slot(nsave) + integer, intent(inout) :: nsave + nsave=mod(nsave,64)+1 + end subroutine next_slot + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine require + +end program test_map65_s3avg_contracts diff --git a/tests/unit/jt9/CMakeLists.txt b/tests/unit/jt9/CMakeLists.txt new file mode 100644 index 00000000..724bff19 --- /dev/null +++ b/tests/unit/jt9/CMakeLists.txt @@ -0,0 +1,11 @@ +add_executable (test_jt9_input_validation test_jt9_input_validation.f90) +wsjt_link_common_fortran (test_jt9_input_validation) +add_test (NAME test_jt9_input_validation COMMAND test_jt9_input_validation) + +add_executable (test_readwav_validation test_readwav_validation.f90) +wsjt_link_common_fortran (test_readwav_validation) +add_test (NAME test_readwav_validation COMMAND test_readwav_validation) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_readwav_validation PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") +endif () diff --git a/tests/unit/jt9/test_jt9_cli_validation.cmake b/tests/unit/jt9/test_jt9_cli_validation.cmake new file mode 100644 index 00000000..16f2499e --- /dev/null +++ b/tests/unit/jt9/test_jt9_cli_validation.cmake @@ -0,0 +1,17 @@ +function (require_rejection option value) + execute_process ( + COMMAND "${JT9}" "${option}" "${value}" + RESULT_VARIABLE result + ERROR_VARIABLE stderr) + if (result EQUAL 0) + message (FATAL_ERROR "${option}=${value} unexpectedly succeeded") + endif () + if (NOT stderr MATCHES "jt9: invalid value") + message (FATAL_ERROR "${option}=${value} did not report a validation error: ${stderr}") + endif () +endfunction () + +require_rejection (-Q 6) +require_rejection (-Q invalid) +require_rejection (-p invalid) +require_rejection (-m invalid) diff --git a/tests/unit/jt9/test_jt9_input_validation.f90 b/tests/unit/jt9/test_jt9_input_validation.f90 new file mode 100644 index 00000000..c9c88370 --- /dev/null +++ b/tests/unit/jt9/test_jt9_input_validation.f90 @@ -0,0 +1,63 @@ +program test_jt9_input_validation + use jt9_input_validation, only: parse_integer, parse_real, parse_wav_filename_nutc + implicit none + + integer :: integer_value, nutc + real(kind=8) :: real_value + logical :: ok + + call parse_integer('42', integer_value, ok) + call assert_true(ok .and. integer_value == 42, 'integer parsing accepts integers') + + call parse_integer('-42', integer_value, ok) + call assert_true(ok .and. integer_value == -42, 'integer parsing accepts signs') + + call parse_integer('not-a-number', integer_value, ok) + call assert_true(.not. ok, 'integer parsing rejects text') + + call parse_integer('42x', integer_value, ok) + call assert_true(.not. ok, 'integer parsing requires one complete token') + + call parse_real('7.5', real_value, ok) + call assert_true(ok .and. real_value == 7.5d0, 'real parsing accepts finite values') + + call parse_real('60', real_value, ok) + call assert_true(ok .and. real_value == 60.d0, 'real parsing accepts whole numbers') + + call parse_real('7.5e1', real_value, ok) + call assert_true(ok .and. real_value == 75.d0, 'real parsing accepts decimal exponents') + + call parse_real('NaN', real_value, ok) + call assert_true(.not. ok, 'real parsing rejects NaN') + + call parse_real('7.5x', real_value, ok) + call assert_true(.not. ok, 'real parsing requires one complete token') + + call parse_wav_filename_nutc('240101_1234.wav', nutc) + call assert_true(nutc == 1234, 'four-digit timestamp is read') + + call parse_wav_filename_nutc('240101_123456.WAV', nutc) + call assert_true(nutc == 123456, 'six-digit timestamp is read') + + call parse_wav_filename_nutc('recording2026.wav', nutc) + call assert_true(nutc == 0, 'four-digit suffix without separator defaults to midnight') + + call parse_wav_filename_nutc('valid-audio', nutc) + call assert_true(nutc == 0, 'extensionless files default to midnight') + + call parse_wav_filename_nutc('a.wav', nutc) + call assert_true(nutc == 0, 'short names default to midnight') + +contains + + subroutine assert_true(condition, message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if (.not. condition) then + write(*, '(A)') message + error stop 1 + end if + end subroutine assert_true + +end program test_jt9_input_validation diff --git a/tests/unit/jt9/test_readwav_validation.f90 b/tests/unit/jt9/test_readwav_validation.f90 new file mode 100644 index 00000000..fd3d4603 --- /dev/null +++ b/tests/unit/jt9/test_readwav_validation.f90 @@ -0,0 +1,162 @@ +program test_readwav_validation + use readwav, only: wav_header + implicit none + + type(wav_header) :: wav + integer :: samples_read, status, unit + integer*2 :: samples(4) + character(len=128) :: message + + call write_valid_wav('test_readwav_validation.wav') + call wav%read('test_readwav_validation.wav', status, message) + call assert_true(status == 0, 'valid WAV is accepted') + call assert_true(wav%audio_format%sample_rate == 12000, 'format chunk is read') + close(wav%lun) + + call write_format_wav('test_readwav_11025.wav', 1, 1, 11025, 16) + call wav%read('test_readwav_11025.wav', status, message) + call assert_true(status == 0, 'supported JT4 sample rate is accepted') + close(wav%lun) + + call write_format_wav('test_readwav_stereo.wav', 1, 2, 12000, 16) + call wav%read('test_readwav_stereo.wav', status, message) + call assert_true(status /= 0, 'unsupported sample representation is rejected') + + call write_format_wav('test_readwav_48000.wav', 1, 1, 48000, 16) + call wav%read('test_readwav_48000.wav', status, message) + call assert_true(status /= 0, 'unsupported sample rate is rejected') + + call write_short_file('test_readwav_short.wav') + call wav%read('test_readwav_short.wav', status, message) + call assert_true(status /= 0, 'short WAV is rejected') + + call write_non_wave_file('test_readwav_not_wave.wav') + call wav%read('test_readwav_not_wave.wav', status, message) + call assert_true(status /= 0, 'non-WAVE RIFF file is rejected') + + call write_unpadded_odd_data('test_readwav_odd_data.wav') + call wav%read('test_readwav_odd_data.wav', status, message) + call assert_true(status == 0 .and. wav%data_size == 1, 'unpadded final data chunk is accepted') + close(wav%lun) + + call write_wav_with_trailing_chunk('test_readwav_trailing_chunk.wav') + call wav%read('test_readwav_trailing_chunk.wav', status, message) + call assert_true(status == 0, 'WAV with trailing metadata is accepted') + call wav%read_samples(samples, samples_read, status, message) + call assert_true(status == 0 .and. samples_read == 1, 'only data chunk samples are read') + call assert_true(samples(1) == 1234 .and. all(samples(2:) == 0), & + 'sample reads zero-fill without consuming metadata') + call wav%read_samples(samples, samples_read, status, message) + call assert_true(status == 0 .and. samples_read == 0, 'data chunk exhaustion is reported') + close(wav%lun) + + call write_truncated_chunk('test_readwav_truncated.wav') + call wav%read('test_readwav_truncated.wav', status, message) + call assert_true(status /= 0, 'truncated chunk is rejected') + +contains + + subroutine write_valid_wav(filename) + character(len=*), intent(in) :: filename + integer*2 :: audio_format, channels, block_align, bits_per_sample + integer :: sample_rate, byte_rate + + audio_format = 1 + channels = 1 + sample_rate = 12000 + byte_rate = 24000 + block_align = 2 + bits_per_sample = 16 + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 36, 'WAVE', 'fmt ', 16, audio_format, channels, sample_rate, & + byte_rate, block_align, bits_per_sample, 'data', 0 + close(unit) + end subroutine write_valid_wav + + subroutine write_short_file(filename) + character(len=*), intent(in) :: filename + + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF' + close(unit) + end subroutine write_short_file + + subroutine write_format_wav(filename, audio_format, channels, sample_rate, bits_per_sample) + character(len=*), intent(in) :: filename + integer, intent(in) :: audio_format, channels, sample_rate, bits_per_sample + integer*2 :: format_value, channel_value, block_align, bits_value + integer :: byte_rate + + format_value = audio_format + channel_value = channels + bits_value = bits_per_sample + block_align = channels * bits_per_sample / 8 + byte_rate = sample_rate * block_align + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 36, 'WAVE', 'fmt ', 16, format_value, channel_value, sample_rate, & + byte_rate, block_align, bits_value, 'data', 0 + close(unit) + end subroutine write_format_wav + + subroutine write_non_wave_file(filename) + character(len=*), intent(in) :: filename + + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 36, 'NOPE' + close(unit) + end subroutine write_non_wave_file + + subroutine write_unpadded_odd_data(filename) + character(len=*), intent(in) :: filename + integer*2 :: audio_format, channels, block_align, bits_per_sample + integer :: sample_rate, byte_rate + + audio_format = 1 + channels = 1 + sample_rate = 12000 + byte_rate = 24000 + block_align = 2 + bits_per_sample = 16 + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 37, 'WAVE', 'fmt ', 16, audio_format, channels, sample_rate, & + byte_rate, block_align, bits_per_sample, 'data', 1, 'x' + close(unit) + end subroutine write_unpadded_odd_data + + subroutine write_truncated_chunk(filename) + character(len=*), intent(in) :: filename + + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 36, 'WAVE', 'fmt ', 32 + close(unit) + end subroutine write_truncated_chunk + + subroutine write_wav_with_trailing_chunk(filename) + character(len=*), intent(in) :: filename + integer*2 :: audio_format, channels, block_align, bits_per_sample, sample + integer :: sample_rate, byte_rate + + audio_format = 1 + channels = 1 + sample_rate = 12000 + byte_rate = 24000 + block_align = 2 + bits_per_sample = 16 + sample = 1234 + open(newunit=unit, file=filename, access='stream', form='unformatted', status='replace') + write(unit) 'RIFF', 50, 'WAVE', 'fmt ', 16, audio_format, channels, sample_rate, & + byte_rate, block_align, bits_per_sample, 'data', 2, sample, 'JUNK', 4, 'abcd' + close(unit) + end subroutine write_wav_with_trailing_chunk + + subroutine assert_true(condition, text) + logical, intent(in) :: condition + character(len=*), intent(in) :: text + + if (.not. condition) then + write(*, '(A)') text + error stop 1 + end if + end subroutine assert_true + +end program test_readwav_validation diff --git a/tests/unit/jtty/CMakeLists.txt b/tests/unit/jtty/CMakeLists.txt new file mode 100644 index 00000000..8dd698d0 --- /dev/null +++ b/tests/unit/jtty/CMakeLists.txt @@ -0,0 +1,198 @@ +add_executable (test_jtty_pack test_jtty_pack.f90) +target_include_directories (test_jtty_pack PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_pack) + +add_executable (test_jtty_source_codec test_jtty_source_codec.f90) +target_include_directories (test_jtty_source_codec PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_source_codec) +add_test (NAME test_jtty_source_codec COMMAND test_jtty_source_codec) +set_tests_properties (test_jtty_source_codec PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_source_codec: all checks passed" +) + +add_executable (test_tbcc test_tbcc.f90) +target_include_directories (test_tbcc PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_tbcc) +add_test (NAME test_tbcc COMMAND test_tbcc) +set_tests_properties (test_tbcc PROPERTIES + PASS_REGULAR_EXPRESSION "test_tbcc: all checks passed" +) + +add_executable (test_jtty_block_pow test_jtty_block_pow.f90) +target_include_directories (test_jtty_block_pow PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_block_pow) +add_test (NAME test_jtty_block_pow COMMAND test_jtty_block_pow) +set_tests_properties (test_jtty_block_pow PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_block_pow: all checks passed" +) + +add_executable (test_jtty_message_matching test_jtty_message_matching.f90) +target_include_directories (test_jtty_message_matching PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_message_matching) +add_test (NAME test_jtty_message_matching COMMAND test_jtty_message_matching) +set_tests_properties (test_jtty_message_matching PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_message_matching: all checks passed" +) + +add_executable (test_jtty_receive_state test_jtty_receive_state.f90) +target_include_directories (test_jtty_receive_state PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_receive_state) +add_test (NAME test_jtty_receive_state COMMAND test_jtty_receive_state) +set_tests_properties (test_jtty_receive_state PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_receive_state: all checks passed" +) + +add_executable (test_jtty_adjacent_decode test_jtty_adjacent_decode.f90) +target_include_directories (test_jtty_adjacent_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_adjacent_decode) +add_test (NAME test_jtty_adjacent_decode COMMAND test_jtty_adjacent_decode) +# These decoder tests are compute-heavy under ARM emulation. Their timeouts +# include headroom for hosted-runner variability. +set_tests_properties (test_jtty_adjacent_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_adjacent_decode: all checks passed" + TIMEOUT 180 +) + +add_executable (test_jtty_structured_decode + test_jtty_structured_decode.f90 + jtty_cpp_n1mm_smoke.cpp) +target_include_directories (test_jtty_structured_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_structured_decode) +target_link_libraries (test_jtty_structured_decode PRIVATE Qt5::Core) +add_test (NAME test_jtty_structured_decode COMMAND test_jtty_structured_decode) +set_tests_properties (test_jtty_structured_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_structured_decode: all checks passed" + TIMEOUT 240 +) + +add_executable (test_jtty_overlap_decode test_jtty_overlap_decode.f90) +target_include_directories (test_jtty_overlap_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_overlap_decode) +add_test (NAME test_jtty_overlap_decode COMMAND test_jtty_overlap_decode) +set_tests_properties (test_jtty_overlap_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_overlap_decode: all checks passed" + TIMEOUT 180 +) + +add_test (NAME test_jtty_overlap_decode_480 COMMAND test_jtty_overlap_decode 480) +set_tests_properties (test_jtty_overlap_decode_480 PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_overlap_decode: all checks passed" + TIMEOUT 240 +) + +add_executable (test_jtty_sticky_retry test_jtty_sticky_retry.f90) +target_include_directories (test_jtty_sticky_retry PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_sticky_retry) +add_test (NAME test_jtty_sticky_retry COMMAND test_jtty_sticky_retry) +set_tests_properties (test_jtty_sticky_retry PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_sticky_retry: all checks passed" + TIMEOUT 60 +) + +add_executable (test_jtty_windowed_decode test_jtty_windowed_decode.f90) +target_include_directories (test_jtty_windowed_decode PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_windowed_decode) +add_test (NAME test_jtty_windowed_decode COMMAND test_jtty_windowed_decode) +set_tests_properties (test_jtty_windowed_decode PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_windowed_decode: all checks passed" + TIMEOUT 180 +) + +add_executable (test_jtty_gap_merge test_jtty_gap_merge.f90) +target_include_directories (test_jtty_gap_merge PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_gap_merge) +add_test (NAME test_jtty_gap_merge COMMAND test_jtty_gap_merge) +set_tests_properties (test_jtty_gap_merge PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_gap_merge: all checks passed" + TIMEOUT 180 +) + +configure_file(${CMAKE_SOURCE_DIR}/tests/fixtures/jtty/jtty_msgs.txt "${CMAKE_CURRENT_BINARY_DIR}/jtty_msgs.txt" COPYONLY) + +add_test (NAME test_jtty_pack COMMAND test_jtty_pack) +set_tests_properties (test_jtty_pack PROPERTIES + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + PASS_REGULAR_EXPRESSION "^ 3 3 67 14 NOW IS THE TIME FOR ALL GOOD MEN TO COME TO THE AID OF THEIR PARTY\.;^ 3 3 52 11 THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG, TWICE\.;\nTotal messages: 36 Number of errors: 0\n$" +) + +add_executable (test_jtty_frequency_window test_jtty_frequency_window.f90) +wsjt_link_common_fortran (test_jtty_frequency_window) +add_test (NAME test_jtty_frequency_window COMMAND test_jtty_frequency_window) + +add_executable (test_jtty_surface_ranges test_jtty_surface_ranges.f90) +wsjt_link_common_fortran (test_jtty_surface_ranges) +add_test (NAME test_jtty_surface_ranges COMMAND test_jtty_surface_ranges) +set_tests_properties (test_jtty_surface_ranges PROPERTIES TIMEOUT 180) + +add_executable (test_jtty_get_updates test_jtty_get_updates.f90) +target_include_directories (test_jtty_get_updates PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_jtty_get_updates) +add_test (NAME test_jtty_get_updates COMMAND test_jtty_get_updates) +set_tests_properties (test_jtty_get_updates PROPERTIES + PASS_REGULAR_EXPRESSION "test_jtty_get_updates: all checks passed" +) + +add_executable (test_jtty_txstream + test_jtty_txstream.cpp + ${CMAKE_SOURCE_DIR}/Logger.cpp + ${CMAKE_SOURCE_DIR}/Modulator/JttyPcmFifo.cpp + ${CMAKE_SOURCE_DIR}/Audio/TxAudioQueue.cpp + ${CMAKE_SOURCE_DIR}/Modulator/JttyTxStream.cpp + ${CMAKE_SOURCE_DIR}/Audio/soundout.cpp) +target_link_libraries (test_jtty_txstream wsjt_qt Boost::log_setup Qt5::Test Qt5::Multimedia) +add_test (NAME test_jtty_txstream COMMAND test_jtty_txstream) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_jtty_txstream PROPERTIES + ENVIRONMENT + "QT_QPA_PLATFORM=offscreen;TSAN_OPTIONS=${wsjt_tsan_gui_options}") +endif () + +add_executable (test_jtty_messages test_jtty_messages.cpp) +target_link_libraries (test_jtty_messages Qt5::Test) +add_test (NAME test_jtty_messages COMMAND test_jtty_messages) + +add_executable (test_jtty_draft_acceptance test_jtty_draft_acceptance.cpp) +target_link_libraries (test_jtty_draft_acceptance Qt5::Test) +add_test (NAME test_jtty_draft_acceptance COMMAND test_jtty_draft_acceptance) + +add_executable (test_jtty_n1mm test_jtty_n1mm.cpp) +target_link_libraries (test_jtty_n1mm Qt5::Test) +add_test (NAME test_jtty_n1mm COMMAND test_jtty_n1mm) + +add_executable (test_mmttyif + test_mmttyif.cpp + ${CMAKE_SOURCE_DIR}/widgets/MMTTYIF.cpp +) +target_link_libraries (test_mmttyif Qt5::Test Qt5::Network) +add_test (NAME test_mmttyif COMMAND test_mmttyif) +# Connection setup may retry for several seconds on slow Windows runners. +set_tests_properties (test_mmttyif PROPERTIES TIMEOUT 30) + +add_executable (test_jtty_tbcc_list_decoder test_jtty_tbcc_list_decoder.f90) +wsjt_link_common_fortran (test_jtty_tbcc_list_decoder) +add_test (NAME test_jtty_tbcc_list_decoder COMMAND test_jtty_tbcc_list_decoder) + +add_executable (test_jtty_tbcc_decoder test_jtty_tbcc_decoder.f90) +wsjt_link_common_fortran (test_jtty_tbcc_decoder) +add_test (NAME test_jtty_tbcc_decoder COMMAND test_jtty_tbcc_decoder) + +add_executable (test_jtty_tbcc_code_profile test_jtty_tbcc_code_profile.f90) +wsjt_link_common_fortran (test_jtty_tbcc_code_profile) +add_test (NAME test_jtty_tbcc_code_profile COMMAND test_jtty_tbcc_code_profile) + +add_executable (test_jtty_payload_correlators test_jtty_payload_correlators.f90) +wsjt_link_common_fortran (test_jtty_payload_correlators) +add_test (NAME test_jtty_payload_correlators COMMAND test_jtty_payload_correlators) + +add_executable (test_jtty_replay_ownership + test_jtty_replay_ownership.cpp + ${CMAKE_SOURCE_DIR}/DecDataMutex.cpp) +target_link_libraries (test_jtty_replay_ownership + Qt5::Core Qt5::Test) +add_test (NAME test_jtty_replay_ownership COMMAND test_jtty_replay_ownership) +set_tests_properties (test_jtty_replay_ownership PROPERTIES + TIMEOUT 30 LABELS "receive-handoff;jtty-replay") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_jtty_replay_ownership PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp new file mode 100644 index 00000000..1d666113 --- /dev/null +++ b/tests/unit/jtty/jtty_cpp_n1mm_smoke.cpp @@ -0,0 +1,78 @@ +#include "widgets/JttyN1mm.hpp" +#include "wsjtx_config.h" + +#include <algorithm> +#include <array> + +extern "C" void genjtty_atoms_c (Jtty::NativeAtomDescriptor const atoms[], int natoms, + int tones[], int* nsym, int* status); +extern "C" void genjtty_profile_ (char*, int const*, int*, int*, fortran_charlen_t); + +extern "C" int jtty_cpp_n1mm_smoke (int tones[], int* nsym) +{ + auto const compiled = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ 32D EMA"), + Jtty::NativeExchangeProfile::FieldDay); + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + if (compiled.isNative ()) { + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), + tones, nsym, &status); + } + return status; +} + +extern "C" int jtty_cpp_cq_smoke (int tones[], int* nsym, char text[], int chained) +{ + Jtty::NativeMacroContext const context {QStringLiteral ("K1ABC"), {}, 0}; + auto const compiled = Jtty::compileNativeMacro ( + 1, Jtty::nativeMacroTemplate (1), context); + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + if (compiled.isNative ()) { + auto const frame = Jtty::transmitFrame (compiled.text, chained != 0).toLatin1 (); + std::copy (frame.cbegin (), frame.cend (), text); + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), + tones, nsym, &status); + } + return status; +} + +extern "C" int jtty_cpp_rtty_smoke (int tones[], int* nsym) +{ + Jtty::NativeMacroContext context { + QStringLiteral ("K1ABC"), {}, 1, Jtty::NativeExchangeProfile::RttyRoundup, + QStringLiteral ("DX")}; + *nsym = 0; + int status = static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + std::array<int, 16 * 59> packedTones {}; + struct Example {int serial; QString raw; QString canonical;}; + std::array<Example, 3> const examples {{ + {1, QStringLiteral ("599 001"), QStringLiteral ("599 001")}, + {5, QStringLiteral ("599 05"), QStringLiteral ("599 005")}, + {123, QStringLiteral ("599 0123"), QStringLiteral ("599 123")}}}; + for (auto const& example : examples) { + context.serialNumber = example.serial; + auto const compiled = Jtty::compileNativeMacro (8, Jtty::nativeMacroTemplate (8), context); + if (!compiled.isNative () || compiled.text != example.canonical) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + genjtty_atoms_c (compiled.atoms.constData (), compiled.atoms.size (), tones, nsym, &status); + if (status != static_cast<int> (Jtty::NativeEncodeStatus::Ok) || *nsym <= 0) return status; + auto text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + int packedSymbols {}; + auto profile = static_cast<int> (context.exchangeProfile); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + if (packedSymbols != *nsym || !std::equal (tones, tones + *nsym, packedTones.cbegin ()) || + text != Jtty::transmitFrame (example.canonical, false).toLatin1 ()) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + text = Jtty::transmitFrame (example.raw, false).toLatin1 (); + profile = static_cast<int> (Jtty::NativeExchangeProfile::None); + genjtty_profile_ (text.data (), &profile, packedTones.data (), &packedSymbols, text.size ()); + if (packedSymbols != 2 * *nsym || text != Jtty::transmitFrame (example.raw, false).toLatin1 ()) { + return static_cast<int> (Jtty::NativeEncodeStatus::InvalidDescriptor); + } + } + return status; +} diff --git a/tests/unit/jtty/test_jtty_adjacent_decode.f90 b/tests/unit/jtty/test_jtty_adjacent_decode.f90 new file mode 100644 index 00000000..dc3e6cdd --- /dev/null +++ b/tests/unit/jtty/test_jtty_adjacent_decode.f90 @@ -0,0 +1,105 @@ +program test_jtty_adjacent_decode + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + integer :: failures + + failures=0 + call run_case('CQ KA1ABC CQ','WB9XYZ TU',1,1,failures) + call run_case('WB9XYZ 599 0123','WB9XYZ TU CQ KA1ABC CQ',3,2,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_adjacent_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_adjacent_decode: all checks passed' + +contains + + subroutine run_case(first_message,second_message,first_frames,second_frames, & + count) + character(len=*), intent(in) :: first_message,second_message + integer, intent(in) :: first_frames,second_frames + integer, intent(inout) :: count + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols,first_samples,second_samples + integer :: total_samples + integer(int16), allocatable :: pcm(:) + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + call discard_pending_updates() + first_input=first_message + second_input=second_message + call genjtty(first_input,first_tones,first_symbols) + call genjtty(second_input,second_tones,second_symbols) + call expect(first_symbols.eq.first_frames*frame_symbols, & + 'the first message has the expected frame count',count) + call expect(second_symbols.eq.second_frames*frame_symbols, & + 'the second message has the expected frame count',count) + + first_samples=first_symbols*nsps + second_samples=second_symbols*nsps + total_samples=first_samples+second_samples+frame_symbols*nsps + allocate(first_wave(first_samples),second_wave(second_samples)) + allocate(complex_wave(max(first_samples,second_samples))) + allocate(pcm(total_samples)) + + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,first_wave,0,first_samples) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,second_wave,0,second_samples) + pcm=0_int16 + pcm(1:first_samples)=int(nint(30000.0*first_wave),int16) + pcm(first_samples+1:first_samples+second_samples)= & + int(nint(30000.0*second_wave),int16) + + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + + call expect(npending.eq.2,'the decoder keeps two adjacent messages',count) + if(npending.eq.2) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.trim(first_message), & + 'the first decoded text is retained in order',count) + call expect(trim(normalized(pending_updates(2)%decoded)).eq.trim(second_message), & + 'the second decoded text is retained in order',count) + call expect(pending_updates(1)%complete, & + 'the first message reaches end of message',count) + call expect(pending_updates(2)%complete, & + 'the second message reaches end of message',count) + endif + + deallocate(pcm,first_wave,second_wave,complex_wave) + end subroutine run_case + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_adjacent_decode diff --git a/tests/unit/jtty/test_jtty_block_pow.f90 b/tests/unit/jtty/test_jtty_block_pow.f90 new file mode 100644 index 00000000..e4366970 --- /dev/null +++ b/tests/unit/jtty/test_jtty_block_pow.f90 @@ -0,0 +1,144 @@ +program test_jtty_block_pow + + ! Focused tests for coherent block detection (lib/jtty/jtty_block_pow.f90), + ! used as a fallback by jtty_mdecode.f90's decode_and_merge when ordinary + ! blocksize-1 (single-symbol) detection fails to decode a candidate. + + use, intrinsic :: iso_fortran_env, only: real32, int32 + use jtty_fec ! re-exports tbcc's public API: TOTAL_K, PAYLOAD_BITS, + ! tbcc_init, tbcc_encode, tbcc_wava_fsk_decode + implicit none + + call expect_block_roundtrip_and_phase_invariance() + call expect_block_detection_rescues_a_misleading_symbol() + call expect_clean_signal_unaffected_by_block_detection() + + print *, 'test_jtty_block_pow: all checks passed' + +contains + + subroutine expect_block_roundtrip_and_phase_invariance() + ! Noiseless round trip through jtty_block_pow at iblock=2 and iblock=4, + ! then through tbcc_wava_fsk_decode, at an arbitrary global carrier + ! phase -- block detection must not need to know absolute phase, only + ! stay coherent within each short block, so the result must not depend + ! on this offset. + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + complex(real32) :: z(0:3, TOTAL_K), phase + real(real32) :: pow_block(0:3, TOTAL_K) + logical :: success + integer :: i, t, iblk + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) + end do + payload(JTTY_RESERVED_BIT) = 0 ! reserved_zero_bit requires this below + call tbcc_encode(payload, tone_symbols) + + phase = cmplx(cos(0.7_real32), sin(0.7_real32), real32) ! arbitrary global carrier phase + z = cmplx(0.0_real32, 0.0_real32, real32) + do t = 1, TOTAL_K + z(tone_symbols(t), t) = phase + end do + + do iblk = 2, 4, 2 + call jtty_block_pow(z, TOTAL_K, iblk, pow_block) + call tbcc_wava_fsk_decode(pow_block, 4, 2, & + decoded, success, reserved_zero_bit=JTTY_RESERVED_BIT) + if (.not. success) then + print *, 'test_jtty_block_pow: noiseless block decode failed, iblock=', iblk + error stop 1 + end if + if (any(decoded /= payload)) then + print *, 'test_jtty_block_pow: noiseless block decode mismatch, iblock=', iblk + error stop 1 + end if + end do + end subroutine expect_block_roundtrip_and_phase_invariance + + subroutine expect_block_detection_rescues_a_misleading_symbol() + ! A minimal, hand-verified 2-symbol block where blocksize-1 detection + ! picks the WRONG tone at position 1 (tone 1's raw |z|^2 = 1.1025 + ! exceeds tone 0's |z|^2 = 1.0 there), but tone 1's value is phase- + ! rotated 120 degrees away from the block's coherent reference (the + ! phase shared by position 1's correct tone and position 2's tone). + ! Coherently summing across the block must favor the true sequence + ! (tone 0 @ position 1, tone 2 @ position 2) despite tone 1's larger + ! single-symbol magnitude, because it doesn't add constructively: + ! |z(0,1)+z(2,2)|^2 = |1.0+1.0|^2 = 4.0 + ! |z(1,1)+z(2,2)|^2 = |1.05*exp(i*2pi/3)+1.0|^2 ~= 1.05 + ! This is the actual mechanism block detection is meant to exploit -- + ! not merely averaging out noise, but that a misleading single-symbol + ! reading doesn't survive being coherently combined with its neighbor. + complex(real32) :: z(0:3, 2) + real(real32) :: pow_block(0:3, 2) + real(real32) :: twopi, pow1_correct, pow1_wrong + + twopi = 8.0_real32*atan(1.0_real32) + + z = cmplx(0.0_real32, 0.0_real32, real32) + z(0,1) = cmplx(1.0_real32, 0.0_real32, real32) ! correct tone, position 1 + z(1,1) = 1.05_real32 * cmplx(cos(twopi/3.0_real32), & + sin(twopi/3.0_real32), real32) ! misleading tone, position 1 + z(2,2) = cmplx(1.0_real32, 0.0_real32, real32) ! correct tone, position 2 + + pow1_correct = real(z(0,1)*conjg(z(0,1))) + pow1_wrong = real(z(1,1)*conjg(z(1,1))) + if (.not. (pow1_wrong > pow1_correct)) then + print *, 'test_jtty_block_pow: test setup error -- expected tone 1 to look', & + ' stronger than tone 0 at blocksize 1' + error stop 1 + end if + + call jtty_block_pow(z, 2, 2, pow_block) + + if (.not. (pow_block(0,1) > pow_block(1,1))) then + print *, 'test_jtty_block_pow: block detection failed to rescue the', & + ' misleading symbol at position 1' + error stop 1 + end if + if (maxloc(pow_block(:,1),dim=1)-1 /= 0) then + print *, 'test_jtty_block_pow: block-detected tone at position 1 is not the correct one' + error stop 1 + end if + if (maxloc(pow_block(:,2),dim=1)-1 /= 2) then + print *, 'test_jtty_block_pow: block-detected tone at position 2 is not the correct one' + error stop 1 + end if + end subroutine expect_block_detection_rescues_a_misleading_symbol + + subroutine expect_clean_signal_unaffected_by_block_detection() + ! Non-regression: on an unambiguous, noiseless signal, blocksize-2 and + ! blocksize-4 detection must pick exactly the same tone at every + ! position as blocksize-1 already does -- block detection is a fallback + ! that should never second-guess an already-clean reading. + integer(int32) :: tone_symbols(TOTAL_K) + complex(real32) :: z(0:3, TOTAL_K) + real(real32) :: pow_block(0:3, TOTAL_K) + integer :: i, t, iblk + + do t = 1, TOTAL_K + tone_symbols(t) = mod(t, 4) ! deterministic, exercises all 4 tones + end do + + z = cmplx(0.0_real32, 0.0_real32, real32) + do t = 1, TOTAL_K + z(tone_symbols(t), t) = cmplx(1.0_real32, 0.0_real32, real32) + end do + + do iblk = 2, 4, 2 + call jtty_block_pow(z, TOTAL_K, iblk, pow_block) + do i = 1, TOTAL_K + if (maxloc(pow_block(:,i),dim=1)-1 /= tone_symbols(i)) then + print *, 'test_jtty_block_pow: clean-signal regression at position', i, & + ' iblock=', iblk + error stop 1 + end if + end do + end do + end subroutine expect_clean_signal_unaffected_by_block_detection + +end program test_jtty_block_pow diff --git a/tests/unit/jtty/test_jtty_draft_acceptance.cpp b/tests/unit/jtty/test_jtty_draft_acceptance.cpp new file mode 100644 index 00000000..f321aaf5 --- /dev/null +++ b/tests/unit/jtty/test_jtty_draft_acceptance.cpp @@ -0,0 +1,128 @@ +#include <QtTest> + +#include "widgets/JttyDraftAcceptanceTracker.hpp" + +class TestJttyDraftAcceptance final + : public QObject +{ + Q_OBJECT + +private slots: + void acceptedCurrentSubmissionClearsDraft () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + + QVERIFY (tracker.accept (1)); + } + + void rejectedSubmissionPreservesDraft () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.reject (1); + + QVERIFY (!tracker.accept (1)); + } + + void delayedAcceptancePreservesNewerDraft () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.noteDraftChanged (); + + QVERIFY (!tracker.accept (1)); + } + + void identicalRetypedDraftHasNewIdentity () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.noteDraftChanged (); + tracker.noteDraftChanged (); + + QVERIFY (!tracker.accept (1)); + } + + void unrelatedAcceptancePreservesDraft () + { + JttyDraftAcceptanceTracker tracker; + + QVERIFY (!tracker.accept (1)); + } + + void currentDraftReportsPendingSubmission () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + + QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); + QVERIFY (tracker.isPending (1)); + QVERIFY (!tracker.isPending (2)); + } + + void rejectedCurrentDraftCanBeRetried () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.reject (1); + + QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); + QVERIFY (!tracker.isPending (1)); + + tracker.trackSubmission (2); + QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); + QVERIFY (tracker.isPending (2)); + } + + void newerDraftCanBeSubmittedWhileOlderDraftIsPending () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.noteDraftChanged (); + + QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); + + tracker.trackSubmission (2); + QVERIFY (tracker.hasPendingSubmissionForCurrentDraft ()); + QVERIFY (tracker.isPending (1)); + QVERIFY (tracker.isPending (2)); + } + + void acceptedRequestIsNoLongerPending () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + + QVERIFY (tracker.accept (1)); + QVERIFY (!tracker.hasPendingSubmissionForCurrentDraft ()); + QVERIFY (!tracker.isPending (1)); + } + + void successiveAcceptedDraftsCanClear () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + QVERIFY (tracker.accept (1)); + + tracker.noteDraftChanged (); + tracker.noteDraftChanged (); + tracker.trackSubmission (2); + QVERIFY (tracker.accept (2)); + } + + void olderAcceptanceDoesNotClearSuccessiveDraft () + { + JttyDraftAcceptanceTracker tracker; + tracker.trackSubmission (1); + tracker.noteDraftChanged (); + tracker.trackSubmission (2); + + QVERIFY (!tracker.accept (1)); + QVERIFY (tracker.accept (2)); + } +}; + +QTEST_GUILESS_MAIN (TestJttyDraftAcceptance) + +#include "test_jtty_draft_acceptance.moc" diff --git a/tests/unit/jtty/test_jtty_frequency_window.f90 b/tests/unit/jtty/test_jtty_frequency_window.f90 new file mode 100644 index 00000000..897fd823 --- /dev/null +++ b/tests/unit/jtty/test_jtty_frequency_window.f90 @@ -0,0 +1,89 @@ +program test_jtty_frequency_window + use jtty_mdec, only: jtty_search_window + implicit none + + integer, parameter :: first_bin=3,last_bin=4094 + real, parameter :: df=6000.0/8192.0 + integer :: ja,jb + real :: fc + logical :: usable + + fc=1500.0 + call jtty_search_window(fc,50.0,200,2800,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'nominal window is usable') + call assert_true(fc.eq.1500.0, 'nominal center is unchanged') + call assert_true(ja.eq.int(1450.0/df), 'nominal lower bin is unchanged') + call assert_true(jb.eq.int(1550.0/df), 'nominal upper bin is unchanged') + + fc=2500.0 + call jtty_search_window(fc,1000.0,0,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'partially overlapping upper window is usable') + call assert_true(ja.eq.int(1500.0/df), 'partial upper window keeps its lower bin') + call assert_true(jb.eq.last_bin, 'partial upper window is clipped to the spectrum') + + fc=5000.0 + call jtty_search_window(fc,1000.0,0,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'window above the spectrum is rejected') + + fc=1500.0 + call jtty_search_window(fc,20.0,4900,5000,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(fc.eq.4900.0, 'center is clamped to the graph lower edge') + call assert_true(.not.usable, 'graph above the spectrum is rejected') + + fc=1500.0 + call jtty_search_window(fc,20.0,4900,5000,.false.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'QSO window ignores an unrelated graph range') + call assert_true(fc.eq.1500.0, 'QSO center is not moved to the graph edge') + call assert_true(ja.eq.int(1480.0/df), 'QSO lower bin follows Rx tolerance') + call assert_true(jb.eq.int(1520.0/df), 'QSO upper bin follows Rx tolerance') + + fc=1500.0 + call jtty_search_window(fc,20.0,1800,1200,.false.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'QSO window ignores inverted graph limits') + call assert_true(fc.eq.1500.0, 'inverted graph limits do not move QSO center') + + fc=1350.0 + call jtty_search_window(fc,150.0,1400,1600,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'lower auxiliary edge is usable') + call assert_true(fc.eq.1400.0, 'lower auxiliary center is clamped') + call assert_true(ja.eq.ceiling(1400.0/df), 'lower graph edge clips the window') + + fc=1650.0 + call jtty_search_window(fc,150.0,1400,1600,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(usable, 'upper auxiliary edge is usable') + call assert_true(fc.eq.1600.0, 'upper auxiliary center is clamped') + call assert_true(jb.eq.floor(1600.0/df), 'upper graph edge clips the window') + + fc=1500.0 + call jtty_search_window(fc,50.0,1800,1200,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'inverted graph limits are rejected') + + fc=1500.0 + call jtty_search_window(fc,-1.0,200,2800,.true.,df,first_bin,last_bin, & + ja,jb,usable) + call assert_true(.not.usable, 'negative window width is rejected') + + print *, 'JTTY frequency window tests passed' + +contains + + subroutine assert_true(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine assert_true + +end program test_jtty_frequency_window diff --git a/tests/unit/jtty/test_jtty_gap_merge.f90 b/tests/unit/jtty/test_jtty_gap_merge.f90 new file mode 100644 index 00000000..ff13e28e --- /dev/null +++ b/tests/unit/jtty/test_jtty_gap_merge.f90 @@ -0,0 +1,135 @@ +program test_jtty_gap_merge + + ! When a frame in the middle of a multi-frame message fails to decode + ! (common at marginal SNR), the message must still remain one message with + ! a gap marker between the surviving fragments, not split into two + ! messages (the bug Joe reported on 000000_000011.wav: "THE QUICK BROWN FOX + ! JUMPED OVER THE LAZY DOG." decoded as two separate lines, "THE Q" and + ! "BROWN FOX JUMPED OVER THE LAZY DOG.", losing "UICK " with no trace). + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg='THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.' + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: failures,total_samples,nframes + integer(int16), allocatable :: reference_pcm(:) + + failures=0 + + call build_message_pcm(msg,reference_pcm,total_samples,nframes) + call run_dropped_frame_case(msg,reference_pcm,total_samples,nframes,1,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_gap_merge: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_gap_merge: all checks passed' + +contains + + subroutine build_message_pcm(message,pcm,total_samples,nframes) + character(len=*), intent(in) :: message + integer(int16), allocatable, intent(out) :: pcm(:) + integer, intent(out) :: total_samples,nframes + integer :: tones(MAX_FRAMES*frame_symbols) + integer :: nsymbols + real, allocatable :: wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: input + + input=message + call genjtty(input,tones,nsymbols) + nframes=nsymbols/frame_symbols + total_samples=(nsymbols+frame_symbols)*nsps + allocate(wave(nsymbols*nsps),complex_wave(nsymbols*nsps),pcm(total_samples)) + call gen_jttywave(tones,nsymbols,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsymbols*nsps) + pcm=0_int16 + pcm(1:nsymbols*nsps)=int(nint(30000.0*wave),int16) + end subroutine build_message_pcm + + ! Drops consecutive middle frames and confirms the message still merges + ! into one slot with a fixed-width gap marker. + subroutine run_dropped_frame_case(expected_text,reference_pcm, & + total_samples,nframes,n_dropped,count) + character(len=*), intent(in) :: expected_text + integer(int16), intent(in) :: reference_pcm(:) + integer, intent(in) :: total_samples,nframes,n_dropped + integer, intent(inout) :: count + integer :: idrop + integer :: drop_start,drop_end + integer(int16), allocatable :: pcm(:) + character(len=80) :: before,after + character(len=200) :: description + integer :: gap_pos + logical :: surviving_text_matches + + pcm=reference_pcm + idrop=nframes/2 + + ! Zero out idrop..idrop+n_dropped-1's audio so those frames can't sync. + drop_start=(idrop-1)*frame_symbols*nsps+1 + drop_end=(idrop+n_dropped-1)*frame_symbols*nsps + pcm(drop_start:drop_end)=0_int16 + + call discard_pending_updates() + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s) still merges into one message' + call expect(npending.eq.1,trim(description),count) + if(npending.ne.1) return + + ! The gap sentinel is a fixed-width 5-tilde run regardless of how many + ! frames were actually dropped -- " ... " is a generic "something's + ! missing" marker, not a precise character count (matches Joe's own + ! suggested display). + gap_pos=index(pending_updates(1)%decoded,'~~~~~') + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s) leaves a gap sentinel' + call expect(gap_pos.gt.0,trim(description),count) + if(gap_pos.le.0) return + + before=trim(normalized(adjustl(pending_updates(1)%decoded(1:gap_pos-1)))) + after=trim(normalized(adjustl(pending_updates(1)%decoded(gap_pos+5:)))) + write(description,'(a,i0,a)') 'dropping ',n_dropped, & + ' consecutive frame(s): surviving text matches the original message' + surviving_text_matches=.false. + if(len_trim(before).gt.0 .and. len_trim(after).gt.0 .and. & + len_trim(after).le.len_trim(expected_text)) then + surviving_text_matches=index(expected_text,trim(before)).eq.1 .and. & + expected_text(len_trim(expected_text)-len_trim(after)+1: & + len_trim(expected_text)).eq.trim(after) + endif + call expect(surviving_text_matches,trim(description),count) + end subroutine run_dropped_frame_case + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_gap_merge diff --git a/tests/unit/jtty/test_jtty_get_updates.f90 b/tests/unit/jtty/test_jtty_get_updates.f90 new file mode 100644 index 00000000..0ecf61dc --- /dev/null +++ b/tests/unit/jtty/test_jtty_get_updates.f90 @@ -0,0 +1,113 @@ +program test_jtty_get_updates + use iso_fortran_env, only: int64 + use jtty_mdec, only: message_assembly,npending,discard_pending_updates, & + queue_message_update + implicit none + + integer, parameter :: BATCH_SIZE=30,TEXT_WIDTH=80 + character(len=BATCH_SIZE*TEXT_WIDTH) :: text_blocks + integer(int64) :: message_ids(BATCH_SIZE) + real :: frequencies(BATCH_SIZE),start_tsync(BATCH_SIZE) + logical*1 :: eom(BATCH_SIZE) + type(message_assembly) :: message + integer :: i,count + + call discard_pending_updates() + + message=make_message(41_int64,1500.4,1.25,'CQ K1ABC') + call queue_message_update(message,.false.) + message%decoded='CQ K1ABC FN20' + call queue_message_update(message,.true.) + call expect(npending.eq.1, & + 'updates for one logical message coalesce before delivery') + + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.1 .and. npending.eq.0, & + 'retrieving an update drains it exactly once') + call expect(message_ids(1).eq.41_int64 .and. & + trim(block_text(text_blocks,1)).eq.'CQ K1ABC FN20', & + 'the batch contains the newest state and stable identity') + call expect(abs(frequencies(1)-1500.4).lt.0.001 .and. & + abs(start_tsync(1)-1.25).lt.0.001 .and. eom(1), & + 'the batch preserves structured message metadata') + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.0, 'a drained update is not returned again') + + message=make_message(42_int64,1501.0,2.5,'UNCHANGED TEXT') + call queue_message_update(message,.false.) + call queue_message_update(message,.true.) + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.1 .and. eom(1) .and. & + trim(block_text(text_blocks,1)).eq.'UNCHANGED TEXT', & + 'completion metadata coalesces when message text is unchanged') + + do i=1,35 + message=make_message(int(100+i,int64),1400.0+real(i), & + 10.0+real(i),'MESSAGE') + write(message%decoded,'(a,i0)') 'MESSAGE ',i + message%k=len_trim(message%decoded) + call queue_message_update(message,mod(i,2).eq.0) + enddo + call expect(npending.eq.35, & + 'the pending store retains more than one ABI batch') + + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.BATCH_SIZE .and. npending.eq.5, & + 'the first batch drains the oldest thirty updates') + do i=1,BATCH_SIZE + call expect(message_ids(i).eq.int(100+i,int64), & + 'the first batch preserves update order') + call expect(abs(frequencies(i)-(1400.0+real(i))).lt.0.001 .and. & + abs(start_tsync(i)-(10.0+real(i))).lt.0.001, & + 'the first batch preserves numeric metadata') + call expect(eom(i) .eqv. (mod(i,2).eq.0), & + 'the first batch preserves completion state') + enddo + + call jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count) + call expect(count.eq.5 .and. npending.eq.0, & + 'a second batch drains every remaining update') + do i=1,5 + call expect(message_ids(i).eq.int(130+i,int64), & + 'the second batch continues in update order') + enddo + + print *, 'test_jtty_get_updates: all checks passed' + +contains + + function make_message(id,frequency,tsync,text) result(value) + integer(int64), intent(in) :: id + real, intent(in) :: frequency,tsync + character(len=*), intent(in) :: text + type(message_assembly) :: value + + value%message_id=id + value%f1=frequency + value%tsync=tsync + value%start_tsync=tsync + value%decoded=text + value%k=len_trim(value%decoded) + end function make_message + + function block_text(blocks,index) result(text) + character(len=*), intent(in) :: blocks + integer, intent(in) :: index + character(len=TEXT_WIDTH) :: text + integer :: first + + first=(index-1)*TEXT_WIDTH+1 + text=blocks(first:first+TEXT_WIDTH-1) + end function block_text + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine expect + +end program test_jtty_get_updates diff --git a/tests/unit/jtty/test_jtty_message_matching.f90 b/tests/unit/jtty/test_jtty_message_matching.f90 new file mode 100644 index 00000000..1308009a --- /dev/null +++ b/tests/unit/jtty/test_jtty_message_matching.f90 @@ -0,0 +1,99 @@ +program test_jtty_message_matching + use jtty_mdec, only: decode,message_assembly,classify_active_candidate + implicit none + + real, parameter :: frame_period=2.0 + type(message_assembly) :: existing + type(decode) :: candidate + logical :: match,is_window_dupe + integer :: failures,nframes_gap + + failures=0 + existing%f1=1500.0 + existing%tsync=10.0 + existing%decoded='OPEN MESSAGE' + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+frame_period + candidate%decoded='CONTINUATION' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.1, & + 'an active message accepts the next frame',failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+frame_period/4.0 + candidate%decoded='SHIFTED REDISCOVERY' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. is_window_dupe, & + 'an active message rejects a quarter-frame rediscovery',failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+frame_period + candidate%decoded='WIDE CONTINUATION' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe, & + 'an active message accepts a 5 Hz next frame',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+2*frame_period + candidate%decoded='ONE MISSED FRAME' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.2, & + 'an active message bridges one missed frame',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+3*frame_period + candidate%decoded='TWO MISSED FRAMES' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. .not.is_window_dupe .and. nframes_gap.eq.3, & + 'an active message bridges two missed frames',failures) + + candidate%f1=1501.0 + candidate%tsync=existing%tsync+4*frame_period + candidate%decoded='THREE MISSED FRAMES' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(.not.match, & + 'an active message does not bridge beyond the continuation limit', & + failures) + + candidate%f1=1505.0 + candidate%tsync=existing%tsync+3*frame_period/4.0 + candidate%decoded='LAST RETRO STEP' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(match .and. is_window_dupe, & + 'the final actual retro step is classified as rediscovery',failures) + + candidate%tsync=existing%tsync+5*frame_period/4.0 + candidate%decoded='OUTSIDE RETRO HORIZON' + call classify_active_candidate(existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + call expect(.not.match, & + 'a later quarter-phase frame is not mistaken for rediscovery',failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_message_matching: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_message_matching: all checks passed' + +contains + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_message_matching diff --git a/tests/unit/jtty/test_jtty_messages.cpp b/tests/unit/jtty/test_jtty_messages.cpp new file mode 100644 index 00000000..7c38dfa4 --- /dev/null +++ b/tests/unit/jtty/test_jtty_messages.cpp @@ -0,0 +1,938 @@ +#include <QtTest> + +#include "widgets/JttyMessages.hpp" + +class TestJttyMessages final + : public QObject +{ + Q_OBJECT + +private slots: + void nativeMacroMappings () + { + Jtty::NativeMacroContext const context {QString {"k1abc"}, QString {"w9xyz"}, 7}; + + struct Expected + { + QString text; + QVector<int> kinds; + QVector<int> subtypes; + QVector<QString> calls; + }; + QVector<Expected> const expected { + {QString {"CQ K1ABC CQ"}, {0}, {0}, {QString {"K1ABC"}}}, + {QString {"W9XYZ 599 007"}, {0, 1}, {1, 0}, {QString {"W9XYZ"}, QString {}}}, + {QString {"W9XYZ TU CQ K1ABC CQ"}, {0, 0}, {3, 0}, + {QString {"W9XYZ"}, QString {"K1ABC"}}}, + {QString {"K1ABC"}, {0}, {1}, {QString {"K1ABC"}}}, + {QString {"W9XYZ"}, {0}, {1}, {QString {"W9XYZ"}}}, + {QString {"TU NOW W9XYZ 599 007"}, {0, 1}, {5, 0}, + {QString {"W9XYZ"}, QString {}}}, + {QString {"W9XYZ AGN?"}, {0}, {4}, {QString {"W9XYZ"}}}, + {QString {"599 007"}, {1}, {0}, {QString {}}} + }; + + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + auto const compiled = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + auto const& wanted = expected.at (functionKey - 1); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, wanted.text); + QCOMPARE (compiled.atoms.size (), wanted.kinds.size ()); + for (int i = 0; i < compiled.atoms.size (); ++i) { + auto const& atom = compiled.atoms.at (i); + QCOMPARE (int {atom.kind}, wanted.kinds.at (i)); + QCOMPARE (int {atom.subtype}, wanted.subtypes.at (i)); + QCOMPARE (int {atom.reserved}, 0); + QCOMPARE (QString::fromLatin1 (atom.text), wanted.calls.at (i)); + if (atom.kind == static_cast<qint8> (Jtty::NativeAtomKind::ExchangeNumber)) { + QCOMPARE (int {atom.role}, static_cast<int> (Jtty::ExchangeRole::Full)); + QCOMPARE (atom.value, qint32 {7}); + } else { + QCOMPARE (int {atom.role}, 0); + QCOMPARE (atom.value, qint32 {0}); + } + } + } + } + + void nativeMacroMatchesCaseAndWhitespaceBeforeExpansion () + { + Jtty::NativeMacroContext const context {QString {" k1abc "}, QString {" w9xyz "}, 42}; + auto const compiled = Jtty::compileNativeMacro ( + 3, QString {" \t%h tu\n cq %m cq "}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QString {"W9XYZ TU CQ K1ABC CQ"}); + QCOMPARE (compiled.atoms.size (), 2); + QCOMPARE (QString::fromLatin1 (compiled.atoms.at (0).text), QString {"W9XYZ"}); + QCOMPARE (QString::fromLatin1 (compiled.atoms.at (1).text), QString {"K1ABC"}); + } + + void customizedMacroFallsBackToExpandedLiteral () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 7}; + auto const customized = Jtty::compileNativeMacro ( + 2, QString {"TEST %H 599 %N"}, context); + QCOMPARE (customized.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (customized.text, QString {"TEST W9XYZ 599 007"}); + QVERIFY (customized.atoms.isEmpty ()); + + auto const movedDefault = Jtty::compileNativeMacro ( + 4, QString {"%H"}, context); + QCOMPARE (movedDefault.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (movedDefault.text, QString {"W9XYZ"}); + QCOMPARE (movedDefault.atoms.size (), 1); + QCOMPARE (int {movedDefault.atoms.at (0).subtype}, + static_cast<int> (Jtty::CallAction::Call)); + + auto const unknownPlaceholder = Jtty::compileNativeMacro ( + 8, QString {"599 %R"}, context); + QCOMPARE (unknownPlaceholder.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (unknownPlaceholder.text, QString {"599 %R"}); + + auto const editedLegacyCase = Jtty::compileNativeMacro ( + 2, QString {"%h 599 %n"}, context); + QCOMPARE (editedLegacyCase.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (editedLegacyCase.text, QString {"%h 599 %n"}); + + auto const editedLegacySpacing = Jtty::compileNativeMacro ( + 8, QString {" 599 %N "}, context); + QCOMPARE (editedLegacySpacing.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (editedLegacySpacing.text, QString {" 599 007 "}); + } + + void blankMacroDoesNotSelectNativeCq () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 7}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + for (QString const& macro : {QString {}, QString {" \t "}}) { + auto const compiled = Jtty::compileNativeMacro (functionKey, macro, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::LiteralFallback); + QVERIFY (compiled.atoms.isEmpty ()); + QVERIFY (compiled.text.trimmed ().isEmpty ()); + } + } + } + + void nativeCallDescriptorTextIsBounded () + { + auto const atom = Jtty::nativeCallAtom ( + Jtty::CallAction::Call, QStringLiteral ("K1ABCDEFGHIJK")); + QCOMPARE (QString::fromLatin1 (atom.text), QStringLiteral ("K1ABCDEF")); + } + + void recognizedMacroRejectsInvalidRuntime_data () + { + QTest::addColumn<int> ("functionKey"); + QTest::addColumn<QString> ("myCall"); + QTest::addColumn<QString> ("hisCall"); + QTest::addColumn<int> ("serialNumber"); + + QTest::newRow ("missing-my-call") << 1 << QString {} << QString {"W9XYZ"} << 1; + QTest::newRow ("missing-his-call") << 2 << QString {"K1ABC"} << QString {} << 1; + QTest::newRow ("call-without-area") << 4 << QString {"KABC"} << QString {"W9XYZ"} << 1; + QTest::newRow ("call-without-suffix") << 5 << QString {"K1ABC"} << QString {"W9"} << 1; + QTest::newRow ("q-prefix") << 7 << QString {"K1ABC"} << QString {"Q1ABC"} << 1; + QTest::newRow ("portable-call") << 3 << QString {"K1ABC/P"} << QString {"W9XYZ"} << 1; + QTest::newRow ("negative-serial") << 8 << QString {"K1ABC"} << QString {"W9XYZ"} << -1; + QTest::newRow ("serial-overflow") << 6 << QString {"K1ABC"} << QString {"W9XYZ"} + << (1 << 17); + } + + void recognizedMacroRejectsInvalidRuntime () + { + QFETCH (int, functionKey); + QFETCH (QString, myCall); + QFETCH (QString, hisCall); + QFETCH (int, serialNumber); + Jtty::NativeMacroContext const context {myCall, hisCall, serialNumber}; + + auto const compiled = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (compiled.atoms.isEmpty ()); + QVERIFY (compiled.text.isEmpty ()); + } + + void nativeRuntimeBoundariesAndUnusedFields () + { + auto const minimum = Jtty::compileNativeMacro ( + 8, Jtty::nativeMacroTemplate (8), {QString {}, QString {}, 0}); + QCOMPARE (minimum.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (minimum.text, QString {"599 000"}); + QCOMPARE (minimum.atoms.at (0).value, qint32 {0}); + + auto const maximum = Jtty::compileNativeMacro ( + 8, Jtty::nativeMacroTemplate (8), {QString {}, QString {}, (1 << 17) - 1}); + QCOMPARE (maximum.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (maximum.text, QString {"599 131071"}); + QCOMPARE (maximum.atoms.at (0).value, qint32 {(1 << 17) - 1}); + + auto const unusedInvalidFields = Jtty::compileNativeMacro ( + 1, Jtty::nativeMacroTemplate (1), {QString {"K1ABC"}, QString {}, -1}); + QCOMPARE (unusedInvalidFields.status, Jtty::NativeMacroStatus::Native); + } + + void functionKeyApiIsParityFriendly () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 123}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + QString const configuredText = Jtty::nativeMacroTemplate (functionKey); + auto const keyboard = Jtty::compileNativeMacro (functionKey, configuredText, context); + auto const button = Jtty::compileNativeMacro (functionKey, configuredText, context); + QCOMPARE (keyboard.status, button.status); + QCOMPARE (keyboard.text, button.text); + QCOMPARE (keyboard.atoms.size (), button.atoms.size ()); + for (int i = 0; i < keyboard.atoms.size (); ++i) { + QCOMPARE (keyboard.atoms.at (i).kind, button.atoms.at (i).kind); + QCOMPARE (keyboard.atoms.at (i).subtype, button.atoms.at (i).subtype); + QCOMPARE (keyboard.atoms.at (i).role, button.atoms.at (i).role); + QCOMPARE (keyboard.atoms.at (i).value, button.atoms.at (i).value); + QCOMPARE (QString::fromLatin1 (keyboard.atoms.at (i).text), + QString::fromLatin1 (button.atoms.at (i).text)); + } + } + } + + void legacyAndProfileAwareTemplatesRemainNative () + { + Jtty::NativeMacroContext const context {QString {"K1ABC"}, QString {"W9XYZ"}, 12}; + for (int functionKey = 1; functionKey <= 8; ++functionKey) { + auto const current = Jtty::compileNativeMacro ( + functionKey, Jtty::nativeMacroTemplate (functionKey), context); + auto const legacy = Jtty::compileNativeMacro ( + functionKey, Jtty::legacyNativeMacroTemplate (functionKey), context); + QCOMPARE (current.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (legacy.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (current.text, legacy.text); + QCOMPARE (current.atoms.size (), legacy.atoms.size ()); + } + + QCOMPARE (Jtty::nativeMacroTemplate (2), QString {"%H %E"}); + QCOMPARE (Jtty::nativeMacroTemplate (6), QString {"TU NOW %Q %E"}); + QCOMPARE (Jtty::nativeMacroTemplate (8), QString {"%E"}); + } + + void savedDefaultMigrationIsExactAndNarrow () + { + for (int functionKey : {2, 6, 8}) { + QCOMPARE (Jtty::migratedNativeMacroTemplate ( + functionKey, Jtty::legacyNativeMacroTemplate (functionKey)), + Jtty::nativeMacroTemplate (functionKey)); + } + + QCOMPARE (Jtty::migratedNativeMacroTemplate (1, QString {"CQ %M CQ"}), + QString {"CQ %M CQ"}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (2, QString {"%h 599 %n"}), + QString {"%h 599 %n"}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (8, QString {" 599 %N "}), + QString {" 599 %N "}); + QCOMPARE (Jtty::migratedNativeMacroTemplate (8, QString {"TEST 599 %N"}), + QString {"TEST 599 %N"}); + } + + void noneProfileUsesLiveSerial () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 7, Jtty::NativeExchangeProfile::None}; + auto const compiled = Jtty::compileNativeMacro (QString {"%H %E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QString {"W9XYZ 599 007"}); + QCOMPARE (compiled.atoms.size (), 2); + QCOMPARE (int {compiled.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber)); + QCOMPARE (int {compiled.atoms.at (1).subtype}, + static_cast<int> (Jtty::NumberKind::Serial)); + QCOMPARE (int {compiled.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::Full)); + QCOMPARE (compiled.atoms.at (1).value, qint32 {7}); + } + + void fieldDayProfileParsesClassAndSection_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::addColumn<QString> ("text"); + QTest::addColumn<int> ("count"); + QTest::addColumn<int> ("classIndex"); + QTest::addColumn<QString> ("section"); + + QTest::newRow ("minimum") << QString {"1A AB"} << QString {"1A AB"} + << 1 << 0 << QString {"AB"}; + QTest::newRow ("maximum") << QString {"32F EMA"} << QString {"32F EMA"} + << 32 << 5 << QString {"EMA"}; + QTest::newRow ("normalizes-case-and-spacing") + << QString {" 2d wma "} << QString {"2D WMA"} << 2 << 3 << QString {"WMA"}; + } + + void compactFieldDayConfigurationIsNormalized () + { + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral ("3AOR")), + QStringLiteral ("3A OR")); + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral (" 32fema ")), + QStringLiteral ("32F EMA")); + QCOMPARE (Jtty::normalizedFieldDayExchange (QStringLiteral ("3A OR")), + QStringLiteral ("3A OR")); + + Jtty::NativeMacroContext context; + context.exchangeProfile = Jtty::NativeExchangeProfile::FieldDay; + context.configuredExchange = Jtty::normalizedFieldDayExchange ( + QStringLiteral ("3AOR")); + auto const compiled = Jtty::compileNativeMacro (QStringLiteral ("%E"), context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, QStringLiteral ("3A OR")); + } + + void fieldDayProfileParsesClassAndSection () + { + QFETCH (QString, exchange); + QFETCH (QString, text); + QFETCH (int, count); + QFETCH (int, classIndex); + QFETCH (QString, section); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::FieldDay, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, text); + QCOMPARE (compiled.atoms.size (), 1); + auto const& atom = compiled.atoms.constFirst (); + QCOMPARE (int {atom.kind}, static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + QCOMPARE (int {atom.subtype}, static_cast<int> (Jtty::PairSchema::ClassSection)); + QCOMPARE (int {atom.role}, classIndex); + QCOMPARE (atom.value, qint32 {count}); + QCOMPARE (QString::fromLatin1 (atom.text), section); + } + + void profileExchangeComposesWithCallActions () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::FieldDay, QString {"2D WMA"}}; + + auto const reply = Jtty::compileNativeMacro (QString {"%H %E"}, context); + QCOMPARE (reply.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (reply.text, QString {"W9XYZ 2D WMA"}); + QCOMPARE (reply.atoms.size (), 2); + QCOMPARE (int {reply.atoms.at (0).kind}, static_cast<int> (Jtty::NativeAtomKind::Call)); + QCOMPARE (int {reply.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + + auto const queued = Jtty::compileNativeMacro (QString {"TU NOW %Q %E"}, context); + QCOMPARE (queued.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (queued.text, QString {"TU NOW W9XYZ 2D WMA"}); + QCOMPARE (queued.atoms.size (), 2); + QCOMPARE (int {queued.atoms.at (0).subtype}, + static_cast<int> (Jtty::CallAction::TuNowCall)); + QCOMPARE (int {queued.atoms.at (1).kind}, + static_cast<int> (Jtty::NativeAtomKind::ExchangePair)); + } + + void invalidFieldDayExchangeIsRejected_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::newRow ("missing") << QString {}; + QTest::newRow ("zero-count") << QString {"0A EMA"}; + QTest::newRow ("count-overflow") << QString {"33A EMA"}; + QTest::newRow ("bad-class") << QString {"1G EMA"}; + QTest::newRow ("short-section") << QString {"1A E"}; + QTest::newRow ("long-section") << QString {"1A WMAA"}; + QTest::newRow ("non-base36-section") << QString {"1A E-A"}; + QTest::newRow ("noncanonical-three-character-section") << QString {"1A 0AB"}; + } + + void invalidFieldDayExchangeIsRejected () + { + QFETCH (QString, exchange); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::FieldDay, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + QVERIFY (compiled.atoms.isEmpty ()); + } + + void rttyProfileParsesConfiguredExchange_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::addColumn<int> ("serial"); + QTest::addColumn<int> ("kind"); + QTest::addColumn<int> ("value"); + QTest::addColumn<QString> ("atomText"); + QTest::addColumn<QString> ("rendered"); + + QTest::newRow ("dx-live-serial") << QString {"DX"} << 42 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 42 << QString {} + << QString {"599 042"}; + QTest::newRow ("hash-live-serial") << QString {"#"} << 1234 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 1234 << QString {} + << QString {"599 1234"}; + QTest::newRow ("decimal-serial") << QString {"0013"} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeNumber) << 13 << QString {} + << QString {"599 013"}; + QTest::newRow ("state") << QString {" ma "} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation) << 0 << QString {"MA"} + << QString {"599 MA"}; + QTest::newRow ("province") << QString {"nwt"} << 99 + << static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation) << 0 << QString {"NWT"} + << QString {"599 NWT"}; + } + + void rttyProfileParsesConfiguredExchange () + { + QFETCH (QString, exchange); + QFETCH (int, serial); + QFETCH (int, kind); + QFETCH (int, value); + QFETCH (QString, atomText); + QFETCH (QString, rendered); + Jtty::NativeMacroContext const context { + QString {}, QString {}, serial, Jtty::NativeExchangeProfile::RttyRoundup, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, rendered); + auto const& atom = compiled.atoms.constFirst (); + QCOMPARE (int {atom.kind}, kind); + QCOMPARE (atom.value, qint32 {value}); + QCOMPARE (QString::fromLatin1 (atom.text), atomText); + if (kind == static_cast<int> (Jtty::NativeAtomKind::ExchangeLocation)) { + QCOMPARE (int {atom.subtype}, static_cast<int> (Jtty::LocationKind::StateProvince)); + QCOMPARE (int {atom.role}, static_cast<int> (Jtty::ExchangeRole::Full)); + } + } + + void invalidRttyExchangeIsRejected_data () + { + QTest::addColumn<QString> ("exchange"); + QTest::newRow ("empty") << QString {}; + QTest::newRow ("one-character") << QString {"M"}; + QTest::newRow ("too-long") << QString {"NWTX"}; + QTest::newRow ("punctuation") << QString {"M-A"}; + QTest::newRow ("noncanonical-three-character-token") << QString {"0MA"}; + QTest::newRow ("decimal-overflow") << QString {"131072"}; + } + + void invalidRttyExchangeIsRejected () + { + QFETCH (QString, exchange); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 7, Jtty::NativeExchangeProfile::RttyRoundup, exchange}; + auto const compiled = Jtty::compileNativeMacro (QString {"%E"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + } + + void gridMacroUsesFieldOnlyAndFullRoles_data () + { + QTest::addColumn<QString> ("macro"); + QTest::addColumn<QString> ("grid"); + QTest::addColumn<int> ("role"); + QTest::addColumn<QString> ("text"); + QTest::newRow ("field-only-lower-bound") << QString {"%G"} << QString {"aa00"} + << static_cast<int> (Jtty::ExchangeRole::FieldOnly) << QString {"AA00"}; + QTest::newRow ("field-only-upper-bound") << QString {"%G"} << QString {"RR99"} + << static_cast<int> (Jtty::ExchangeRole::FieldOnly) << QString {"RR99"}; + QTest::newRow ("full") << QString {"599 %G"} << QString {"FN42"} + << static_cast<int> (Jtty::ExchangeRole::Full) << QString {"599 FN42"}; + } + + void gridMacroUsesFieldOnlyAndFullRoles () + { + QFETCH (QString, macro); + QFETCH (QString, grid); + QFETCH (int, role); + QFETCH (QString, text); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::None, QString {}, grid}; + auto const compiled = Jtty::compileNativeMacro (macro, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, text); + QCOMPARE (compiled.atoms.size (), 1); + QCOMPARE (int {compiled.atoms.constFirst ().kind}, + static_cast<int> (Jtty::NativeAtomKind::Grid4)); + QCOMPARE (int {compiled.atoms.constFirst ().role}, role); + QCOMPARE (QString::fromLatin1 (compiled.atoms.constFirst ().text), grid.toUpper ()); + } + + void callAndQueuedGridTemplatesKeepGridFieldOnly () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::None, QString {}, QString {"FN42"}}; + + auto const call = Jtty::compileNativeMacro (QString {"%H %G"}, context); + QCOMPARE (call.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (call.text, QString {"W9XYZ FN42"}); + QCOMPARE (call.atoms.size (), 2); + QCOMPARE (int {call.atoms.at (1).kind}, static_cast<int> (Jtty::NativeAtomKind::Grid4)); + QCOMPARE (int {call.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::FieldOnly)); + + auto const queued = Jtty::compileNativeMacro (QString {"TU NOW %Q %G"}, context); + QCOMPARE (queued.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (queued.text, QString {"TU NOW W9XYZ FN42"}); + QCOMPARE (queued.atoms.size (), 2); + QCOMPARE (int {queued.atoms.at (1).role}, + static_cast<int> (Jtty::ExchangeRole::FieldOnly)); + } + + void configuredSubsquareProducesGrid4WithoutChangingLiteralExpansion () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 1, + Jtty::NativeExchangeProfile::None, QString {}, QString {"fn42ab"}}; + auto const native = Jtty::compileNativeMacro (QString {"%H %G"}, context); + QCOMPARE (native.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (native.text, QString {"W9XYZ FN42"}); + QCOMPARE (QString::fromLatin1 (native.atoms.at (1).text), QString {"FN42"}); + + auto const literal = Jtty::compileNativeMacro (QString {"GRID %G"}, context); + QCOMPARE (literal.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (literal.text, QString {"GRID fn42ab"}); + } + + void invalidGridIsRejected_data () + { + QTest::addColumn<QString> ("grid"); + QTest::newRow ("empty") << QString {}; + QTest::newRow ("short") << QString {"AA0"}; + QTest::newRow ("field-overflow") << QString {"AS00"}; + QTest::newRow ("square-letter") << QString {"AA0A"}; + QTest::newRow ("invalid-subsquare") << QString {"FN42AZ"}; + } + + void invalidGridIsRejected () + { + QFETCH (QString, grid); + Jtty::NativeMacroContext const context { + QString {}, QString {}, 1, Jtty::NativeExchangeProfile::None, QString {}, grid}; + auto const compiled = Jtty::compileNativeMacro (QString {"%G"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::InvalidRuntime); + QVERIFY (!compiled.error.isEmpty ()); + } + + void registeredControlPhrasesCompileNatively () + { + Jtty::NativeMacroContext const context; + for (int phraseId = 0; phraseId < 18; ++phraseId) { + auto const compiled = Jtty::compileNativeMacro ( + QString {" %1 "}.arg (Jtty::controlPhrase (phraseId).toLower ()), context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::Native); + QCOMPARE (compiled.text, Jtty::controlPhrase (phraseId)); + QCOMPARE (compiled.atoms.size (), 1); + QCOMPARE (int {compiled.atoms.constFirst ().kind}, + static_cast<int> (Jtty::NativeAtomKind::Control)); + QCOMPARE (int {compiled.atoms.constFirst ().subtype}, phraseId); + } + } + + void customLiteralExpandsProfileFields () + { + Jtty::NativeMacroContext const context { + QString {"K1ABC"}, QString {"W9XYZ"}, 7, + Jtty::NativeExchangeProfile::RttyRoundup, QString {" dx "}, QString {"fn42"}}; + auto const compiled = Jtty::compileNativeMacro (QString {"TEST %E %G"}, context); + QCOMPARE (compiled.status, Jtty::NativeMacroStatus::LiteralFallback); + QCOMPARE (compiled.text, QString {"TEST 007 fn42"}); + QVERIFY (compiled.error.isEmpty ()); + } + + void prepareTransmitText_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<QString> ("expected"); + QTest::addColumn<bool> ("substituted"); + QTest::addColumn<bool> ("truncated"); + + QTest::newRow ("empty") << QString {} << QString {} + << false << false; + QTest::newRow ("supported") << QString {"CQ KA1ABC CQ"} << QString {"CQ KA1ABC CQ"} + << false << false; + QTest::newRow ("lowercase-preserved") << QString {"cq ka1abc cq"} << QString {"cq ka1abc cq"} + << false << false; + QTest::newRow ("tab") << QString {"HELLO\tWORLD"} << QString {"HELLO#WORLD"} + << true << false; + QTest::newRow ("cr-lf") << QString {"HELLO\r\nWORLD"} << QString {"HELLO##WORLD"} + << true << false; + QTest::newRow ("nul") << (QString {"A"} + QChar::Null + QString {"B"}) << QString {"A B"} + << true << false; + QTest::newRow ("display-space-marker") << QString {"A~B"} << QString {"A B"} + << true << false; + QTest::newRow ("exactly-80") << QString (80, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) + << false << false; + QTest::newRow ("truncated") << QString (81, QLatin1Char {'A'}) << QString (80, QLatin1Char {'A'}) + << false << true; + QTest::newRow ("unsupported-past-limit") + << (QString (80, QLatin1Char {'A'}) + QString {"\t"}) + << QString (80, QLatin1Char {'A'}) + << false << true; + QTest::newRow ("substitution-and-truncation") + << (QString (79, QLatin1Char {'A'}) + QString {"\tB"}) + << (QString (79, QLatin1Char {'A'}) + QString {"#"}) + << true << true; + } + + void prepareTransmitText () + { + QFETCH (QString, message); + QFETCH (QString, expected); + QFETCH (bool, substituted); + QFETCH (bool, truncated); + + auto const prepared = Jtty::prepareTransmitText (message); + + QCOMPARE (prepared.text, expected); + QCOMPARE (prepared.substituted, substituted); + QCOMPARE (prepared.truncated, truncated); + QCOMPARE (prepared.changed (), substituted || truncated); + } + + void withChainedSpacing_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<bool> ("isChained"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("not-chained-unchanged") << QString {"CQ KA1ABC CQ"} << false + << QString {"CQ KA1ABC CQ"}; + QTest::newRow ("chained-gets-leading-space") << QString {"TU DE KA1ABC"} << true + << QString {" TU DE KA1ABC"}; + QTest::newRow ("not-chained-empty-stays-empty") << QString {} << false << QString {}; + QTest::newRow ("chained-at-max-length-drops-last-char") + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) << true + << (QString {" "} + QString (Jtty::maxTransmitLength - 1, QLatin1Char {'A'})); + } + + void withChainedSpacing () + { + QFETCH (QString, message); + QFETCH (bool, isChained); + QFETCH (QString, expected); + + QCOMPARE (Jtty::withChainedSpacing (message, isChained), expected); + } + + void transmitFrame_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<bool> ("isChained"); + QTest::addColumn<QString> ("expected"); + + auto const padded = [] (QString const& text) { + return text + QString (Jtty::maxTransmitLength - text.size (), QLatin1Char {' '}); + }; + + QTest::newRow ("not-chained-padded-to-width") + << QString {"CQ KA1ABC CQ"} << false << padded (QString {"CQ KA1ABC CQ"}); + QTest::newRow ("chained-prefixed-and-padded") + << QString {"TU K1ABC CQ"} << true << padded (QString {" TU K1ABC CQ"}); + QTest::newRow ("chained-at-max-length-stays-exact") + << QString (Jtty::maxTransmitLength, QLatin1Char {'A'}) << true + << (QString {" "} + QString (Jtty::maxTransmitLength - 1, QLatin1Char {'A'})); + QTest::newRow ("empty-not-chained-all-spaces") + << QString {} << false << QString (Jtty::maxTransmitLength, QLatin1Char {' '}); + } + + void transmitFrame () + { + QFETCH (QString, message); + QFETCH (bool, isChained); + QFETCH (QString, expected); + + QString const frame = Jtty::transmitFrame (message, isChained); + + QCOMPARE (frame, expected); + QCOMPARE (frame.size (), Jtty::maxTransmitLength); + } + + void wavCaptureValid_data () + { + QTest::addColumn<qint32> ("k0"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("zero") << qint32 {0} << false; + QTest::newRow ("negative") << qint32 {-1} << false; + QTest::newRow ("below-one-frame") << qint32 {Jtty::jttyFrameSamples - 1} << false; + QTest::newRow ("exactly-one-frame") << qint32 {Jtty::jttyFrameSamples} << false; + QTest::newRow ("just-over-one-frame") << qint32 {Jtty::jttyFrameSamples + 1} << true; + QTest::newRow ("typical-interval") << qint32 {1000000} << true; + QTest::newRow ("sentinel-minus-one") << qint32 {Jtty::invalidCaptureSamples - 1} << true; + QTest::newRow ("sentinel") << qint32 {Jtty::invalidCaptureSamples} << false; + QTest::newRow ("sentinel-plus-one") << qint32 {Jtty::invalidCaptureSamples + 1} << false; + } + + void wavCaptureValid () + { + QFETCH (qint32, k0); + QFETCH (bool, expected); + + QCOMPARE (Jtty::wavCaptureValid (k0), expected); + } + + void formatSerialNumber_data () + { + QTest::addColumn<int> ("serialNumber"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("minimum") << 1 << QString {"001"}; + QTest::newRow ("single-digit") << 5 << QString {"005"}; + QTest::newRow ("two-digit") << 57 << QString {"057"}; + QTest::newRow ("three-digit") << 101 << QString {"101"}; + QTest::newRow ("four-digit") << 1234 << QString {"1234"}; + QTest::newRow ("spinbox-maximum") << 5000 << QString {"5000"}; + } + + void formatSerialNumber () + { + QFETCH (int, serialNumber); + QFETCH (QString, expected); + + QCOMPARE (Jtty::formatSerialNumber (serialNumber), expected); + } + + void jttyLineTimeLabel_data () + { + QTest::addColumn<QDateTime> ("diskDateTime"); + QTest::addColumn<qint32> ("utcDiskRaw"); + QTest::addColumn<float> ("tsyncSeconds"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("real-date-anchors-tsync") + << QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC} + << qint32 {194507} << 3.0f << QString {"194510"}; + QTest::newRow ("real-date-wraps-past-midnight") + << QDateTime {QDate {2026, 8, 28}, QTime {23, 59, 58}, Qt::UTC} + << qint32 {235958} << 5.0f << QString {"000003"}; + QTest::newRow ("subsecond-offset-preserves-current-second") + << QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC} + << qint32 {194507} << 0.6f << QString {"194507"}; + QTest::newRow ("dummy-date-falls-back-to-raw-digits") + << QDateTime {} << qint32 {2} << 0.0f << QString {"000002"}; + QTest::newRow ("dummy-date-fallback-still-anchors-tsync") + << QDateTime {} << qint32 {2} << 5.0f << QString {"000007"}; + QTest::newRow ("neither-anchor-usable") + << QDateTime {} << qint32 {999999} << 0.0f << QString {}; + } + + void jttyLineTimeLabel () + { + QFETCH (QDateTime, diskDateTime); + QFETCH (qint32, utcDiskRaw); + QFETCH (float, tsyncSeconds); + QFETCH (QString, expected); + + QCOMPARE (Jtty::jttyLineTimeLabel (diskDateTime, utcDiskRaw, tsyncSeconds), expected); + } + + void jttyLineStartTimeUtc () + { + QDateTime const diskDateTime {QDate {2026, 8, 28}, QTime {23, 59, 58}, Qt::UTC}; + QDateTime const expectedMidnight {QDate {2026, 8, 29}, QTime {0, 0, 3}, Qt::UTC}; + QDateTime const expectedFallback {QDate {2000, 1, 1}, QTime {0, 0, 7}, Qt::UTC}; + QCOMPARE (Jtty::jttyLineStartTimeUtc (diskDateTime, 235958, 5.0f), expectedMidnight); + QCOMPARE (Jtty::jttyLineStartTimeUtc (QDateTime {}, 2, 5.0f), expectedFallback); + QVERIFY (!Jtty::jttyLineStartTimeUtc (QDateTime {}, 999999, 0.0f).isValid ()); + } + + void jttyLineTimeLabelForStoredTimestamp () + { + QCOMPARE (Jtty::jttyLineTimeLabel ( + QDateTime {QDate {2026, 8, 28}, QTime {19, 45, 7}, Qt::UTC}), + QString {"194507"}); + QCOMPARE (Jtty::jttyLineTimeLabel (QDateTime {}), QString {}); + } + + void parseDecodeLine_data () + { + QTest::addColumn<QString> ("line"); + QTest::addColumn<int> ("frequency"); + QTest::addColumn<QString> ("message"); + QTest::addColumn<bool> ("valid"); + + QTest::newRow ("four-digit-frequency") + << QString {"1500 CQ K1ABC"} << 1500 << QString {"CQ K1ABC"} << true; + QTest::newRow ("three-digit-frequency-with-padding") + << QString {" 500 599 K1ABC "} << 500 << QString {"599 K1ABC"} << true; + QTest::newRow ("numeric-leading-message-is-preserved") + << QString {"1500 599 K1ABC"} << 1500 << QString {"599 K1ABC"} << true; + QTest::newRow ("frequency-only") + << QString {"1500"} << 1500 << QString {} << true; + QTest::newRow ("malformed-frequency") + << QString {"CQ K1ABC"} << 0 << QString {"CQ K1ABC"} << false; + QTest::newRow ("empty") + << QString {} << 0 << QString {} << false; + } + + void parseDecodeLine () + { + QFETCH (QString, line); + QFETCH (int, frequency); + QFETCH (QString, message); + QFETCH (bool, valid); + + auto const decoded = Jtty::parseDecodeLine (line); + + QCOMPARE (decoded.frequency, frequency); + QCOMPARE (decoded.message, message); + QCOMPARE (decoded.valid, valid); + } + + void wrapMessage_data () + { + QTest::addColumn<QString> ("text"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("short-unchanged") << QString {"HELLO"} << QString {"HELLO"}; + QTest::newRow ("exactly-40-unchanged") + << QString (40, QLatin1Char {'A'}) << QString (40, QLatin1Char {'A'}); + QTest::newRow ("joes-example") + << QString {"MAYBE CLAUDE COULD HELP US MAKE THE 3 MIN TRANSITION SEAMLESS"} + << QString {"MAYBE CLAUDE COULD HELP US MAKE THE 3\n MIN TRANSITION SEAMLESS"}; + QTest::newRow ("break-at-boundary") + << (QString (39, QLatin1Char {'A'}) + QString {" B"}) + << (QString (39, QLatin1Char {'A'}) + QString {"\n B"}); + QTest::newRow ("hard-break-no-blank") + << QString (50, QLatin1Char {'A'}) + << (QString (40, QLatin1Char {'A'}) + QString {"\n "} + + QString (10, QLatin1Char {'A'})); + QTest::newRow ("leading-space-does-not-create-empty-line") + << (QString {" "} + QString (79, QLatin1Char {'A'})) + << (QString {" "} + QString (39, QLatin1Char {'A'}) + QString {"\n "} + + QString (40, QLatin1Char {'A'})); + QTest::newRow ("multiple-wrap-points") + << QString {"AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC DDDDDDDDDD EEEEEEEEEE FFFFFFFFFF GGGGGGGGGG"} + << QString {"AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC\n DDDDDDDDDD EEEEEEEEEE FFFFFFFFFF\n GGGGGGGGGG"}; + } + + void wrapMessage () + { + QFETCH (QString, text); + QFETCH (QString, expected); + + QCOMPARE (Jtty::wrapMessage (text), expected); + } + + void compareMessagesTracksMessageSemantics () + { + auto const unchanged = Jtty::compareMessages ( + QStringLiteral ("CQ K1ABC"), QStringLiteral ("CQ K1ABC")); + QVERIFY (!unchanged.messageChanged); + QVERIFY (!unchanged.extendsMessage); + QVERIFY (!unchanged.startsMessage); + QVERIFY (unchanged.appendedText.isEmpty ()); + + auto const growth = Jtty::compareMessages ( + QStringLiteral ("CQ K1"), QStringLiteral ("CQ K1ABC")); + QVERIFY (growth.messageChanged); + QVERIFY (growth.extendsMessage); + QVERIFY (!growth.startsMessage); + QCOMPARE (growth.appendedText, QStringLiteral ("ABC")); + + auto const replacement = Jtty::compareMessages ( + QStringLiteral ("FIRST"), QStringLiteral ("SECOND")); + QVERIFY (replacement.messageChanged); + QVERIFY (!replacement.extendsMessage); + QVERIFY (!replacement.startsMessage); + QVERIFY (replacement.appendedText.isEmpty ()); + + auto const textAfterEmptyFrame = Jtty::compareMessages ( + QString {}, QStringLiteral ("ABC")); + QVERIFY (textAfterEmptyFrame.messageChanged); + QVERIFY (textAfterEmptyFrame.extendsMessage); + QVERIFY (textAfterEmptyFrame.startsMessage); + QCOMPARE (textAfterEmptyFrame.appendedText, QStringLiteral ("ABC")); + } + + void messageUpdatesDoNotRemoveHistory () + { + QVector<Jtty::MessageUpdate> history { + {1, 1000.f, QStringLiteral ("FIRST"), 1.f, false}, + {2, 1100.f, QStringLiteral ("SECOND"), 2.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {2, 1100.f, QStringLiteral ("SECOND"), 2.f, false}, + }; + + QVERIFY (!Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 2); + QCOMPARE (history.at (0).messageId, qint64 {1}); + QCOMPARE (history.at (1).messageId, qint64 {2}); + } + + void messageUpdatesReplaceSameId () + { + QVector<Jtty::MessageUpdate> history { + {8, 1400.f, QStringLiteral ("CQ K1"), 3.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {8, 1401.f, QStringLiteral ("CQ K1ABC"), 3.f, true}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 1); + QCOMPARE (history.at (0).frequency, 1401.f); + QCOMPARE (history.at (0).text, QStringLiteral ("CQ K1ABC")); + QVERIFY (history.at (0).complete); + } + + void messageUpdatesPreserveCompletionAndInitialStart () + { + QVector<Jtty::MessageUpdate> history { + {12, 1600.f, QStringLiteral ("TEST"), 4.f, true}, + }; + QVector<Jtty::MessageUpdate> updates { + {12, 1600.f, QStringLiteral ("TEST"), 9.f, false}, + }; + + QVERIFY (!Jtty::mergeMessageUpdates (history, updates)); + QVERIFY (history.at (0).complete); + QCOMPARE (history.at (0).sequenceStart, 4.f); + } + + void messageUpdatesDistinguishIdenticalTextById () + { + QVector<Jtty::MessageUpdate> history { + {qint64 {1} << 35, 1600.f, QStringLiteral ("TEST"), 1.f, false}, + }; + QVector<Jtty::MessageUpdate> updates { + {(qint64 {1} << 35) + 1, 1600.f, QStringLiteral ("TEST"), 2.f, false}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 2); + QVERIFY (history.at (0).messageId != history.at (1).messageId); + QCOMPARE (history.at (0).text, history.at (1).text); + } + + void messageUpdatesOrderByStartTimeThenId () + { + QVector<Jtty::MessageUpdate> history; + QVector<Jtty::MessageUpdate> updates { + {9, 1000.f, QStringLiteral ("FOURTH"), 5.f, false}, + {4, 2000.f, QStringLiteral ("FIRST"), 1.f, false}, + {7, 900.f, QStringLiteral ("THIRD"), 3.f, false}, + {2, 1800.f, QStringLiteral ("SECOND"), 3.f, false}, + }; + + QVERIFY (Jtty::mergeMessageUpdates (history, updates)); + QCOMPARE (history.size (), 4); + QCOMPARE (history.at (0).messageId, qint64 {4}); + QCOMPARE (history.at (1).messageId, qint64 {2}); + QCOMPARE (history.at (2).messageId, qint64 {7}); + QCOMPARE (history.at (3).messageId, qint64 {9}); + } + + void qsoHistoryRetainsAdmittedMessageAcrossDrift () + { + QVERIFY (Jtty::shouldApplyToQsoHistory (false, 1504.f, 1500.f, 5.f)); + QVERIFY (!Jtty::shouldApplyToQsoHistory (false, 1505.f, 1500.f, 5.f)); + QVERIFY (Jtty::shouldApplyToQsoHistory (true, 1510.f, 1500.f, 5.f)); + } +}; + +QTEST_MAIN (TestJttyMessages) +#include "test_jtty_messages.moc" diff --git a/tests/unit/jtty/test_jtty_n1mm.cpp b/tests/unit/jtty/test_jtty_n1mm.cpp new file mode 100644 index 00000000..7f2f167f --- /dev/null +++ b/tests/unit/jtty/test_jtty_n1mm.cpp @@ -0,0 +1,245 @@ +#include <QtTest> + +#include "widgets/JttyN1mm.hpp" +#include "widgets/JttyN1mmOutput.hpp" + +class TestJttyN1mm final : public QObject +{ + Q_OBJECT + + using Kind = Jtty::NativeAtomKind; + using Profile = Jtty::NativeExchangeProfile; + using Status = Jtty::N1mmCompileStatus; + +private slots: + void rejectedOutputCompletesOnceAtOff () + { + Jtty::N1mmOutput output; + output.submit (1); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (false, true)); + output.start (); + output.finish (); + QVERIFY (output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (false, true)); + output.finish (); + QVERIFY (!output.finishRequested ()); + } + + void mixedOutputWaitsForAcceptedAudio () + { + Jtty::N1mmOutput output; + output.start (); + output.submit (1); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (output.startRequested ()); + output.submit (2); + output.finish (); + QVERIFY (output.startRequested ()); + QVERIFY (!output.takeCompletion (false)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.accept (2)); + output.started (); + QVERIFY (output.resolve (2)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.takeCompletion (false, true)); + } + + void asynchronousRejectionAfterOffCompletesWithoutDrain () + { + Jtty::N1mmOutput output; + output.start (); + output.submit (1); + output.finish (); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.resolve (1)); + QVERIFY (!output.takeCompletion (true)); + QVERIFY (output.takeCompletion (false)); + } + + void drainBeforeOffAndAbortDoNotDuplicateCompletion () + { + Jtty::N1mmOutput output; + output.submit (1); + output.start (); + QVERIFY (output.accept (1)); + QVERIFY (output.resolve (1)); + QVERIFY (output.takeCompletion (false, true)); + output.finish (); + QVERIFY (!output.takeCompletion (false)); + output.submit (2); + output.abort (); + QVERIFY (!output.resolve (2)); + output.finish (); + QVERIFY (!output.takeCompletion (false, true)); + } + + void everyActionCompiles () + { + struct Example + { + QString message; + Profile profile; + QString canonical; + QVector<Kind> kinds; + }; + QVector<Example> const examples { + {"[[JTTY:CQ]] K1ABC", Profile::None, "CQ K1ABC CQ", {Kind::Call}}, + {"[[JTTY:CALL_EXCH]] W9XYZ 7", Profile::None, "W9XYZ 599 007", + {Kind::Call, Kind::ExchangeNumber}}, + {"[[JTTY:CALL_TU_CQ]] W9XYZ K1ABC", Profile::None, "W9XYZ TU CQ K1ABC CQ", + {Kind::Call, Kind::Call}}, + {"[[JTTY:MYCALL]] K1ABC", Profile::None, "K1ABC", {Kind::Call}}, + {"[[JTTY:HISCALL]] W9XYZ", Profile::None, "W9XYZ", {Kind::Call}}, + {"[[JTTY:TU_NOW_EXCH]] W9XYZ 42", Profile::None, "TU NOW W9XYZ 599 042", + {Kind::Call, Kind::ExchangeNumber}}, + {"[[JTTY:CALL_MY]] W9XYZ K1ABC", Profile::None, "W9XYZ K1ABC", + {Kind::Call, Kind::Call}}, + {"[[JTTY:CALL_TU_MY]] W9XYZ K1ABC", Profile::None, "W9XYZ TU K1ABC", + {Kind::Call, Kind::Call}}, + {"[[JTTY:EXCH]] 1D EMA", Profile::FieldDay, "1D EMA", {Kind::ExchangePair}}, + {"[[JTTY:GRID]] fn42", Profile::None, "FN42", {Kind::Grid4}}, + {"[[JTTY:CONTROL]] qsl tu", Profile::None, "QSL TU", {Kind::Control}} + }; + + for (auto const& example : examples) { + auto const result = Jtty::compileN1mmMessage (example.message, example.profile); + QCOMPARE (result.status, Status::Native); + QCOMPARE (result.canonicalText, example.canonical); + QCOMPARE (result.atoms.size (), example.kinds.size ()); + for (int i = 0; i < result.atoms.size (); ++i) { + QCOMPARE (int {result.atoms.at (i).kind}, static_cast<int> (example.kinds.at (i))); + } + } + } + + void tagMatchingIsCaseAndWhitespaceNormalized () + { + auto const result = Jtty::compileN1mmMessage ( + QStringLiteral (" \t[[jtty:call_tu_cq]] w9xyz\n k1abc ")); + QCOMPARE (result.status, Status::Native); + QCOMPARE (result.canonicalText, QStringLiteral ("W9XYZ TU CQ K1ABC CQ")); + } + + void tagClassification () + { + QString const literal = QStringLiteral (" W9XYZ 599 007"); + auto const untagged = Jtty::compileN1mmMessage (literal); + QCOMPARE (untagged.status, Status::Literal); + QCOMPARE (untagged.literalText, literal); + QVERIFY (untagged.atoms.isEmpty ()); + + auto const notFirst = Jtty::compileN1mmMessage ( + QStringLiteral ("CQ [[JTTY:CQ]] K1ABC")); + QCOMPARE (notFirst.status, Status::Literal); + + auto const malformed = Jtty::compileN1mmMessage ( + QStringLiteral (" [[JTTY:CQ K1ABC")); + QCOMPARE (malformed.status, Status::Error); + QVERIFY (!malformed.error.isEmpty ()); + + auto const malformedStem = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY]] K1ABC")); + QCOMPARE (malformedStem.status, Status::Error); + QVERIFY (!malformedStem.error.isEmpty ()); + + auto const unknown = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:MAGIC]] K1ABC")); + QCOMPARE (unknown.status, Status::Error); + QVERIFY (unknown.error.contains (QStringLiteral ("unknown"))); + } + + void profileDrivenExchange () + { + auto const serial = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 00042"), Profile::RttyRoundup); + QCOMPARE (serial.status, Status::Native); + QCOMPARE (serial.canonicalText, QStringLiteral ("599 042")); + QCOMPARE (int {serial.atoms.first ().kind}, static_cast<int> (Kind::ExchangeNumber)); + QCOMPARE (serial.atoms.first ().value, qint32 {42}); + + auto const state = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ az"), Profile::RttyRoundup); + QCOMPARE (state.status, Status::Native); + QCOMPARE (state.canonicalText, QStringLiteral ("W9XYZ 599 AZ")); + QCOMPARE (int {state.atoms.last ().kind}, static_cast<int> (Kind::ExchangeLocation)); + QCOMPARE (int {state.atoms.last ().subtype}, + static_cast<int> (Jtty::LocationKind::StateProvince)); + + auto const dx = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] DX"), Profile::RttyRoundup); + QCOMPARE (dx.status, Status::Native); + QCOMPARE (dx.canonicalText, QStringLiteral ("599 DX")); + QCOMPARE (int {dx.atoms.first ().kind}, static_cast<int> (Kind::ExchangeLocation)); + + auto const fieldDay = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 32f ema"), Profile::FieldDay); + QCOMPARE (fieldDay.status, Status::Native); + QCOMPARE (fieldDay.canonicalText, QStringLiteral ("32F EMA")); + QCOMPARE (fieldDay.atoms.first ().value, qint32 {32}); + QCOMPARE (int {fieldDay.atoms.first ().role}, 5); + QCOMPARE (QString::fromLatin1 (fieldDay.atoms.first ().text), QStringLiteral ("EMA")); + } + + void payloadValidation_data () + { + QTest::addColumn<QString> ("message"); + QTest::addColumn<int> ("profile"); + + QTest::newRow ("empty") << QStringLiteral ("[[JTTY:CQ]]") << int (Profile::None); + QTest::newRow ("cq-extra") << QStringLiteral ("[[JTTY:CQ]] K1ABC CQ") + << int (Profile::None); + QTest::newRow ("bad-call") << QStringLiteral ("[[JTTY:HISCALL]] NOTACALL") + << int (Profile::None); + QTest::newRow ("call-extra") << QStringLiteral ("[[JTTY:MYCALL]] K1ABC EXTRA") + << int (Profile::None); + QTest::newRow ("missing-exchange") << QStringLiteral ("[[JTTY:CALL_EXCH]] W9XYZ") + << int (Profile::None); + QTest::newRow ("serial-junk") << QStringLiteral ("[[JTTY:EXCH]] 12A") + << int (Profile::None); + QTest::newRow ("serial-overflow") << QStringLiteral ("[[JTTY:EXCH]] 131072") + << int (Profile::RttyRoundup); + QTest::newRow ("unexpanded-hash") << QStringLiteral ("[[JTTY:EXCH]] #") + << int (Profile::RttyRoundup); + QTest::newRow ("field-day-shape") << QStringLiteral ("[[JTTY:EXCH]] 1D") + << int (Profile::FieldDay); + QTest::newRow ("field-day-compact") << QStringLiteral ("[[JTTY:EXCH]] 3AOR") + << int (Profile::FieldDay); + QTest::newRow ("field-day-count") << QStringLiteral ("[[JTTY:EXCH]] 33A EMA") + << int (Profile::FieldDay); + QTest::newRow ("grid-extra") << QStringLiteral ("[[JTTY:GRID]] 599 FN42") + << int (Profile::None); + QTest::newRow ("grid-field") << QStringLiteral ("[[JTTY:GRID]] SA00") + << int (Profile::None); + QTest::newRow ("grid-digit") << QStringLiteral ("[[JTTY:GRID]] FN4A") + << int (Profile::None); + QTest::newRow ("control") << QStringLiteral ("[[JTTY:CONTROL]] THANKS") + << int (Profile::None); + } + + void payloadValidation () + { + QFETCH (QString, message); + QFETCH (int, profile); + auto const result = Jtty::compileN1mmMessage ( + message, static_cast<Profile> (profile)); + QCOMPARE (result.status, Status::Error); + QVERIFY (!result.error.isEmpty ()); + QVERIFY (result.atoms.isEmpty ()); + } + + void contextOverloadUsesSelectedProfile () + { + Jtty::NativeMacroContext context; + context.exchangeProfile = Profile::FieldDay; + auto const result = Jtty::compileN1mmMessage ( + QStringLiteral ("[[JTTY:EXCH]] 1D EMA"), context); + QCOMPARE (result.status, Status::Native); + QCOMPARE (int {result.atoms.first ().kind}, static_cast<int> (Kind::ExchangePair)); + } +}; + +QTEST_GUILESS_MAIN (TestJttyN1mm) +#include "test_jtty_n1mm.moc" diff --git a/tests/unit/jtty/test_jtty_overlap_decode.f90 b/tests/unit/jtty/test_jtty_overlap_decode.f90 new file mode 100644 index 00000000..b440d1f3 --- /dev/null +++ b/tests/unit/jtty/test_jtty_overlap_decode.f90 @@ -0,0 +1,202 @@ +program test_jtty_overlap_decode + + ! Overlap two generated JTTY transmissions and decode them through + ! rjtty_sub. This is a stand-in for the private W2PU on-air corpus. + ! + ! The 4 Hz case reproduces leftover extra-slot fragments: a real next + ! frame lands just outside the 3 Hz continuation gate and opens a new + ! message instead of staying on its assembly. Isolated and 2 Hz cases are + ! controls that already pass. + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg_a='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: msg_b='CLAUDE CO 3 MIN TRANSITION' + integer :: failures,nsps + character(len=16) :: rate_arg + integer :: failures_before_overlap + + nsps=384 + call get_command_argument(1,rate_arg) + if(len_trim(rate_arg).gt.0) read(rate_arg,*) nsps + failures=0 + + call expect_complete_pair('isolated first message',msg_a,1500.0,0.2, & + '',1500.0,0.6,1,failures) + call expect_complete_pair('isolated second message','',1500.0,0.2, & + msg_b,1504.0,0.6,1,failures) + call expect_complete_pair('2 Hz overlap stays two complete messages', & + msg_a,1500.0,0.2,msg_b,1502.0,0.6,2,failures) + + failures_before_overlap=failures + call expect_complete_pair('4 Hz overlap stays two complete messages', & + msg_a,1500.0,0.2,msg_b,1504.0,0.6,2,failures) + if(failures.gt.failures_before_overlap) then + write(*,'(a)') '4 Hz overlap messages: '//trim(message_summary()) + endif + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_overlap_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_overlap_decode: all checks passed' + +contains + + subroutine expect_complete_pair(description,first_message,first_hz, & + first_dt,second_message,second_hz,second_dt,expected_messages,count) + character(len=*), intent(in) :: description,first_message,second_message + real, intent(in) :: first_hz,first_dt,second_hz,second_dt + integer, intent(in) :: expected_messages + integer, intent(inout) :: count + logical :: found_a,found_b + + call decode_overlap(first_message,first_hz,first_dt,second_message, & + second_hz,second_dt,50.0) + call message_coverage(first_message,second_message,found_a,found_b) + call expect(npending.eq.expected_messages,description//': message count',count) + if(len_trim(first_message).gt.0) then + call expect(found_a,description//': first message complete',count) + endif + if(len_trim(second_message).gt.0) then + call expect(found_b,description//': second message complete',count) + endif + end subroutine expect_complete_pair + + subroutine decode_overlap(first_message,first_hz,first_dt,second_message, & + second_hz,second_dt,ftol) + character(len=*), intent(in) :: first_message,second_message + real, intent(in) :: first_hz,first_dt,second_hz,second_dt,ftol + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols + integer :: first_samples,second_samples,first_start,second_start + integer :: total_samples,i,idx + integer :: first_pcm,second_pcm,mixed + integer(int16), allocatable :: pcm(:) + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + call discard_pending_updates() + first_symbols=0 + second_symbols=0 + first_samples=0 + second_samples=0 + first_start=1 + second_start=1 + + if(len_trim(first_message).gt.0) then + first_input=first_message + call genjtty(first_input,first_tones,first_symbols) + first_samples=first_symbols*nsps + first_start=max(1,nint(first_dt*12000.0)+1) + endif + if(len_trim(second_message).gt.0) then + second_input=second_message + call genjtty(second_input,second_tones,second_symbols) + second_samples=second_symbols*nsps + second_start=max(1,nint(second_dt*12000.0)+1) + endif + + total_samples=max(first_start+first_samples-1, & + second_start+second_samples-1)+frame_symbols*nsps + allocate(pcm(total_samples)) + pcm=0_int16 + + if(first_samples.gt.0) then + allocate(first_wave(first_samples),complex_wave(first_samples)) + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,first_hz, & + complex_wave,first_wave,0,first_samples) + do i=1,first_samples + idx=first_start+i-1 + first_pcm=nint(14000.0*first_wave(i)) + pcm(idx)=int(max(-32767,min(32767,first_pcm)),int16) + enddo + deallocate(first_wave,complex_wave) + endif + + if(second_samples.gt.0) then + allocate(second_wave(second_samples),complex_wave(second_samples)) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0, & + second_hz,complex_wave,second_wave,0,second_samples) + do i=1,second_samples + idx=second_start+i-1 + second_pcm=nint(14000.0*second_wave(i)) + mixed=int(pcm(idx))+second_pcm + pcm(idx)=int(max(-32767,min(32767,mixed)),int16) + enddo + deallocate(second_wave,complex_wave) + endif + + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,ftol) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,ftol) + deallocate(pcm) + end subroutine decode_overlap + + subroutine message_coverage(first_message,second_message,found_a,found_b) + character(len=*), intent(in) :: first_message,second_message + logical, intent(out) :: found_a,found_b + integer :: i + + found_a=len_trim(first_message).eq.0 + found_b=len_trim(second_message).eq.0 + do i=1,npending + if(len_trim(first_message).gt.0) then + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(first_message)) & + found_a=.true. + endif + if(len_trim(second_message).gt.0) then + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(second_message)) & + found_b=.true. + endif + enddo + end subroutine message_coverage + + function message_summary() result(text) + character(len=240) :: text + character(len=80) :: body + integer :: i,pos + + text='' + pos=1 + do i=1,npending + body=normalized(pending_updates(i)%decoded) + if(pos.gt.1) then + text(pos:pos)='|' + pos=pos+1 + endif + text(pos:pos+len_trim(body)-1)=trim(body) + pos=pos+len_trim(body) + if(pos.ge.len(text)-1) exit + enddo + end function message_summary + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_overlap_decode diff --git a/tests/unit/jtty/test_jtty_pack.f90 b/tests/unit/jtty/test_jtty_pack.f90 new file mode 100644 index 00000000..31541cfb --- /dev/null +++ b/tests/unit/jtty/test_jtty_pack.f90 @@ -0,0 +1,460 @@ +program test_jtty_pack + + use jtty_mod + use packjt77, only: pack28 + character*80 msg0,msg,expected + character*34 c32(MAX_FRAMES) + character*17 cparms + character*1 err + integer, parameter :: expected_errors = 0 + + open(10,file='jtty_msgs.txt',status='old') + write(*,1000) +1000 format('i2.n2 i2.n2 NC NF err Message'/87('-')) + nerr=0 + nz=0 + c32='' + do imsg=1,99 + read(10,'(a80)',end=100) msg0 + call normalize_jtty_message(msg0,expected) + nlength=len_trim(expected) + if(nlength.eq.0) then + write(*,*) + cycle + endif + nz=nz+1 + call pack_jtty(msg0,c32,nframes) + if(nframes.lt.0) then + err='*' + nerr=nerr+1 + cycle + endif + call expect_no_reserved_frame_ids(c32,nframes,msg0) + call unpack_jtty(c32,nframes,msg) + call display_jtty_message(msg) + err=' ' + if(msg.ne.expected) then + err='*' + nerr=nerr+1 + write(12,1010) trim(expected),trim(msg) +1010 format(a/a) + endif + read(c32(1),1012) n2a,i2a + read(c32(2),1012) n2b,i2b +1012 format(28x,2b2) + write(cparms,1018) i2a,n2a,i2b,n2b,nlength,nframes +1018 format(i2,'.',i1,2x,i2,'.',i1,i4,i3) + if(i2a.ge.2) cparms(3:4)=' ' + if(i2b.ge.2) cparms(9:10)=' ' + if(nframes.eq.1) cparms(7:10)=' ' + write(*,1020) cparms,err,trim(msg) +1020 format(a17,2x,a1,2x,a) + enddo + +100 write(*,1100) nz,nerr +1100 format(/'Total messages:',i3,' Number of errors:',i3) + if(nerr.ne.expected_errors) error stop 1 + + call expect_pack('CQ KA1ABC CQ',1,0,0,-1,-1) + call expect_pack('CQ K1ABC CQ',1,0,0,-1,-1) + call expect_pack('K1A',1,0,1,-1,-1) + call expect_pack('WB9XYZ',1,0,1,-1,-1) + call expect_pack('TU WB9XYZ CQ',1,0,2,-1,-1) + call expect_pack('WB9XYZ TU',1,0,3,-1,-1) + call expect_pack('WB9XYZ AGN?',1,1,0,-1,-1) + call expect_pack('TU NOW WB9XYZ',1,1,1,-1,-1) + call expect_pack('WB9XYZ TU CQ KA1ABC CQ',2,0,3,0,0) + call expect_pack('K1ABC TU NOW W1XYZ',2,0,1,1,1) + call expect_pack('WB9XYZ 599 123',2,0,1,2,-1) + call expect_pack('599 MA',1,2,-1,-1,-1) + call expect_pack('599 FN42',1,2,-1,-1,-1) + call expect_pack('FN42',1,2,-1,-1,-1) + call expect_pack('1D EMA',1,2,-1,-1,-1) + call expect_pack('32F EMA',1,2,-1,-1,-1) + call expect_pack('0',1,2,-1,-1,-1) + call expect_pack('131071',1,2,-1,-1,-1) + call expect_pack('599 131071',1,2,-1,-1,-1) + call expect_pack('599 001',2,-1,-1,-1,-1) + call expect_pack('599 05',2,-1,-1,-1,-1) + call expect_pack('599 BRUCE',2,-1,-1,-1,-1) + call expect_pack('131072',2,3,-1,3,-1) + call expect_pack('000001',2,3,-1,3,-1) + call expect_pack('01D EMA',2,3,-1,3,-1) + call expect_pack('33D EMA',2,3,-1,3,-1) + call expect_pack('1G EMA',2,3,-1,3,-1) + call expect_pack('1D ZZZ',2,3,-1,3,-1) + call expect_pack('599 SA00',2,-1,-1,-1,-1) + call expect_pack('599 A!',2,-1,-1,-1,-1) + call expect_pack('599 XYZ',1,2,-1,-1,-1) + call expect_pack('599 0AB',2,-1,-1,-1,-1) + call expect_pack('CQ K1ABC CQ!',3,-1,-1,-1,-1) + call expect_pack('TEST WB9XYZ',2,3,-1,0,1) + call expect_pack('HI WB9XYZ',2,3,-1,3,-1) + call expect_pack('K1ABC HELLO',2,0,1,3,-1) + call expect_pack('TEST AGN NR',2,3,-1,2,-1) + call expect_pack(repeat('A',80),16,3,-1,3,-1) + call expect_pack('',0,-1,-1,-1,-1) + call expect_pack(' ',0,-1,-1,-1,-1) + call expect_pack('599 A',1,3,-1,-1,-1) + call expect_pack('599 BRUCE F',3,-1,-1,-1,-1) + call expect_pack('A599 MA',2,3,-1,3,-1) + call expect_pack('VP2/KF2GHI',2,3,-1,3,-1) + call expect_pack('VP2/KA1ABC',2,3,-1,3,-1) + call expect_pack('QU1RK',1,3,-1,-1,-1) + call expect_pack('TU QU1RKP CQ',3,2,-1,3,-1) + call expect_pack('WB9XYZABC',2,3,-1,3,-1) + call expect_pack('K1A A',1,3,-1,-1,-1) + call expect_pack('PSE AGN NR',2,-1,-1,-1,-1) + call expect_pack('AGN NR PSE',2,2,-1,3,-1) + call expect_control_phrase_literals() + call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_GENERIC,123)) + call expect_atom('123',jtty_exch_num_atom(JTTY_ROLE_FIELD_ONLY,JTTY_NUM_GENERIC,123)) + call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'MA')) + call expect_atom('599 FN42',jtty_grid4_atom(JTTY_ROLE_FULL,'FN42')) + call expect_exchange_profiles() + ! Normalization is part of the round-trip contract for operator input. + call expect_pack('cq ka1abc cq',1,0,0,-1,-1) + call expect_pack(' vp2/kf2ghi ',2,3,-1,3,-1) + call expect_pack('A'//char(0)//'B',1,3,-1,-1,-1) + call expect_pack('A~B',1,3,-1,-1,-1) + call expect_pack('HELLO~',1,3,-1,-1,-1) + call expect_pack('HELLO'//char(9)//'WORLD',3,3,-1,3,-1) + call expect_pack('HELLO'//char(10)//'WORLD',3,3,-1,3,-1) + call expect_pack('HELLO'//char(13)//'WORLD',3,3,-1,3,-1) + call expect_unassigned_unpack_empty(1,2) + call expect_unassigned_unpack_empty(1,3) + call expect_structured_unpack_boundary() + call expect_empty_waveform_guard() + call expect_last_frame_flag() + +contains + + subroutine expect_atom(text,atom,exchange_profile) + character(len=*), intent(in) :: text + type(jtty_source_atom), intent(in) :: atom + integer, intent(in), optional :: exchange_profile + character(len=80) :: input + character(len=34) :: frames(MAX_FRAMES),expected_frame + integer :: nframes + logical :: valid + + input=text + call pack_jtty(input,frames,nframes,exchange_profile) + call pack_jtty_atom(atom,expected_frame,.true.,valid) + if(.not.valid .or. nframes.ne.1 .or. frames(1).ne.expected_frame) then + write(*,'(a)') 'Unexpected inferred atom for "'//text//'"' + error stop 1 + endif + end subroutine expect_atom + + subroutine expect_exchange_profiles() + character(len=80), parameter :: examples(*)=[character(len=80) :: & + '599 001','K1ABC 599 001','599 05','599 0123','001','599 123', & + '599 MA','599 131071','599 0AB','1D EMA','CQ K1ABC CQ','K1A A'] + character(len=80) :: input,decoded + character(len=34) :: baseline(MAX_FRAMES),frames(MAX_FRAMES) + integer :: i,profile,baseline_nf,nframes + + call expect_pack('599 001',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('K1ABC 599 001',2,0,1,2,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('K1ABC 599 001',3,0,1,-1,-1,JTTY_EXCHANGE_UNKNOWN) + call expect_pack('599 05',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 005') + call expect_pack('599 0123',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 123') + call expect_pack('K1ABC 599 05 QSL TU',3,0,1,2,-1,JTTY_EXCHANGE_RTTY,'K1ABC 599 005 QSL TU') + call expect_pack('599 05 599 0123',2,2,-1,2,-1,JTTY_EXCHANGE_RTTY,'599 005 599 123') + call expect_pack('599 000005',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 005') + call expect_pack('599 0',1,2,-1,-1,-1,JTTY_EXCHANGE_RTTY,'599 000') + call expect_pack('599 0000005',3,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 131072',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05A',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('A599 05',2,3,-1,3,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05!',2,-1,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('05',1,3,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_pack('599 05',2,-1,-1,-1,-1,JTTY_EXCHANGE_FIELD_DAY) + call expect_pack(repeat('A',72)//' 599 05',16,3,-1,3,-1,JTTY_EXCHANGE_RTTY, & + repeat('A',72)//' 599 005') + call expect_pack(repeat('A',64)//' 599 05 599 0123',15,3,-1,3,-1,JTTY_EXCHANGE_RTTY, & + repeat('A',64)//' 599 005 599 123') + call expect_pack('001',1,3,-1,-1,-1,JTTY_EXCHANGE_RTTY) + call expect_atom('599 001',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1),JTTY_EXCHANGE_RTTY) + call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,123),JTTY_EXCHANGE_RTTY) + call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_STATE_PROVINCE,'MA'),JTTY_EXCHANGE_RTTY) + call expect_atom('123',jtty_exch_num_atom(JTTY_ROLE_FIELD_ONLY,JTTY_NUM_GENERIC,123),JTTY_EXCHANGE_RTTY) + call expect_atom('599 123',jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_GENERIC,123),JTTY_EXCHANGE_FIELD_DAY) + call expect_atom('599 MA',jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'MA'),JTTY_EXCHANGE_FIELD_DAY) + + do i=1,size(examples) + input=examples(i) + call pack_jtty(input,baseline,baseline_nf) + do profile=JTTY_EXCHANGE_UNKNOWN,JTTY_EXCHANGE_RTTY + input=examples(i) + call pack_jtty(input,frames,nframes,profile) + if(nframes.lt.1 .or. nframes.gt.baseline_nf) error stop 'Profile worsened frame count' + if(profile.ne.JTTY_EXCHANGE_RTTY) then + if(nframes.ne.baseline_nf .or. any(frames.ne.baseline)) error stop 'Unexpected non-RTTY inference' + endif + call unpack_jtty(frames,nframes,decoded) + call display_jtty_message(decoded) + if(decoded.ne.input) error stop 'Profile changed rendered text' + enddo + input=examples(i) + call pack_jtty(input,frames,nframes) + if(nframes.ne.baseline_nf .or. any(frames.ne.baseline)) error stop 'Profile leaked between calls' + enddo + input='599 001' + call pack_jtty(input,frames,nframes,-1) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted invalid negative profile' + call pack_jtty(input,frames,nframes,JTTY_EXCHANGE_RTTY+1) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted unknown profile' + input=repeat('A',73)//' 599 05' + call pack_jtty(input,frames,nframes,JTTY_EXCHANGE_RTTY) + if(nframes.ne.-1 .or. any(frames.ne.'')) error stop 'Accepted canonical text exceeding 80 characters' + end subroutine expect_exchange_profiles + + subroutine expect_control_phrase_literals() + type(jtty_source_atom) atom + character*80 input,decoded,expected + character*34 frame,frames(MAX_FRAMES) + integer phrase_id,got_nf + logical valid,eom + + do phrase_id=lbound(CONTROL_TEXT,1),ubound(CONTROL_TEXT,1) + input='' + if(phrase_id.eq.JTTY_CONTROL_AGN_NR) then + input=' agn nr ' + else + input=trim(CONTROL_TEXT(phrase_id)) + endif + call normalize_jtty_message(input,expected) + call pack_jtty(input,frames,got_nf) + if(got_nf.ne.1) then + write(*,1030) trim(expected),got_nf +1030 format('Control phrase "',a,'" encoded in ',i0,' frames') + error stop 1 + endif + frame=frames(1) + call unpack_jtty_atom(frame,atom,valid,eom) + if(.not.valid .or. .not.eom .or. atom%kind.ne.JTTY_ATOM_CONTROL .or. & + atom%subtype.ne.phrase_id .or. frames(1)(33:33).ne.'0') then + write(*,1040) trim(expected),phrase_id +1040 format('Control phrase "',a,'" did not encode as CONTROL ',i0) + error stop 1 + endif + call unpack_jtty(frames,got_nf,decoded) + call display_jtty_message(decoded) + if(decoded.ne.expected) then + write(*,1050) trim(expected),trim(decoded) +1050 format('Control phrase "',a,'" decoded as "',a,'"') + error stop 1 + endif + enddo + end subroutine expect_control_phrase_literals + + subroutine display_jtty_message(text) + character*80 text + + do i=1,len_trim(text) + if(text(i:i).eq.'~') text(i:i)=' ' + enddo + end subroutine display_jtty_message + + subroutine expect_pack(text,want_nf,want_i2a,want_n2a,want_i2b,want_n2b,exchange_profile,canonical_text) + character*(*) text + character*80 input,decoded,want_decoded,part,incremental + character*34 frames(MAX_FRAMES),single(MAX_FRAMES) + integer want_nf,want_i2a,want_n2a,want_i2b,want_n2b + integer, intent(in), optional :: exchange_profile + character(len=*), intent(in), optional :: canonical_text + integer got_nf,got_i2a,got_n2a,got_i2b,got_n2b,iframe + logical trailing_sep,is_last,valid + + input='' + input=text + call normalize_jtty_message(input,want_decoded) + if(present(canonical_text)) want_decoded=canonical_text + frames='' + call pack_jtty(input,frames,got_nf,exchange_profile) + if(input.ne.want_decoded) error stop 'Returned message differs from canonical text' + if(got_nf.lt.0) then + write(*,1195) trim(input) +1195 format('Unexpected pack failure for "',a,'"') + error stop 1 + endif + call expect_no_reserved_frame_ids(frames,got_nf,input) + call unpack_jtty(frames,got_nf,decoded) + call display_jtty_message(decoded) + if(decoded.ne.want_decoded) then + write(*,1200) trim(want_decoded),trim(decoded) +1200 format('Round-trip failure for "',a,'"; decoded "',a,'"') + error stop 1 + endif + if(got_nf.ne.want_nf) then + write(*,1210) trim(input),want_nf,got_nf +1210 format('Frame-count failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + incremental='' + do iframe=1,got_nf + single='' + single(1)=frames(iframe) + call unpack_jtty(single,1,part,trailing_sep,is_last,valid) + if(.not.valid .or. (is_last.neqv.(iframe.eq.got_nf))) error stop 'Invalid incremental frame' + incremental=trim(incremental)//trim(part) + if(trailing_sep .and. iframe.lt.got_nf) incremental=trim(incremental)//'~' + if(frames(iframe)(33:33).ne.'0') error stop 'Nonzero reserved bit' + enddo + call display_jtty_message(incremental) + if(incremental.ne.want_decoded) error stop 'Incremental text differs from whole-message text' + if(got_nf.eq.0) return + read(frames(1),'(28x,2b2)') got_n2a,got_i2a + if(want_i2a.ge.0 .and. got_i2a.ne.want_i2a) then + write(*,1220) trim(input),want_i2a,got_i2a +1220 format('First-frame i2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_n2a.ge.0 .and. got_n2a.ne.want_n2a) then + write(*,1230) trim(input),want_n2a,got_n2a +1230 format('First-frame n2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_i2b.ge.0) then + read(frames(2),'(28x,2b2)') got_n2b,got_i2b + if(got_i2b.ne.want_i2b) then + write(*,1240) trim(input),want_i2b,got_i2b +1240 format('Second-frame i2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + if(want_n2b.ge.0 .and. got_n2b.ne.want_n2b) then + write(*,1250) trim(input),want_n2b,got_n2b +1250 format('Second-frame n2 failure for "',a,'"; wanted ',i0,' got ',i0) + error stop 1 + endif + endif + end subroutine expect_pack + + subroutine expect_no_reserved_frame_ids(frames,nframes,input) + character*34 frames(MAX_FRAMES) + character*(*) input + integer nframes, iframe, got_i2, got_n2 + + do iframe=1,nframes + read(frames(iframe),'(28x,2b2)') got_n2, got_i2 + if(got_i2.eq.1 .and. got_n2.ge.2) then + write(*,1260) trim(input),iframe,got_i2,got_n2 +1260 format('Reserved frame id for "',a,'" frame ',i0,': ',i0,'.',i0) + error stop 1 + endif + enddo + end subroutine expect_no_reserved_frame_ids + + subroutine expect_unassigned_unpack_empty(i2,n2) + character*34 frames(MAX_FRAMES) + character*80 decoded + character*13 c13 + integer i2,n2,n28,n32 + + frames='' + c13='K1ABC ' + call pack28(c13,n28) + n32=shiftl(n28,4) + 4*n2 + i2 + write(frames(1),'(b32.32,a2)') n32,'00' + call unpack_jtty(frames,1,decoded) + if(len_trim(decoded).ne.0) then + write(*,1280) i2,n2,trim(decoded) +1280 format('Unassigned frame ',i0,'.',i0,' decoded unexpectedly as "',a,'"') + error stop 1 + endif + end subroutine expect_unassigned_unpack_empty + + subroutine expect_structured_unpack_boundary() + character*34 frames(MAX_FRAMES) + character*80 decoded,expected + character*13 c13 + integer iframe,n28,n32,n30 + + ! A long structured append that straddles column 80 must be truncated exactly. + frames='' + n30=0 + do i=1,5 + n30=64*n30 + jchar('A') + enddo + n32=ishft(n30,2) + 3 + do iframe=1,14 + write(frames(iframe),'(b32.32,a2)') n32,'00' + enddo + c13='KA1ABC ' + call pack28(c13,n28) + n32=shiftl(n28,4) + 4*1 + 1 + write(frames(15),'(b32.32,a2)') n32,'00' + + expected='' + do i=1,70 + expected(i:i)='A' + enddo + expected(71:80)='TU NOW KA1' + call unpack_jtty(frames,15,decoded) + if(len_trim(decoded).ne.80 .or. decoded.ne.expected) then + write(*,1300) len_trim(decoded),trim(decoded) +1300 format('Structured-boundary unpack test decoded length ',i0,' as "',a,'"') + error stop 1 + endif + end subroutine expect_structured_unpack_boundary + + subroutine expect_empty_waveform_guard() + integer, parameter :: TEST_NSPS=4*384 + integer tones(1) + integer nsym, nsps, icmplx, nwave + real bt, fsample, f0 + real wave(TEST_NSPS) + complex cwave(TEST_NSPS) + + tones=0 + nsym=0 + nsps=TEST_NSPS + bt=2.0 + fsample=48000.0 + f0=1500.0 + icmplx=0 + nwave=nsps + + call gen_jttywave(tones,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave) + if(nwave.ne.0) then + write(*,1310) nwave +1310 format('Empty waveform guard returned nwave ',i0) + error stop 1 + endif + end subroutine expect_empty_waveform_guard + + subroutine expect_last_frame_flag() + ! Bit 34 of each 34-bit frame word must be 0 on every frame except the + ! last, and 1 on the last frame of a multi-frame message -- matching how + ! the real decode drivers call unpack_jtty one frame at a time. + character*80 input, decoded + character*34 frames(MAX_FRAMES) + integer got_nf, iframe + logical is_last + + input='TU NOW JA6DEF 599 123' + frames='' + call pack_jtty(input,frames,got_nf) + if(got_nf.lt.2) then + write(*,1400) got_nf +1400 format('expect_last_frame_flag: expected >=2 frames, got ',i0) + error stop 1 + endif + do iframe=1,got_nf + call unpack_jtty(frames(iframe:iframe),1,decoded,is_last_frame=is_last) + if(iframe.lt.got_nf .and. is_last) then + write(*,1410) iframe +1410 format('expect_last_frame_flag: frame ',i0,' unexpectedly flagged as last') + error stop 1 + endif + if(iframe.eq.got_nf .and. .not.is_last) then + write(*,1420) iframe +1420 format('expect_last_frame_flag: final frame ',i0,' not flagged as last') + error stop 1 + endif + enddo + end subroutine expect_last_frame_flag + +end program test_jtty_pack diff --git a/tests/unit/jtty/test_jtty_payload_correlators.f90 b/tests/unit/jtty/test_jtty_payload_correlators.f90 new file mode 100644 index 00000000..a87fd6c4 --- /dev/null +++ b/tests/unit/jtty/test_jtty_payload_correlators.f90 @@ -0,0 +1,107 @@ +program test_jtty_payload_correlators + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use jtty_payload_correlators + implicit none + + integer(int32), parameter :: lengths(4) = [120,160,192,240] + type(jtty_payload_correlator) :: correlator + complex(real32), allocatable :: samples(:) + complex(real32) :: whole(0:3,46), halves(0:3,46), expected(0:3,46) + integer :: length_index, nss, offset, segment_count + + do length_index = 1, size(lengths) + nss = lengths(length_index) + allocate(samples(0:7+46*nss-1)) + do offset = 0, size(samples)-1 + samples(offset) = cmplx(real(modulo(offset*17,113)-56,real32)/19.0_real32, & + real(modulo(offset*31,127)-63,real32)/23.0_real32,real32) + end do + call jtty_payload_correlator_prepare(correlator,int(nss,int32)) + call jtty_correlate_payload_symbols(correlator,samples,7_int32,whole,halves) + do segment_count = 1, 2 + call separate_reference(samples,7,nss,segment_count,expected) + if (segment_count == 1) then + call require(identical(whole,expected),'shared M1 differs from separate original-order accumulation') + else + call require(identical(halves,expected),'shared M2 differs from separate half-symbol accumulation') + end if + end do + + samples = cmplx(0.0_real32,0.0_real32,real32) + samples(7:7+nss/2-1) = cmplx(1.0_real32,0.0_real32,real32) + samples(7+nss/2:7+nss-1) = cmplx(-1.0_real32,0.0_real32,real32) + call jtty_correlate_payload_symbols(correlator,samples,7_int32,whole,halves) + call require(abs(whole(0,1)) == 0.0_real32,'opposite halves did not cancel in M1') + call require(abs(real(halves(0,1))-real(nss,real32)/sqrt(2.0_real32)) < 0.0001_real32, & + 'M2 failed to retain opposite-phase half energy') + call require(all(abs(whole(:,2:)) == 0.0_real32) .and. & + all(abs(halves(:,2:)) == 0.0_real32),'payload symbol windows overlap') + + samples = cmplx(1.0_real32,0.0_real32,real32) + call jtty_correlate_payload_symbols(correlator,samples(0:7+2*nss-2),7_int32,whole,halves) + call require(abs(whole(0,1)) == real(nss,real32),'complete payload symbol was lost') + call require(all(abs(whole(:,2:)) == 0.0_real32) .and. & + all(abs(halves(:,2:)) == 0.0_real32),'partial symbol was decoded or left stale data') + call jtty_correlate_payload_symbols(correlator,samples,int(size(samples),int32),whole,halves) + call require(all(abs(whole) == 0.0_real32) .and. all(abs(halves) == 0.0_real32), & + 'out-of-range payload left stale observations') + deallocate(samples) + end do + print *, 'test_jtty_payload_correlators: all checks passed' + +contains + + subroutine separate_reference(samples,start,nss,segments,values) + complex(real32), intent(in) :: samples(0:) + integer, intent(in) :: start,nss,segments + complex(real32), intent(out) :: values(0:3,46) + real(real32) :: reference_real(0:nss-1),reference_imaginary(0:nss-1) + real(real32) :: phase,step,sum_real,sum_imaginary,sample_real,sample_imaginary + real(real64) :: energy + integer :: tone,offset,symbol,segment,first,segment_length + + segment_length = nss/segments + do tone = 0, 3 + phase = 0.0_real32 + step = 6.2831853071795864769_real32*real(tone,real32)/real(nss,real32) + do offset = 0, nss-1 + reference_real(offset) = cos(phase) + reference_imaginary(offset) = sin(phase) + phase = phase + step + end do + do symbol = 1, 46 + first = start + (symbol-1)*nss + energy = 0.0_real64 + do segment = 0, segments-1 + sum_real = 0.0_real32 + sum_imaginary = 0.0_real32 + do offset = segment*segment_length, (segment+1)*segment_length-1 + sample_real = real(samples(first+offset),real32) + sample_imaginary = aimag(samples(first+offset)) + sum_real = sum_real + reference_real(offset)*sample_real + & + reference_imaginary(offset)*sample_imaginary + sum_imaginary = sum_imaginary + reference_real(offset)*sample_imaginary - & + reference_imaginary(offset)*sample_real + end do + energy = energy + real(sum_real*sum_real + sum_imaginary*sum_imaginary,real64) + end do + if (segments == 1) then + values(tone,symbol) = cmplx(sum_real,sum_imaginary,real32) + else + values(tone,symbol) = cmplx(real(sqrt(max(0.0_real64,energy)),real32),0.0_real32,real32) + end if + end do + end do + end subroutine separate_reference + + logical function identical(left,right) + complex(real32), intent(in) :: left(:,:),right(:,:) + identical = all(transfer(left,[0_int64],size(left)) == transfer(right,[0_int64],size(right))) + end function identical + + subroutine require(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + if (.not.condition) error stop message + end subroutine require +end program test_jtty_payload_correlators diff --git a/tests/unit/jtty/test_jtty_receive_state.f90 b/tests/unit/jtty/test_jtty_receive_state.f90 new file mode 100644 index 00000000..232679ce --- /dev/null +++ b/tests/unit/jtty/test_jtty_receive_state.f90 @@ -0,0 +1,201 @@ +program test_jtty_receive_state + use iso_fortran_env, only: int64 + use jtty_mdec, only: decode,message_assembly,MAX_ACTIVE_MESSAGES,MAX_RECENT_FRAMES, & + nactive,active_messages, & + nrecent,npending,pending_updates,reset_decode_search_state, & + discard_pending_updates,start_message,append_active_message, & + remove_active_message,is_recent_frame,remember_recent_frame, & + prune_receive_state,classify_active_candidate + implicit none + + real, parameter :: frame_period=2.0 + type(decode) :: candidate,oldest_candidate + type(message_assembly) :: accepted_message,classification_existing + integer(int64) :: first_id,last_id + integer :: i,index,nrecent_before,npending_before,nframes_gap,nmissing + logical :: accepted,match,is_window_dupe + + call reset_all() + + candidate=make_candidate(1500.0,10.0,'FIRST FRAME',.false.) + call start_message(candidate,accepted_message,accepted) + index=nactive + call expect(accepted .and. index.eq.1 .and. nactive.eq.1, & + 'an open message enters the active store') + call expect(npending.eq.1 .and. .not.pending_updates(1)%complete, & + 'an open message publishes its initial state') + call expect(nrecent.eq.1 .and. is_recent_frame(candidate), & + 'an accepted frame enters recent history') + first_id=active_messages(1)%message_id + + candidate=make_candidate(1500.0,12.0,' COMPLETE',.true.) + call append_active_message(1,candidate,1,accepted_message,accepted) + call expect(nactive.eq.0 .and. npending.eq.1, & + 'completion frees active capacity without losing its update') + call expect(pending_updates(1)%message_id.eq.first_id .and. & + pending_updates(1)%complete .and. & + trim(pending_updates(1)%decoded).eq.'FIRST FRAME COMPLETE', & + 'completion coalesces the final state by logical identity') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'BEFORE',.false.) + call start_message(candidate,accepted_message,accepted) + first_id=active_messages(1)%message_id + candidate=make_candidate(1500.0,16.0,'~AFTER',.true.) + call append_active_message(1,candidate,3,accepted_message,accepted) + call expect(accepted .and. nactive.eq.0 .and. npending.eq.1, & + 'a maximum in-range gap completes one logical message') + call expect(pending_updates(1)%message_id.eq.first_id .and. & + pending_updates(1)%complete .and. & + trim(pending_updates(1)%decoded).eq.'BEFORE~~~~~AFTER', & + 'gap assembly inserts one sentinel and strips continuation filler') + + do nmissing=1,3 + classification_existing%f1=1500.0 + classification_existing%tsync=10.0 + candidate=make_candidate(1500.0,10.0+real(nmissing+1)*frame_period, & + 'AFTER',.true.) + call classify_active_candidate(classification_existing,candidate,frame_period, & + match,is_window_dupe,nframes_gap) + if(nmissing.le.2) then + call expect(match .and. .not.is_window_dupe .and. & + nframes_gap.eq.nmissing+1, & + 'classification accepts an in-range missing-frame gap') + else + call expect(.not.match, & + 'classification rejects a gap beyond the merge limit') + endif + enddo + + call reset_decode_search_state() + call expect(nactive.eq.0 .and. nrecent.eq.0 .and. npending.eq.1, & + 'a search reset preserves undelivered updates') + candidate=make_candidate(1510.0,20.0,'AFTER RESET',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. nactive.eq.0 .and. npending.eq.2, & + 'a single-frame completion never occupies active capacity') + call expect(pending_updates(2)%message_id.gt.first_id, & + 'logical identities remain monotonic across search resets') + + call reset_all() + do i=1,MAX_ACTIVE_MESSAGES + candidate=make_candidate(1000.0+real(i),real(i),'OPEN',.false.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. nactive.eq.i, & + 'active messages fill capacity without replacement') + enddo + last_id=active_messages(MAX_ACTIVE_MESSAGES)%message_id + nrecent_before=nrecent + npending_before=npending + candidate=make_candidate(2000.0,100.0,'REFUSED',.false.) + call start_message(candidate,accepted_message,accepted) + call expect(.not.accepted, & + 'a full active store declines a new open message') + call expect(nactive.eq.MAX_ACTIVE_MESSAGES .and. & + nrecent.eq.nrecent_before .and. npending.eq.npending_before, & + 'a declined message leaves every store unchanged') + call remove_active_message(7) + call start_message(candidate,accepted_message,accepted) + index=nactive + call expect(accepted .and. nactive.eq.MAX_ACTIVE_MESSAGES, & + 'freeing one active entry restores capacity') + call expect(active_messages(index)%message_id.eq.last_id+1_int64, & + 'a declined message does not consume a logical identity') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'HISTORY',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(is_recent_frame(candidate), & + 'completion does not remove its frame fingerprint') + call prune_receive_state(11.54,frame_period) + call expect(is_recent_frame(candidate), & + 'history remains until the oldest retro window passes it') + call prune_receive_state(11.56,frame_period) + call expect(.not.is_recent_frame(candidate), & + 'history expires after the rediscovery horizon') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'HISTORY',.true.) + call start_message(candidate,accepted_message,accepted) + candidate=make_candidate(1504.0,10.01,'NEAR SIMULTANEOUS',.true.) + call expect(is_recent_frame(candidate), & + 'recent history rejects a near-simultaneous 4 Hz rediscovery') + candidate=make_candidate(1511.9,10.01,'INSIDE FREQUENCY LIMIT',.true.) + call expect(is_recent_frame(candidate), & + 'recent history catches just inside 12 Hz') + candidate=make_candidate(1512.1,10.01,'OUTSIDE FREQUENCY LIMIT',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows just outside 12 Hz') + candidate=make_candidate(1505.0,10.049,'INSIDE TIME LIMIT',.true.) + call expect(is_recent_frame(candidate), & + 'recent history catches just inside 0.05 seconds') + candidate=make_candidate(1505.0,10.051,'OUTSIDE TIME LIMIT',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows just outside 0.05 seconds') + candidate=make_candidate(1500.0,12.0,'ADJACENT MESSAGE',.true.) + call expect(.not.is_recent_frame(candidate), & + 'recent history allows a message one full frame later') + + call reset_all() + do i=1,MAX_RECENT_FRAMES + candidate=make_candidate(1000.0+real(i),real(i),'HISTORY',.true.) + call remember_recent_frame(candidate) + enddo + oldest_candidate=make_candidate(1001.0,1.0,'HISTORY',.true.) + candidate=make_candidate(2500.0,1000.0,'AFTER HISTORY CAPACITY',.true.) + call start_message(candidate,accepted_message,accepted) + call expect(accepted .and. npending.eq.1, & + 'full duplicate history does not block message delivery') + call expect(nrecent.eq.MAX_RECENT_FRAMES .and. is_recent_frame(candidate) .and. & + .not.is_recent_frame(oldest_candidate), & + 'full duplicate history replaces its oldest fingerprint') + + call reset_all() + candidate=make_candidate(1500.0,10.0,'PARTIAL',.false.) + call start_message(candidate,accepted_message,accepted) + index=nactive + active_messages(index)%decoded='PARTIAL GROWN' + active_messages(index)%k=len_trim(active_messages(index)%decoded) + call prune_receive_state(17.59,frame_period) + call expect(nactive.eq.1, & + 'an assembly remains active through its continuation horizon') + call prune_receive_state(17.61,frame_period) + call expect(nactive.eq.0, & + 'an abandoned assembly expires beyond its continuation horizon') + call expect(npending.eq.1 .and. & + trim(pending_updates(1)%decoded).eq.'PARTIAL GROWN' .and. & + .not.pending_updates(1)%complete, & + 'expiration preserves the newest partial state for delivery') + + print *, 'test_jtty_receive_state: all checks passed' + +contains + + function make_candidate(frequency,tsync,text,complete) result(value) + real, intent(in) :: frequency,tsync + character(len=*), intent(in) :: text + logical, intent(in) :: complete + type(decode) :: value + + value%f1=frequency + value%tsync=tsync + value%decoded=text + value%is_last_frame=complete + end function make_candidate + + subroutine reset_all() + call reset_decode_search_state() + call discard_pending_updates() + end subroutine reset_all + + subroutine expect(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine expect + +end program test_jtty_receive_state diff --git a/tests/unit/jtty/test_jtty_replay_ownership.cpp b/tests/unit/jtty/test_jtty_replay_ownership.cpp new file mode 100644 index 00000000..36876033 --- /dev/null +++ b/tests/unit/jtty/test_jtty_replay_ownership.cpp @@ -0,0 +1,107 @@ +#include <QtTest> +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <mutex> +#include <thread> + +#include "JttyReplay.hpp" + +namespace +{ +constexpr int step = 3456; +} + +class TestJttyReplayOwnership : public QObject +{ + Q_OBJECT + + void verifyReplayBoundWithLiveInput () + { + std::atomic<int> liveFrames {3 * step}; + std::mutex mutex; + std::condition_variable changed; + bool ready = false, released = false, done = false; + bool producerReleased = false, producerReady = false, appendFinished = false; + std::thread writer {[&] { + { + std::unique_lock<std::mutex> lock {mutex}; + ready = true; + changed.notify_all (); + producerReleased = changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return released; }); + } + if (producerReleased) + liveFrames.store (4 * step); + { + std::lock_guard<std::mutex> lock {mutex}; + done = true; + changed.notify_all (); + } + }}; + { + std::unique_lock<std::mutex> lock {mutex}; + producerReady = changed.wait_for (lock, std::chrono::seconds {5}, [&] { return ready; }); + } + QVector<int> visited; + int const replayFrames = liveFrames.load (); + replayJttyFrames (replayFrames, [&] (int k) { + visited.append (k); + if (k == step) + { + std::unique_lock<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + appendFinished = changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return done; }); + } + return false; + }); + writer.join (); + QVERIFY (producerReady); + QVERIFY (producerReleased); + QCOMPARE (liveFrames.load (), 4 * step); + QVERIFY (appendFinished); + // Manual replay is a finite request over its starting receive range; + // audio arriving during a decode belongs to subsequent processing. + QCOMPARE (visited, QVector<int> ({step, 2 * step})); + } + +private Q_SLOTS: + void fixed_range_data () + { + QTest::addColumn<int> ("frames"); + QTest::addColumn<QVector<int>> ("expected"); + QTest::newRow ("empty") << 0 << QVector<int> {}; + QTest::newRow ("short") << step - 1 << QVector<int> {}; + QTest::newRow ("boundary") << step << QVector<int> {}; + QTest::newRow ("past-boundary") << step + 1 << QVector<int> {step}; + QTest::newRow ("multiple") << 3 * step << QVector<int> {step, 2 * step}; + } + + void fixed_range () + { + QFETCH (int, frames); + QFETCH (QVector<int>, expected); + QVector<int> visited; + replayJttyFrames (frames, [&] (int k) { visited.append (k); return false; }); + QCOMPARE (visited, expected); + } + + void picked_stop_processed_once () + { + int frames = 8 * step; + int stop = 5000; + QVector<int> visited; + replayJttyFrames (frames, [&] (int k) { + visited.append (k); + return k >= stop; + }); + QCOMPARE (visited, QVector<int> ({step, 2 * step})); + } + + void replay_is_bounded_at_start () { verifyReplayBoundWithLiveInput (); } +}; + +QTEST_GUILESS_MAIN (TestJttyReplayOwnership) +#include "test_jtty_replay_ownership.moc" diff --git a/tests/unit/jtty/test_jtty_source_codec.f90 b/tests/unit/jtty/test_jtty_source_codec.f90 new file mode 100644 index 00000000..dead01d8 --- /dev/null +++ b/tests/unit/jtty/test_jtty_source_codec.f90 @@ -0,0 +1,202 @@ +program test_jtty_source_codec + use jtty_mod + implicit none + type(jtty_source_atom) :: atom,decoded,atoms(2) + character(len=34) :: frame,frames(MAX_FRAMES) + character(len=80) :: text + logical :: valid,eom + integer :: i,nframes + character(len=34), parameter :: CALL_VECTORS(0:5)=[character(len=34) :: & + '0000100110111101111000110101000001','0000100110111101111000110101010001', & + '0000100110111101111000110101100001','0000100110111101111000110101110001', & + '0000100110111101111000110101000101','0000100110111101111000110101010101'] + character(len=34), parameter :: NUM_VECTORS(0:7)=[character(len=34) :: & + '1000000000000000000001000000001001','1000100000000000000001000000001001', & + '1001000000000000000001000000001001','1001100000000000000001000000001001', & + '1010000000000000000001000000001001','1010100000000000000001000000001001', & + '1011000000000000000001000000001001','1011100000000000000001000000001001'] + character(len=34), parameter :: LOC_VECTORS(0:4)=[character(len=34) :: & + '1000000000000110111010000000011001','1000100000000110111010000000011001', & + '1001000000000110111010000000011001','1001100000000110111010000000011001', & + '1010000000000110111010000000011001'] + character(len=34), parameter :: CONTROL_VECTORS(0:17)=[character(len=34) :: & + '0000000000000000000000000001001001','0000000000100000000000000001001001', & + '0000000001000000000000000001001001','0000000001100000000000000001001001', & + '0000000010000000000000000001001001','0000000010100000000000000001001001', & + '0000000011000000000000000001001001','0000000011100000000000000001001001', & + '0000000100000000000000000001001001','0000000100100000000000000001001001', & + '0000000101000000000000000001001001','0000000101100000000000000001001001', & + '0000000110000000000000000001001001','0000000110100000000000000001001001', & + '0000000111000000000000000001001001','0000000111100000000000000001001001', & + '0000001000000000000000000001001001','0000001000100000000000000001001001'] + + do i=0,5 + call expect_vector(jtty_call_atom(i,'K1ABC'),CALL_VECTORS(i)) + enddo + do i=0,7 + call expect_vector(jtty_exch_num_atom(JTTY_ROLE_FULL,i,1),NUM_VECTORS(i)) + enddo + do i=0,4 + call expect_vector(jtty_exch_loc_atom(JTTY_ROLE_FULL,i,'CA'),LOC_VECTORS(i)) + enddo + call expect_vector(jtty_zone_loc_atom(5,'NWT'), & + '0000001011011110010000110100101001') + call expect_vector(jtty_class_section_atom(1,'D',11), & + '0010000010110001011000000000101001') + call expect_vector(jtty_exch_num_time_atom(JTTY_ROLE_FULL,156,17*60+49), & + '1000000100111001000010110100111001') + call expect_vector(jtty_control_atom(JTTY_CONTROL_AGN), & + '0000000000000000000000000001001001') + call expect_vector(jtty_grid4_atom(JTTY_ROLE_FIELD_ONLY,'FN42'), & + '0001001010000110011000000001001001') + call expect_vector(jtty_text5_atom('HELLO'), & + '0100010011100101010101010110001101') + + do i=0,17 + atom=jtty_control_atom(i) + call expect_vector(atom,CONTROL_VECTORS(i)) + call round_trip(atom,text) + if(trim(text).ne.trim(CONTROL_TEXT(i))) error stop 'control rendering mismatch' + enddo + + atoms(1)=jtty_call_atom(JTTY_CALL_CALL,'K1ABC') + atoms(2)=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,7) + call pack_jtty_atoms(atoms,2,frames,nframes,valid) + if(.not.valid .or. nframes.ne.2) error stop 'atom sequence rejected' + if(frames(1)(33:34).ne.'00' .or. frames(2)(33:34).ne.'01') error stop 'EOM mismatch' + + atom=jtty_exch_loc_atom(JTTY_ROLE_FULL,JTTY_LOC_QTH,'0CA') + call expect_rejected(atom,'noncanonical base36') + call expect_rejected(jtty_exch_loc_atom(1,0,'A-'),'invalid base36 digit') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,0),'CQ zone minimum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,41),'CQ zone maximum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,0),'ITU zone minimum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,91),'ITU zone maximum') + call expect_rejected(jtty_exch_num_atom(1,JTTY_NUM_LICENSE_YEAR,10000),'license year') + call expect_rejected(jtty_exch_num_time_atom(1,16384,0),'time serial') + call expect_rejected(jtty_exch_num_time_atom(1,0,1440),'minute') + call expect_rejected(jtty_zone_loc_atom(0,'CA'),'pair zone') + call expect_rejected(jtty_class_section_atom(0,'A',1),'transmitter count') + call expect_rejected(jtty_class_section_atom(33,'A',1),'transmitter count') + call expect_rejected(jtty_class_section_atom(1,'G',1),'class') + call expect_rejected(jtty_class_section_atom(1,'A',0),'section') + call expect_rejected(jtty_class_section_atom(1,'A',87),'section') + call expect_rejected(jtty_grid4_atom(1,'SA00'),'grid field') + call expect_rejected(jtty_grid4_atom(1,'AA0A'),'grid digit') + call expect_rejected(jtty_call_atom(JTTY_CALL_CALL,'BAD'),'malformed call') + + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,0)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,131071)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,1)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_CQ_ZONE,40)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,1)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_ITU_ZONE,90)) + call expect_legal(jtty_exch_num_atom(1,JTTY_NUM_LICENSE_YEAR,9999)) + call expect_legal(jtty_exch_loc_atom(1,0,'00')) + call expect_legal(jtty_exch_loc_atom(1,0,'100')) + call expect_legal(jtty_exch_num_time_atom(1,0,0)) + call expect_legal(jtty_exch_num_time_atom(1,16383,1439)) + call expect_legal(jtty_class_section_atom(1,'A',1)) + call expect_legal(jtty_class_section_atom(32,'F',86)) + call expect_legal(jtty_grid4_atom(1,'AA00')) + call expect_legal(jtty_grid4_atom(1,'RR99')) + + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,999),'599 999') + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,1000),'599 1000') + call expect_render(jtty_exch_num_atom(1,JTTY_NUM_SERIAL,131071),'599 131071') + call expect_render(jtty_exch_num_atom(0,JTTY_NUM_CHECK,7),'07') + call expect_render(jtty_exch_num_atom(0,JTTY_NUM_CHECK,100),'100') + call expect_render(jtty_exch_num_time_atom(1,16383,1439),'599 16383 2359') + + frame=repeat('0',34) + call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'all-zero sentinel accepted' + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(33:33)='1'; call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'reserved bit 33 accepted' + atom=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1) + call pack_jtty_atom(atom,frame,.true.,valid) + frame(27:27)='1'; call unpack_jtty_atom(frame,decoded,valid,eom) + if(valid .or. eom) error stop 'reserved STRUCT30 field accepted' + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(28:30)='101'; call expect_invalid_frame(frame,'reserved family') + atom=jtty_control_atom(0); call pack_jtty_atom(atom,frame,.true.,valid) + frame(1:4)='0010'; call expect_invalid_frame(frame,'reserved MISC subtype') + atom=jtty_zone_loc_atom(1,'CA'); call pack_jtty_atom(atom,frame,.true.,valid) + frame(1:3)='010'; call expect_invalid_frame(frame,'reserved pair schema') + + write(*,'(a)') 'test_jtty_source_codec: all checks passed' + +contains + subroutine expect_vector(source,want) + type(jtty_source_atom), intent(in) :: source + character(len=34), intent(in) :: want + type(jtty_source_atom) :: result + character(len=34) :: got + logical :: ok,last + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok .or. got.ne.want) then + write(*,'(a,/,a,/,a)') 'golden vector mismatch',want,got + error stop 1 + endif + call unpack_jtty_atom(got,result,ok,last) + if(.not.ok .or. .not.last) error stop 'golden vector did not unpack' + end subroutine expect_vector + + subroutine round_trip(source,rendered) + type(jtty_source_atom), intent(in) :: source + character(len=80), intent(out) :: rendered + type(jtty_source_atom) :: result + character(len=34) :: got + logical :: ok,last + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok) error stop 'round-trip pack failed' + call unpack_jtty_atom(got,result,ok,last) + if(.not.ok) error stop 'round-trip unpack failed' + call render_jtty_atom(result,rendered,ok) + if(.not.ok) error stop 'round-trip render failed' + end subroutine round_trip + + subroutine expect_legal(source) + type(jtty_source_atom), intent(in) :: source + character(len=34) :: got + logical :: ok + call pack_jtty_atom(source,got,.true.,ok) + if(.not.ok) error stop 'legal boundary rejected' + end subroutine expect_legal + + subroutine expect_render(source,want) + type(jtty_source_atom), intent(in) :: source + character(len=*), intent(in) :: want + character(len=80) :: got + call round_trip(source,got) + if(trim(got).ne.want) then + write(*,'(a,/,a,/,a)') 'canonical rendering mismatch',want,trim(got) + error stop 1 + endif + end subroutine expect_render + + subroutine expect_rejected(source,label) + type(jtty_source_atom), intent(in) :: source + character(len=*), intent(in) :: label + character(len=34) :: got + logical :: ok + call pack_jtty_atom(source,got,.true.,ok) + if(ok) then + write(*,'(a,a)') 'invalid atom accepted: ',label + error stop 1 + endif + end subroutine expect_rejected + + subroutine expect_invalid_frame(got,label) + character(len=34), intent(in) :: got + character(len=*), intent(in) :: label + type(jtty_source_atom) :: result + logical :: ok,last + call unpack_jtty_atom(got,result,ok,last) + if(ok .or. last) then + write(*,'(a,a)') 'invalid frame accepted or completed EOM: ',label + error stop 1 + endif + end subroutine expect_invalid_frame +end program test_jtty_source_codec diff --git a/tests/unit/jtty/test_jtty_sticky_retry.f90 b/tests/unit/jtty/test_jtty_sticky_retry.f90 new file mode 100644 index 00000000..719b1ecf --- /dev/null +++ b/tests/unit/jtty/test_jtty_sticky_retry.f90 @@ -0,0 +1,155 @@ +program test_jtty_sticky_retry + + ! decode_and_merge's sticky-sync retry rescues a continuation frame whose + ! own sync symbols are too degraded for the blind search to find, by + ! redecoding directly at the position remembered from the slot it + ! continues -- bypassing the blind search's sync-quality gate entirely. + ! Two bugs in that retry (found in PR #337 review by David Christle, + ! fixed in 48b9e6d74) meant it could silently fail or read the wrong + ! frequency's data. Reproducing the real stochastic conditions that + ! trigger it (weak SNR, fading) isn't reliable for a regression test, so + ! this instead forces it deterministically: frame 2's 13 sync tones are + ! shifted by 2 (mod 4), guaranteeing zero matches against the true sync + ! pattern -- so the blind search's nsync<=6 gate rejects it outright, + ! regardless of what the coarse candidate search finds -- while frame + ! 2's 46 payload tones are left untouched. If the retry works, it merges + ! anyway; if not, frame 2's contribution is silently missing. A second, + ! in-band signal is superimposed so the shared c1 work array actually + ! gets shifted away from the target's own frequency before the retry + ! runs -- see the comment at its construction below for why. + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + integer :: failures + + failures=0 + call run_case('WB9XYZ 599 0123',3,failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_sticky_retry: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_sticky_retry: all checks passed' + +contains + + subroutine run_case(message,nframes,count) + character(len=*), intent(in) :: message + integer, intent(in) :: nframes + integer, intent(inout) :: count + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: tones(MAX_FRAMES*frame_symbols) + integer :: qrm_tones(frame_symbols) + integer :: nsym,qrm_nsym,nsamples,total_samples,ib,i0 + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:),qrm_wave(:),combined(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: input,qrm_input + + call discard_pending_updates() + input=message + call genjtty(input,tones,nsym) + call expect(nsym.eq.nframes*frame_symbols, & + 'the message has the expected frame count',count) + + ! Frame 2's sync tones start right after frame 1's 59 symbols. + ib=frame_symbols+1 + tones(ib:ib+size(is13)-1)=mod(is13+2,4) + + ! rjtty_sub only processes a window once nchunk (1.25 frame periods) + ! more data is available past its start; without a trailing pad past + ! the message's own end, the internal quarter-step sweep runs out of + ! data before ever reaching the window that would check frame 2's + ! continuation, blind or sticky-retry alike (matches the same padding + ! test_jtty_adjacent_decode.f90 uses for the same reason). + nsamples=nsym*nsps + total_samples=nsamples+frame_symbols*nsps + allocate(wave(nsamples),complex_wave(total_samples),combined(total_samples)) + allocate(pcm(total_samples)) + call gen_jttywave(tones,nsym,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsamples) + combined=0. + combined(1:nsamples)=wave + + ! twkfreq unconditionally re-shifts the shared c1 work array for + ! every candidate the blind search tries this call, whether or not + ! it decodes -- so by the time the sticky retry runs, c1 reflects + ! whichever candidate was tried last, not necessarily the target's + ! own frequency. A single clean signal with no competing candidate + ! doesn't exercise that (verified: reverting 48b9e6d74 didn't fail + ! this test until the interferer below was added) -- an in-band + ! interferer (within ftol=50 Hz of f0=1500, so channel 0's own + ! search sees it) gives c1 something else to be shifted to. Tiled + ! from one short message repeated across the buffer, at lower + ! amplitude so it can't preempt the target's own frame 1 decode. + qrm_input='N2PPI' + call genjtty(qrm_input,qrm_tones,qrm_nsym) + allocate(qrm_wave(qrm_nsym*nsps)) + call gen_jttywave(qrm_tones,qrm_nsym,nsps,2.0,12000.0,1540.0, & + complex_wave(1:qrm_nsym*nsps),qrm_wave,0,qrm_nsym*nsps) + i0=1 + do while(i0.le.total_samples) + ib=min(total_samples,i0+qrm_nsym*nsps-1) + combined(i0:ib)=combined(i0:ib)+0.3*qrm_wave(1:ib-i0+1) + i0=i0+qrm_nsym*nsps + enddo + + pcm=int(nint(30000.0*combined),int16) + + ! nfb=1499 (not the usual Wide Graph range) keeps channels 1 and 2 -- + ! whose hardwired bands, [1200,1500] and [1500,1800], meet exactly at + ! the target's own f0 -- from independently retrying the same slot + ! themselves and masking a channel-0-specific failure: the target's + ! own estimated frequency lands a couple of Hz above 1500, just + ! inside channel 2's band too, so without this its own sticky retry + ! can coincidentally rescue the frame channel 0's retry failed to. + call rjtty_sub(pcm,1,nsps,200,1499,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,1499,1500.0,50.0) + + call expect(npending.eq.2,'the decoder keeps the target and interferer', & + count) + call expect(found_complete(message), & + 'the full message decodes despite the corrupted sync',count) + + deallocate(pcm,wave,complex_wave,combined,qrm_wave) + end subroutine run_case + + logical function found_complete(message) + character(len=*), intent(in) :: message + integer :: i + + found_complete=.false. + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message) .and. & + pending_updates(i)%complete) found_complete=.true. + enddo + end function found_complete + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_sticky_retry diff --git a/tests/unit/jtty/test_jtty_structured_decode.f90 b/tests/unit/jtty/test_jtty_structured_decode.f90 new file mode 100644 index 00000000..e74b9c2a --- /dev/null +++ b/tests/unit/jtty/test_jtty_structured_decode.f90 @@ -0,0 +1,330 @@ +program test_jtty_structured_decode + + use iso_c_binding, only: c_int,c_char,c_null_char,c_sizeof + use iso_fortran_env, only: int16,int32 + use jtty_fec, only: is13,PAYLOAD_BITS,TOTAL_K,tbcc_encode + use jtty_tbcc_code_profiles + use jtty_mdec, only: npending,pending_updates,nactive,discard_pending_updates,display_message_text + use jtty_mod, only: jtty_source_atom,jtty_source_atom_c,jtty_call_atom, & + jtty_exch_num_atom,unpack_jtty,MAX_FRAMES,JTTY_CALL_CALL,JTTY_ROLE_FULL, & + JTTY_NUM_SERIAL,JTTY_ATOM_CALL,JTTY_ATOM_EXCH_NUM,JTTY_ATOM_EXCH_LOC, & + JTTY_ATOM_EXCH_PAIR, & + JTTY_ATOM_CONTROL,JTTY_ATOM_GRID4,JTTY_LOC_STATE_PROVINCE, & + JTTY_PAIR_CLASS_SECTION,JTTY_CONTROL_QSL_TU,JTTY_ROLE_FIELD_ONLY, & + JTTY_ENCODE_OK,JTTY_ENCODE_INVALID_DESCRIPTOR, & + JTTY_ENCODE_UNKNOWN_SECTION + implicit none + + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer :: failures + + interface + function jtty_cpp_n1mm_smoke(tones,nsym) result(status) bind(C) + import :: c_int + integer(c_int), intent(out) :: tones(*),nsym + integer(c_int) :: status + end function jtty_cpp_n1mm_smoke + function jtty_cpp_cq_smoke(tones,nsym,text,chained) result(status) bind(C) + import :: c_int,c_char + integer(c_int), intent(out) :: tones(*),nsym + character(kind=c_char), intent(out) :: text(*) + integer(c_int), value :: chained + integer(c_int) :: status + end function jtty_cpp_cq_smoke + function jtty_cpp_rtty_smoke(tones,nsym) result(status) bind(C) + import :: c_int + integer(c_int), intent(out) :: tones(*),nsym + integer(c_int) :: status + end function jtty_cpp_rtty_smoke + subroutine genjtty_atoms(atoms,natoms,itone,nsym) + use jtty_mod, only: jtty_source_atom + type(jtty_source_atom), intent(in) :: atoms(:) + integer, intent(in) :: natoms + integer, intent(out) :: itone(*) + integer, intent(out) :: nsym + end subroutine genjtty_atoms + subroutine genjtty_atoms_c(atoms,natoms,itone,nsym,status) bind(C,name='genjtty_atoms_c') + import :: c_int,jtty_source_atom_c + type(jtty_source_atom_c), intent(in) :: atoms(*) + integer(c_int), value, intent(in) :: natoms + integer(c_int), intent(out) :: itone(*) + integer(c_int), intent(out) :: nsym + integer(c_int), intent(out) :: status + end subroutine genjtty_atoms_c + end interface + + failures=0 + call reject_reserved_struct_family(failures) + call decode_native_call_and_serial(failures) + call decode_c_adapter_atoms(failures) + call reject_invalid_c_descriptors(failures) + call decode_cpp_compiled_n1mm(failures) + call decode_compact_text(failures) + call decode_profile_text(failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_structured_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_structured_decode: all checks passed' + +contains + + subroutine decode_profile_text(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status + + status=jtty_cpp_rtty_smoke(tones,nsymbols) + call expect(status.eq.JTTY_ENCODE_OK .and. nsymbols.eq.frame_symbols, & + 'C++ RTTY profile text matches native F8 while unknown text uses two frames',count) + if(status.ne.JTTY_ENCODE_OK .or. nsymbols.ne.frame_symbols) return + call decode_waveform(tones,int(nsymbols)) + call expect(npending.eq.1,'RTTY serial text produces one update',count) + if(npending.eq.1) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.'599 123' .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'RTTY serial text uses canonical rendering and completes',count) + endif + end subroutine decode_profile_text + + subroutine decode_compact_text(count) + integer, intent(inout) :: count + integer(c_int) :: native_tones(MAX_FRAMES*frame_symbols),native_nsymbols,status + character(kind=c_char) :: c_text(80) + character(len=80) :: text + integer :: tones(MAX_FRAMES*frame_symbols),nsymbols,chained,i + + do chained=0,1 + status=jtty_cpp_cq_smoke(native_tones,native_nsymbols,c_text,int(chained,c_int)) + call expect(status.eq.JTTY_ENCODE_OK .and. native_nsymbols.eq.frame_symbols, & + 'native F1 generates one frame',count) + if(status.ne.JTTY_ENCODE_OK .or. native_nsymbols.ne.frame_symbols) return + do i=1,len(text) + text(i:i)=c_text(i) + enddo + call genjtty(text,tones,nsymbols) + call expect(nsymbols.eq.native_nsymbols,'GUI CQ text generates one frame',count) + if(nsymbols.ne.native_nsymbols) return + call expect(all(tones(1:nsymbols).eq.native_tones(1:nsymbols)), & + 'GUI CQ text and native F1 generate identical channel symbols',count) + enddo + call decode_waveform(tones,nsymbols) + call expect(npending.eq.1,'compact CQ produces one update',count) + if(npending.eq.1) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.'CQ K1ABC CQ' .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'compact CQ preserves text and completes',count) + endif + + text='TEST WB9XYZ 599 123 QSL TU' + call genjtty(text,tones,nsymbols) + call expect(nsymbols.eq.4*frame_symbols,'mixed text generates four frames',count) + if(nsymbols.ne.4*frame_symbols) return + call decode_waveform(tones,nsymbols,10.0) + call expect(npending.eq.1,'mixed text produces one update on the transmitted channel',count) + if(npending.eq.1) then + call expect(trim(normalized(pending_updates(1)%decoded)).eq.trim(text) .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'mixed TEXT5/call/exchange/control preserves spacing and EOM',count) + endif + end subroutine decode_compact_text + + subroutine decode_cpp_compiled_n1mm(count) + integer, intent(inout) :: count + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status + + status=jtty_cpp_n1mm_smoke(tones,nsymbols) + call expect(status.eq.JTTY_ENCODE_OK .and. nsymbols.eq.2*frame_symbols, & + 'C++ compiled descriptors cross the native encoder ABI',count) + if(status.ne.JTTY_ENCODE_OK .or. nsymbols.ne.2*frame_symbols) return + call decode_waveform(tones,int(nsymbols)) + call expect(npending.eq.1,'C++ compiled N1MM message produces one update',count) + if(npending.ne.1) return + call expect(trim(normalized(pending_updates(1)%decoded)).eq.'W9XYZ 32D EMA' .and. & + pending_updates(1)%complete .and. nactive.eq.0, & + 'C++ call/exchange descriptors preserve canonical text and EOM',count) + end subroutine decode_cpp_compiled_n1mm + + subroutine decode_native_call_and_serial(count) + integer, intent(inout) :: count + type(jtty_source_atom) :: atoms(2) + integer :: tones(MAX_FRAMES*frame_symbols),nsymbols + + atoms(1)=jtty_call_atom(JTTY_CALL_CALL,'WB9XYZ') + atoms(2)=jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,1234) + call genjtty_atoms(atoms,size(atoms),tones,nsymbols) + + call expect(nsymbols.eq.size(atoms)*frame_symbols, & + 'native call plus serial generates two frames',count) + if(nsymbols.le.0) return + + call decode_waveform(tones,nsymbols) + + call expect(npending.eq.1, & + 'native call plus serial produces one update',count) + if(npending.ne.1) return + call expect(trim(normalized(pending_updates(1)%decoded)).eq.'WB9XYZ 599 1234', & + 'merged native atoms use canonical call and serial rendering',count) + call expect(pending_updates(1)%complete .and. nactive.eq.0, & + 'final native atom completes and releases the message',count) + end subroutine decode_native_call_and_serial + + subroutine decode_c_adapter_atoms(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atoms(6) + integer(c_int) :: tones(MAX_FRAMES*frame_symbols),nsymbols,status + + call expect(c_sizeof(atoms(1)).eq.20,'C atom descriptor remains 20 bytes',count) + call initialize_c_atom(atoms(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + call initialize_c_atom(atoms(2),JTTY_ATOM_EXCH_NUM,JTTY_NUM_SERIAL, & + JTTY_ROLE_FULL,12,'') + call initialize_c_atom(atoms(3),JTTY_ATOM_EXCH_LOC,JTTY_LOC_STATE_PROVINCE, & + JTTY_ROLE_FULL,0,'CA') + call initialize_c_atom(atoms(4),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION, & + 3,1,'EMA') + call initialize_c_atom(atoms(5),JTTY_ATOM_GRID4,0,JTTY_ROLE_FIELD_ONLY,0,'FN42') + call initialize_c_atom(atoms(6),JTTY_ATOM_CONTROL,JTTY_CONTROL_QSL_TU,0,0,'') + call genjtty_atoms_c(atoms,size(atoms),tones,nsymbols,status) + call expect(nsymbols.eq.size(atoms)*frame_symbols, & + 'C adapter generates serial/state/FD/grid/control frames',count) + call expect(status.eq.JTTY_ENCODE_OK,'C adapter reports successful encoding',count) + if(nsymbols.le.0) return + + call decode_waveform(tones,int(nsymbols)) + call expect(npending.eq.1,'C adapter atoms produce one update',count) + if(npending.ne.1) return + call expect(trim(normalized(pending_updates(1)%decoded)).eq. & + 'K1ABC 599 012 599 CA 1D EMA FN42 QSL TU', & + 'C adapter atoms retain canonical structured rendering',count) + call expect(pending_updates(1)%complete .and. nactive.eq.0, & + 'final C adapter atom completes and releases the message',count) + end subroutine decode_c_adapter_atoms + + subroutine reject_invalid_c_descriptors(count) + integer, intent(inout) :: count + type(jtty_source_atom_c) :: atom(1) + integer(c_int) :: tones(frame_symbols),nsymbols,status + + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_LOC,JTTY_LOC_STATE_PROVINCE,1,0,'CA') + atom(1)%reserved=1 + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects nonzero reserved byte',count) + call expect(status.eq.JTTY_ENCODE_INVALID_DESCRIPTOR, & + 'C adapter identifies invalid descriptor',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_CALL,JTTY_CALL_CALL,0,0,'K1ABC') + atom(1)%text='A' + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unterminated text',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,JTTY_PAIR_CLASS_SECTION,0,1,'ZZZ') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unknown Field Day section',count) + call expect(status.eq.JTTY_ENCODE_UNKNOWN_SECTION, & + 'C adapter identifies unknown Field Day section',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_EXCH_PAIR,0,0,1,'EMA') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects non-CLASS_SECTION pair schema',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_GRID4,0,0,0,'SA00') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects invalid GRID4',count) + + call initialize_c_atom(atom(1),JTTY_ATOM_CONTROL,18,0,0,'') + call genjtty_atoms_c(atom,1,tones,nsymbols,status) + call expect(nsymbols.eq.0,'C adapter rejects unassigned control phrase',count) + end subroutine reject_invalid_c_descriptors + + subroutine initialize_c_atom(atom,kind,subtype,role,value,text) + type(jtty_source_atom_c), intent(out) :: atom + integer, intent(in) :: kind,subtype,role,value + character(len=*), intent(in) :: text + integer :: i,n + + atom%kind=kind; atom%subtype=subtype; atom%role=role; atom%reserved=0 + atom%value=value; atom%text=c_null_char + n=min(8,len_trim(text)) + do i=1,n + atom%text(i)=text(i:i) + enddo + end subroutine initialize_c_atom + + subroutine reject_reserved_struct_family(count) + integer, intent(inout) :: count + character(len=34) :: frame,frames(MAX_FRAMES) + character(len=80) :: decoded + integer(int32) :: payload(PAYLOAD_BITS),encoded(TOTAL_K) + integer :: tones(frame_symbols) + logical :: source_valid,is_last_frame + + ! With an otherwise-zero STRUCT30 body, n32=22 selects reserved family 101. + write(frame(1:32),'(b32.32)') 22_int32 + frame(33:34)='01' + frames='' + frames(1)=frame + call unpack_jtty(frames,1,decoded,is_last_frame=is_last_frame, & + source_valid=source_valid) + call expect(.not.source_valid, & + 'reserved STRUCT30 family is source-invalid',count) + call expect(.not.is_last_frame, & + 'source-invalid frame cannot report EOM',count) + + read(frame,'(34i1)') payload + call tbcc_encode(payload,encoded,JTTY_TBCC_PROFILE_1167_1545_80F) + tones(1:size(is13))=is13 + tones(size(is13)+1:frame_symbols)=encoded + call decode_waveform(tones,frame_symbols) + call expect(npending.eq.0 .and. nactive.eq.0, & + 'CRC/FEC-valid source-invalid frame creates no message or update',count) + end subroutine reject_reserved_struct_family + + subroutine decode_waveform(tones,nsymbols,channel_width) + integer, intent(in) :: tones(:),nsymbols + real, intent(in), optional :: channel_width + integer :: nsamples,total_samples,nfa,nfb + real :: tolerance + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:) + complex, allocatable :: complex_wave(:) + + nsamples=nsymbols*nsps + total_samples=(nsymbols+frame_symbols)*nsps + allocate(wave(nsamples),complex_wave(nsamples),pcm(total_samples)) + call gen_jttywave(tones,nsymbols,nsps,2.0,12000.0,1500.0, & + complex_wave,wave,0,nsamples) + pcm=0_int16 + pcm(1:nsamples)=int(nint(30000.0*wave),int16) + + nfa=200; nfb=2800; tolerance=50.0 + if(present(channel_width)) then + tolerance=channel_width + nfa=ceiling(1500.0-tolerance) + nfb=floor(1500.0+tolerance) + endif + call discard_pending_updates() + call rjtty_sub(pcm,1,nsps,nfa,nfb,1500.0,tolerance) + call rjtty_sub(pcm,total_samples,nsps,nfa,nfb,1500.0,tolerance) + + deallocate(pcm,wave,complex_wave) + end subroutine decode_waveform + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + result_value=display_message_text(value) + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_structured_decode diff --git a/tests/unit/jtty/test_jtty_surface_ranges.f90 b/tests/unit/jtty/test_jtty_surface_ranges.f90 new file mode 100644 index 00000000..97f9b65c --- /dev/null +++ b/tests/unit/jtty/test_jtty_surface_ranges.f90 @@ -0,0 +1,98 @@ +program test_jtty_surface_ranges + use iso_fortran_env, only: int16 + use fftw3, only: fftwf_cleanup + use jtty_fec, only: is13,TOTAL_K + use jtty_mod, only: MAX_FRAMES + use jtty_mdec, only: npending,pending_updates,discard_pending_updates, & + jtty_release_fft_resources + implicit none + integer, parameter :: ncases=8 + integer, parameter :: rates(ncases)=[240,320,384,240,480,480,384,240] + integer, parameter :: scenarios(ncases)=[1,1,1,4,2,1,3,1] + integer :: icase + complex :: fft_scratch(1) + + ! Direct tests own the frequency-window Cartesian product. Keep integration + ! cases for every FFT geometry and each distinct surface-search behavior. + do icase=1,ncases + if(icase.eq.ncases) then + ! Prove that a populated geometry can be recreated after teardown. + call jtty_release_fft_resources() + call four2a(fft_scratch,-1,1,1,1) + call fftwf_cleanup() + endif + call verify_surface_case(rates(icase),scenarios(icase)) + enddo + + call jtty_release_fft_resources() + print *, 'JTTY surface range tests passed' + +contains + + subroutine verify_surface_case(nsps,icase) + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + integer, intent(in) :: nsps,icase + integer :: nsym,nsamples,nlead,total_samples + integer :: tones(MAX_FRAMES*frame_symbols),nfa,nfb + integer(int16), allocatable :: pcm(:) + real, allocatable :: wave(:) + complex, allocatable :: cwave(:) + real :: hz,fc,width + character(len=80) :: message + + call discard_pending_updates() + hz=1500.0 + fc=hz + width=50.0 + nfa=200 + nfb=2800 + select case(icase) + case(2) + ! Auxiliary channels follow graph limits away from their nominal bands. + hz=2700.0 + fc=900.0 + width=3.0 + nfa=2600 + nfb=2750 + case(3) + ! The QSO channel remains usable with an inverted graph range. + hz=400.0 + fc=hz + width=3.0 + nfa=1800 + nfb=1200 + case(4) + ! Narrow, non-bin-aligned limits still need the smoothing halo. + hz=1504.0 + fc=hz + width=0.5 + nfa=1504 + nfb=1505 + end select + + message='N2PPI' + call genjtty(message,tones,nsym) + nsamples=nsym*nsps + nlead=1800 + ! One 1.25-frame chunk contains the lead-in and complete signal. A + ! longer buffer only schedules empty trailing decoder windows. + total_samples=frame_symbols*nsps+(frame_symbols*nsps)/4 + if(nlead+nsamples.gt.total_samples) & + error stop 'surface fixture exceeds one decoder chunk' + allocate(pcm(total_samples),wave(nsamples),cwave(nsamples)) + call gen_jttywave(tones,nsym,nsps,2.0,12000.0,hz,cwave,wave,0,nsamples) + pcm=0_int16 + pcm(nlead+1:nlead+nsamples)=int(nint(14000.0*wave),int16) + call rjtty_sub(pcm,1,nsps,nfa,nfb,fc,width) + call rjtty_sub(pcm,total_samples,nsps,nfa,nfb,fc,width) + if(npending.ne.1) then + print *, 'Unexpected message count',nsps,icase,npending + stop 1 + endif + if(trim(pending_updates(1)%decoded).ne.'N2PPI' .or. & + .not.pending_updates(1)%complete) then + print *, 'Unexpected message',nsps,icase,pending_updates(1)%decoded + stop 1 + endif + end subroutine verify_surface_case +end program diff --git a/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 b/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 new file mode 100644 index 00000000..f49bcf60 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_code_profile.f90 @@ -0,0 +1,115 @@ +program test_jtty_tbcc_code_profile + use, intrinsic :: iso_fortran_env, only: int32, real32 + use jtty_tbcc_code_profiles + use jtty_tbcc_decoder, only: jtty_tbcc_decode + use jtty_tbcc_list_decoder, only: jtty_tbcc_crc_valid + use jtty_mdec, only: jtty_tbcc_reencode_for_subtraction + use tbcc, only: PAYLOAD_BITS, TOTAL_K, encode_crc12, tbcc_encode, & + tbcc_wava_fsk_decode + implicit none + + integer(int32), parameter :: golden_payload(PAYLOAD_BITS) = [ & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, & + 1,0,0,1,0,0,1,0,0,1 ] + integer(int32), parameter :: golden_information_bits(TOTAL_K) = [ & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0, & + 1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,0 ] + integer(int32), parameter :: golden_encoded_bits(2, TOTAL_K) = reshape([ & + 1,0, 0,0, 0,1, 0,0, 1,0, 1,1, 0,1, 1,1, 0,1, 1,1, & + 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, & + 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, & + 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, 0,0, 0,1, 1,1, & + 0,0, 0,1, 1,1, 0,0, 1,0, 1,0 ], [2, TOTAL_K]) + integer(int32), parameter :: golden_tones(TOTAL_K) = [ & + 3,0,1,0,3,2,1,2,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1, & + 2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,3,3 ] + + call expect_descriptor() + call expect_golden_code() + + print *, 'test_jtty_tbcc_code_profile: all checks passed' + +contains + + subroutine expect_descriptor() + type(jtty_tbcc_code_profile) :: unsupported + + call require(jtty_tbcc_code_profile_is_valid(JTTY_TBCC_PROFILE_1167_1545_80F), & + 'established code descriptor is invalid') + call require(jtty_tbcc_code_profile_is_supported(JTTY_TBCC_PROFILE_1167_1545_80F), & + 'established code descriptor is unsupported') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%memory_nu == 9_int32 .and. & + JTTY_TBCC_PROFILE_1167_1545_80F%state_count == 512_int32, & + 'established code trellis dimensions changed') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%generator_0 == int(o'1167', int32) .and. & + JTTY_TBCC_PROFILE_1167_1545_80F%generator_1 == int(o'1545', int32), & + 'established generator polynomials changed') + call require(JTTY_TBCC_PROFILE_1167_1545_80F%outer_polynomial == int(z'80F', int32), & + 'established outer polynomial changed') + + unsupported = JTTY_TBCC_PROFILE_1167_1545_80F + unsupported%generator_1 = int(o'1547', int32) + call require(jtty_tbcc_code_profile_is_valid(unsupported), & + 'unsupported-code fixture is not structurally valid') + call require(.not.jtty_tbcc_code_profile_is_supported(unsupported), & + 'noncanonical code was reported as supported') + end subroutine expect_descriptor + + subroutine expect_golden_code() + integer(int32) :: encoded_information(2, TOTAL_K), encoded_bits(2, TOTAL_K) + integer(int32) :: invalid_information(TOTAL_K) + integer(int32) :: tones(TOTAL_K), subtraction_tones(TOTAL_K) + integer(int32) :: decoded(PAYLOAD_BITS) + real(real32) :: tone_energies(0:3, TOTAL_K) + complex(real32) :: correlations(0:3, TOTAL_K) + logical :: success + + call encode_crc12(golden_payload, encoded_information, JTTY_TBCC_PROFILE_1167_1545_80F) + call require(all(encoded_information(1, :) == golden_information_bits), & + 'outer-check bits changed from the golden vector') + call require(jtty_tbcc_crc_valid(JTTY_TBCC_PROFILE_1167_1545_80F, & + encoded_information(1, :)), 'golden outer-check word was rejected') + invalid_information = encoded_information(1, :) + invalid_information(TOTAL_K) = 1_int32 - invalid_information(TOTAL_K) + call require(.not.jtty_tbcc_crc_valid(JTTY_TBCC_PROFILE_1167_1545_80F, & + invalid_information), 'outer check accepted a corrupted word') + + call tbcc_encode(golden_payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F, encoded_bits) + call require(all(encoded_bits == golden_encoded_bits), & + 'encoded bits changed from the golden vector') + call require(all(tones == golden_tones), 'tones changed from the golden vector') + + call make_noiseless_observations(tones, tone_energies, correlations) + call tbcc_wava_fsk_decode(tone_energies, 4_int32, 2_int32, decoded, success, & + reserved_zero_bit=33_int32, code_profile=JTTY_TBCC_PROFILE_1167_1545_80F) + call require(success .and. all(decoded == golden_payload), 'WAVA decode failed') + call jtty_tbcc_decode(correlations, correlations, decoded, success) + call require(success .and. all(decoded == golden_payload), 'coherent decode failed') + + call jtty_tbcc_reencode_for_subtraction(golden_payload, subtraction_tones) + call require(all(subtraction_tones == golden_tones), & + 'subtraction re-encoding did not reproduce the established tones') + end subroutine expect_golden_code + + subroutine make_noiseless_observations(tones, tone_energies, correlations) + integer(int32), intent(in) :: tones(TOTAL_K) + real(real32), intent(out) :: tone_energies(0:3, TOTAL_K) + complex(real32), intent(out) :: correlations(0:3, TOTAL_K) + integer(int32) :: symbol + + tone_energies = 0.0_real32 + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, TOTAL_K + tone_energies(tones(symbol), symbol) = 100.0_real32 + correlations(tones(symbol), symbol) = cmplx(100.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_observations + + subroutine require(condition, message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if (.not.condition) error stop message + end subroutine require + +end program test_jtty_tbcc_code_profile diff --git a/tests/unit/jtty/test_jtty_tbcc_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 new file mode 100644 index 00000000..50fb6f63 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_decoder.f90 @@ -0,0 +1,143 @@ +program test_jtty_tbcc_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32 + use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F + use jtty_tbcc_decoder, only: jtty_tbcc_decode, jtty_tbcc_decode_result + use tbcc, only: PAYLOAD_BITS, TOTAL_K, tbcc_encode + implicit none + + complex(real32) :: correlations(0:3, TOTAL_K), halves(0:3, TOTAL_K) + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS), tones(TOTAL_K) + type(jtty_tbcc_decode_result) :: result + logical :: success + integer(int32) :: bit_index + + do bit_index = 1, PAYLOAD_BITS + payload(bit_index) = modulo(bit_index + bit_index/3, 2) + end do + payload(33) = 0_int32 + halves = cmplx(0.0_real32, 0.0_real32, real32) + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(success, 'coherence ladder rejected a noiseless payload') + call require(all(decoded == payload), 'coherence ladder changed the payload') + call require(result%accepted_hypothesis_rank == 1_int32, & + 'noiseless payload was not the first hypothesis') + call require(result%coherent_block_length == 1_int32, & + 'noiseless payload did not stop at one-symbol coherence') + call require(result%evaluated_rung_count == 1_int32, & + 'noiseless payload evaluated unnecessary coherence rungs') + call require(.not.result%used_half_symbol_observation, & + 'rank-one payload unexpectedly evaluated half-symbol fallback') + call require(result%exported_candidate_count <= 4_int32, & + 'coherence ladder exposed more than four hypotheses per rung') + + payload(33) = 1_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(.not.success, 'coherence ladder accepted reserved bit one') + call require(all(decoded == 0_int32), & + 'reserved-bit rejection left a stale payload') + + halves = correlations + correlations = cmplx(0.0_real32, 0.0_real32, real32) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(.not.success, 'half-symbol fallback accepted reserved bit one') + call require(all(decoded == 0_int32), & + 'half-symbol reserved-bit rejection left a stale payload') + + payload(33) = 0_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, halves) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(success .and. all(decoded == payload), 'half-symbol fallback failed to rescue payload') + call require(result%used_half_symbol_observation .and. result%coherent_block_length == 1, & + 'half-symbol fallback used the wrong observation or coherence') + call require(result%evaluated_rung_count == 4, 'fallback skipped an M1 rung') + halves = cmplx(0.0_real32, 0.0_real32, real32) + + payload = 0_int32 + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + call make_noiseless_correlations(tones, correlations) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(.not.success, 'coherence ladder accepted the all-zero payload') + call require(all(decoded == 0_int32), 'failed ladder decode left stale payload') + call require(result%evaluated_rung_count == 4_int32, & + 'failed decode did not report all evaluated rungs') + + correlations = cmplx(0.0_real32, 0.0_real32, real32) + decoded = huge(0_int32) + call jtty_tbcc_decode(correlations, halves, decoded, success, result) + call require(.not.success, 'coherence ladder accepted flat correlations') + call require(all(decoded == 0_int32), 'flat-correlation decode left stale payload') + call require(result%evaluated_rung_count == 4_int32, & + 'flat-correlation decode did not report all evaluated rungs') + + call expect_coherent_decodes() + + print *, 'test_jtty_tbcc_decoder: all checks passed' + +contains + + subroutine expect_coherent_decodes() + ! Seed 6 verifies that reserved-bit pruning retains the valid L1 path. + integer(int32), parameter :: seeds(2) = [2,6], lengths(2) = [2,1], & + ranks(2) = [2,1], evaluated_rungs(2) = [2,1] + integer(int64) :: state + integer :: fixture, symbol, tone, bit + real(real32) :: in_phase, quadrature + + do bit = 1, PAYLOAD_BITS + payload(bit) = modulo(bit + bit/3,2) + end do + payload(33) = 0 + call tbcc_encode(payload,tones,JTTY_TBCC_PROFILE_1167_1545_80F) + halves = cmplx(0.0_real32,0.0_real32,real32) + do fixture = 1, size(seeds) + state = seeds(fixture) + do symbol = 1, TOTAL_K + do tone = 0, 3 + state = modulo(48271_int64*state,2147483647_int64) + in_phase = real(state,real32)/2147483647.0_real32 - 0.5_real32 + state = modulo(48271_int64*state,2147483647_int64) + quadrature = real(state,real32)/2147483647.0_real32 - 0.5_real32 + correlations(tone,symbol) = cmplx(in_phase,quadrature,real32) + end do + correlations(tones(symbol),symbol) = correlations(tones(symbol),symbol) + & + cmplx(0.55_real32,0.0_real32,real32) + end do + call jtty_tbcc_decode(correlations,halves,decoded,success,result) + call require(success .and. all(decoded == payload),'coherent rung failed to decode fixed payload') + call require(result%coherent_block_length == lengths(fixture), 'coherent decode used wrong rung') + call require(result%accepted_hypothesis_rank == ranks(fixture), 'coherent decode candidate rank changed') + call require(result%evaluated_rung_count == evaluated_rungs(fixture), & + 'accepted candidate triggered unnecessary confirmation or fallback') + call require(.not.result%used_half_symbol_observation, 'coherent decode fell through to M2') + end do + end subroutine expect_coherent_decodes + + subroutine make_noiseless_correlations(symbols, values) + integer(int32), intent(in) :: symbols(TOTAL_K) + complex(real32), intent(out) :: values(0:3, TOTAL_K) + integer(int32) :: symbol + + values = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, TOTAL_K + values(symbols(symbol), symbol) = cmplx(100.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_correlations + + subroutine require(condition, message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if (.not.condition) error stop message + end subroutine require + +end program test_jtty_tbcc_decoder diff --git a/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 new file mode 100644 index 00000000..d8b4eed7 --- /dev/null +++ b/tests/unit/jtty/test_jtty_tbcc_list_decoder.f90 @@ -0,0 +1,300 @@ +program test_jtty_tbcc_list_decoder + use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64 + use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, & + JTTY_TBCC_PROFILE_1167_1545_80F + use tbcc, only: tbcc_encode, encode_crc12 + use jtty_tbcc_list_decoder + implicit none + + call expect_optimized_reference_parity() + call expect_noiseless_tailbiting_decode() + call expect_reserved_bit_pruning() + call expect_deterministic_hypothesis_budget() + call expect_coherent_normalization() + + print *, 'test_jtty_tbcc_list_decoder: all checks passed' + +contains + + subroutine expect_optimized_reference_parity() + integer(int32), parameter :: coherent_lengths(3) = [1_int32, 2_int32, 4_int32] + integer(int32), parameter :: survivor_widths(2) = [1_int32, 4_int32] + type(jtty_tbcc_decoder_plan) :: plan + type(jtty_tbcc_decoder_workspace) :: workspace + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: coherent_index, width_index, symbol, tone, wraps + + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + do tone = 0, 3 + correlations(tone, symbol) = cmplx( & + real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & + real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, & + real32) + end do + end do + + do wraps = 1, 2 + do coherent_index = 1, size(coherent_lengths) + do width_index = 1, size(survivor_widths) + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, & + JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, .false.) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), survivor_widths(width_index), wraps, .true.) + end do + end do + end do + + ! Equal branch energies exercise deterministic ties and wrap deduplication. + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do width_index = 1, 4 + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, 4_int32, & + width_index, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + 4_int32, width_index, 2_int32, .false.) + end do + + ! A common large branch collapses distinct accumulated metrics into ties. + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + do tone = 0, 3 + correlations(tone, symbol) = scale(1.0_real32, -18)*cmplx( & + real(modulo(17*tone + 11*symbol, 29) - 14, real32)/8.0_real32, & + real(modulo(7*tone + 19*symbol, 31) - 15, real32)/9.0_real32, real32) + end do + end do + correlations(:, 13) = cmplx(scale(1.0_real32, 20), 0.0_real32, real32) + do coherent_index = 1, size(coherent_lengths) + call jtty_tbcc_init_decoder_plan(plan, JTTY_TBCC_PROFILE_1167_1545_80F, & + coherent_lengths(coherent_index), 4_int32, 2_int32, JTTY_TBCC_MAX_HYPOTHESES) + call jtty_tbcc_init_decoder_workspace(workspace, plan) + call expect_decode_parity(JTTY_TBCC_PROFILE_1167_1545_80F, plan, workspace, correlations, & + coherent_lengths(coherent_index), 4_int32, 2_int32, .false.) + end do + end subroutine expect_optimized_reference_parity + + subroutine expect_decode_parity(code, plan, workspace, correlations, & + coherent_length, survivor_width, wraps, prune) + type(jtty_tbcc_code_profile), intent(in) :: code + type(jtty_tbcc_decoder_plan), intent(in) :: plan + type(jtty_tbcc_decoder_workspace), intent(inout) :: workspace + complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(in) :: coherent_length, survivor_width, wraps + logical, intent(in) :: prune + integer(int32) :: reference_bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: optimized_bits(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: reference_states(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: optimized_states(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: reference_count, optimized_count, reference_pool, optimized_pool + integer(int64) :: reference_ids(JTTY_TBCC_MAX_HYPOTHESES) + integer(int64) :: optimized_ids(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: reference_clean(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: optimized_clean(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: reference_wava(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: optimized_wava(JTTY_TBCC_MAX_HYPOTHESES) + logical :: reference_crc(JTTY_TBCC_MAX_HYPOTHESES) + logical :: optimized_crc(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: tracked_bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32 + integer(int32) :: reference_pool_rank, optimized_pool_rank, reference_h_rank, optimized_h_rank + logical :: reference_present, optimized_present + + call jtty_tbcc_list_wava_reference(correlations, code, coherent_length, & + survivor_width, wraps, JTTY_TBCC_MAX_HYPOTHESES, reference_bits, & + reference_ids, reference_clean, reference_wava, reference_states, & + reference_crc, reference_count, reference_pool, prune_reserved_zero=prune, & + reference_bits=tracked_bits, reference_present=reference_present, & + reference_pool_rank=reference_pool_rank, reference_h_rank=reference_h_rank) + call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, optimized_bits, & + optimized_ids, optimized_clean, optimized_wava, optimized_states, & + optimized_crc, optimized_count, optimized_pool, prune_reserved_zero=prune, & + reference_bits=tracked_bits, reference_present=optimized_present, & + reference_pool_rank=optimized_pool_rank, reference_h_rank=optimized_h_rank) + + if (reference_count /= optimized_count .or. reference_pool /= optimized_pool .or. & + any(reference_bits /= optimized_bits) .or. any(reference_ids /= optimized_ids) .or. & + .not.real_arrays_agree(reference_clean, optimized_clean) .or. & + .not.real_arrays_agree(reference_wava, optimized_wava) .or. & + any(reference_states /= optimized_states) .or. & + any(reference_crc .neqv. optimized_crc) .or. & + (reference_present .neqv. optimized_present) .or. & + reference_pool_rank /= optimized_pool_rank .or. reference_h_rank /= optimized_h_rank) & + error stop 'TBCC list decoder optimized/reference mismatch' + end subroutine expect_decode_parity + + subroutine expect_noiseless_tailbiting_decode() + type(jtty_tbcc_code_profile) :: code + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), candidate_count, pool_count + integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES), rescored_metric + logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES), closed + + code = JTTY_TBCC_PROFILE_1167_1545_80F + call make_codeword(.false., information_bits, tones) + call make_noiseless_correlations(tones, correlations) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.true.) + + if (candidate_count < 1_int32 .or. pool_count < candidate_count) & + error stop 'TBCC list decoder returned no noiseless candidate' + if (any(candidates(:, 1) /= information_bits) .or. .not.crc_valid(1)) & + error stop 'TBCC list decoder noiseless candidate mismatch' + if (states(1) /= jtty_tbcc_tailbiting_state(code, information_bits)) & + error stop 'TBCC list decoder tail-biting state mismatch' + call jtty_tbcc_score_candidate(code, correlations, 4_int32, candidates(:, 1), & + rescored_metric, closed) + if (.not.closed .or. rescored_metric /= clean_metrics(1) .or. & + abs(clean_metrics(1) - 46.0_real64) > 1.0e-12_real64) & + error stop 'TBCC list decoder final L2 block or clean rescore mismatch' + end subroutine expect_noiseless_tailbiting_decode + + subroutine expect_reserved_bit_pruning() + type(jtty_tbcc_code_profile) :: code + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states(JTTY_TBCC_MAX_HYPOTHESES), candidate_count, pool_count + integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES), forbidden_identity + real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES) + + code = JTTY_TBCC_PROFILE_1167_1545_80F + call make_codeword(.true., information_bits, tones) + call make_noiseless_correlations(tones, correlations) + forbidden_identity = jtty_tbcc_candidate_identity(information_bits) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.false.) + if (candidate_count < 1_int32 .or. identities(1) /= forbidden_identity) & + error stop 'TBCC list decoder unpruned control mismatch' + + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, candidates, identities, clean_metrics, path_metrics, & + states, crc_valid, candidate_count, pool_count, prune_reserved_zero=.true.) + if (candidate_count > 0_int32) then + if (any(candidates(JTTY_TBCC_RESERVED_BIT, 1:candidate_count) /= 0_int32)) & + error stop 'TBCC list decoder reserved-bit pruning failed' + if (any(identities(1:candidate_count) == forbidden_identity)) & + error stop 'TBCC list decoder retained reserved-invalid identity' + end if + end subroutine expect_reserved_bit_pruning + + subroutine expect_deterministic_hypothesis_budget() + type(jtty_tbcc_code_profile) :: code + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: bits_a(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: bits_b(JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_a(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: states_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: count_a, count_b, pool_a, pool_b, rank + integer(int64) :: ids_a(JTTY_TBCC_MAX_HYPOTHESES), ids_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: clean_a(JTTY_TBCC_MAX_HYPOTHESES), clean_b(JTTY_TBCC_MAX_HYPOTHESES) + real(real64) :: path_a(JTTY_TBCC_MAX_HYPOTHESES), path_b(JTTY_TBCC_MAX_HYPOTHESES) + logical :: crc_a(JTTY_TBCC_MAX_HYPOTHESES), crc_b(JTTY_TBCC_MAX_HYPOTHESES) + integer(int32) :: one_bit(JTTY_TBCC_INFORMATION_BITS, 1), one_state(1) + integer(int32) :: one_count, one_pool + integer(int64) :: one_id(1) + real(real64) :: one_clean(1), one_path(1) + logical :: one_crc(1) + + code = JTTY_TBCC_PROFILE_1167_1545_80F + correlations = cmplx(0.0_real32, 0.0_real32, real32) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, bits_a, ids_a, clean_a, path_a, states_a, & + crc_a, count_a, pool_a, prune_reserved_zero=.true.) + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + JTTY_TBCC_MAX_HYPOTHESES, bits_b, ids_b, clean_b, path_b, states_b, & + crc_b, count_b, pool_b, prune_reserved_zero=.true.) + + if (count_a /= JTTY_TBCC_MAX_HYPOTHESES .or. count_b /= count_a .or. & + pool_a < count_a .or. pool_b /= pool_a) & + error stop 'TBCC list decoder did not enforce the H4 budget' + if (any(bits_a /= bits_b) .or. any(ids_a /= ids_b) .or. & + any(states_a /= states_b) .or. .not.real_arrays_agree(clean_a, clean_b) .or. & + .not.real_arrays_agree(path_a, path_b) .or. any(crc_a .neqv. crc_b)) & + error stop 'TBCC list decoder tie order is not deterministic' + do rank = 2, count_a + if (ids_a(rank) <= ids_a(rank - 1)) & + error stop 'TBCC list decoder did not deduplicate tied identities' + end do + + call jtty_tbcc_list_wava(correlations, code, 4_int32, 4_int32, 2_int32, & + 1_int32, one_bit, one_id, one_clean, one_path, one_state, one_crc, & + one_count, one_pool, prune_reserved_zero=.true.) + if (one_count /= 1_int32 .or. one_id(1) /= ids_a(1) .or. one_pool /= pool_a) & + error stop 'TBCC list decoder did not enforce the H1 budget' + end subroutine expect_deterministic_hypothesis_budget + + subroutine expect_coherent_normalization() + complex(real32) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: tones4(4), tones2(2) + real(real64) :: metric + + correlations = cmplx(0.0_real32, 0.0_real32, real32) + tones4 = [0_int32, 1_int32, 2_int32, 3_int32] + correlations(0, 3) = cmplx(1.0_real32, 0.0_real32, real32) + correlations(1, 4) = cmplx(2.0_real32, 0.0_real32, real32) + correlations(2, 5) = cmplx(3.0_real32, 0.0_real32, real32) + correlations(3, 6) = cmplx(4.0_real32, 0.0_real32, real32) + metric = jtty_tbcc_coherent_metric(correlations, 3_int32, tones4) + if (metric /= 25.0_real64) error stop 'TBCC L4 normalization mismatch' + + tones2 = [1_int32, 3_int32] + correlations(1, 45) = cmplx(2.0_real32, 0.0_real32, real32) + correlations(3, 46) = cmplx(4.0_real32, 0.0_real32, real32) + metric = jtty_tbcc_coherent_metric(correlations, 45_int32, tones2) + if (metric /= 18.0_real64) error stop 'TBCC final L2 normalization mismatch' + end subroutine expect_coherent_normalization + + subroutine make_codeword(set_reserved_bit, information_bits, tones) + logical, intent(in) :: set_reserved_bit + integer(int32), intent(out) :: information_bits(JTTY_TBCC_INFORMATION_BITS) + integer(int32), intent(out) :: tones(JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: payload(34), encoded(2, JTTY_TBCC_INFORMATION_BITS), bit_index + + do bit_index = 1, size(payload) + payload(bit_index) = modulo(5*bit_index + bit_index/3, 2) + end do + payload(JTTY_TBCC_RESERVED_BIT) = merge(1_int32, 0_int32, set_reserved_bit) + call encode_crc12(payload, encoded, JTTY_TBCC_PROFILE_1167_1545_80F) + call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F) + information_bits = encoded(1, :) + end subroutine make_codeword + + subroutine make_noiseless_correlations(tones, correlations) + integer(int32), intent(in) :: tones(JTTY_TBCC_INFORMATION_BITS) + complex(real32), intent(out) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS) + integer(int32) :: symbol + + correlations = cmplx(0.0_real32, 0.0_real32, real32) + do symbol = 1, JTTY_TBCC_INFORMATION_BITS + correlations(tones(symbol), symbol) = cmplx(1.0_real32, 0.0_real32, real32) + end do + end subroutine make_noiseless_correlations + + pure logical function real_arrays_agree(left, right) result(agree) + real(real64), intent(in) :: left(:), right(:) + integer(int32) :: element + + agree = size(left) == size(right) + if (.not.agree) return + do element = 1, size(left) + if (left(element) == right(element)) cycle + if (abs(left(element)-right(element)) <= 64.0_real64*epsilon(0.0_real64)* & + max(1.0_real64, abs(left(element)), abs(right(element)))) cycle + agree = .false. + return + end do + end function real_arrays_agree + +end program test_jtty_tbcc_list_decoder diff --git a/tests/unit/jtty/test_jtty_txstream.cpp b/tests/unit/jtty/test_jtty_txstream.cpp new file mode 100644 index 00000000..d71be2a6 --- /dev/null +++ b/tests/unit/jtty/test_jtty_txstream.cpp @@ -0,0 +1,487 @@ +#include <QtTest/QtTest> +#include <QSignalSpy> +#include <QPointer> +#include <QThread> +#include <QVector> + +#include "Audio/AudioDevice.hpp" +#include "Audio/TxAudioQueue.hpp" +#include "Audio/TxIdentity.hpp" +#include "Audio/TxPlaybackEvidence.hpp" +#include "Audio/TxRequest.hpp" +#include "Modulator/JttyPcmFifo.hpp" +#include "Modulator/JttyTxStream.hpp" + +// Unit tests for the JTTY async transmit source. These exercise the FIFO / +// served-sample mechanics, the drain predicate, and the drained() edge signal +// without any audio hardware: readData() is driven through the public +// QIODevice::read() API after opening the device with initialize(). + +class TestJttyTxStream : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase (); + void gaplessConcatAndSilencePad (); + void clearResetsCounters (); + void clearThenEnqueueSkipsOldSamples (); + void clearDuringPartialPlaybackSkipsRemainder (); + void pendingResetProgressExcludesAbortedAudio (); + void fifoOverflowRejectsWithoutTruncating (); + void fifoWrappedEnqueuePreservesOrder (); + void enqueueFitPredicate (); + void fifoDrainStateCarriesEpochAndTotal (); + void fifoDrainAfterResetUsesNewEpochAndTotal (); + void fifoEpochBoundaryAfterNaturalDrainResetsTotal (); + void drainedPredicate (); + void readDoesNotEmitDrainedDirectly (); + void timerEmitsDrainedEdge (); + void drainedEmittedFromWorkerThread (); + void sourceCommitUsesCurrentRealExtent (); + void staleQueueEpochDoesNotStart (); + void sourceCommitIsEmittedOncePerStart (); +}; + +namespace +{ + // Default drain guard baked into JttyTxStream when start() has not run (no + // device buffer to measure). Mirrors DEFAULT_DRAIN_GUARD in JttyTxStream.cpp. + constexpr int DEFAULT_GUARD = 9600; + + TxEvidence::TxRequest jttyRequest (qint64 sessionId, qint64 generation, + qint64 queueEpoch = -1) + { + TxEvidence::TxRequest request; + request.mode = QStringLiteral ("JTTY"); + request.session_id = TxEvidence::TxSessionId {sessionId}; + request.generation = TxEvidence::TxGeneration {generation}; + request.queue_epoch = TxAudioQueueEpoch { + queueEpoch >= 0 ? queueEpoch : sessionId}; + return request; + } + + TxAudioQueueEpoch queueEpoch (qint64 value) + { + return TxAudioQueueEpoch {value}; + } + + QVector<qint16> readFrames (JttyTxStream & s, int frames) + { + QByteArray buf (frames * 2, '\xff'); + qint64 got = s.read (buf.data (), buf.size ()); + QVector<qint16> out; + if (got <= 0) return out; + int n = int (got / 2); + qint16 const * p = reinterpret_cast<qint16 const *> (buf.constData ()); + for (int i = 0; i < n; ++i) out.append (p[i]); + return out; + } +} + +void TestJttyTxStream::initTestCase () +{ + qRegisterMetaType<TxAudioQueueDrainState> ("TxAudioQueueDrainState"); +} + +void TestJttyTxStream::gaplessConcatAndSilencePad () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (1); + queue.clear (epoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + + // Two messages queued before any are consumed: they must chain with no gap. + QVERIFY (queue.enqueue (QVector<qint16> {10, 20, 30}, epoch).accepted); + QVERIFY (queue.enqueue (QVector<qint16> {40, 50}, epoch).accepted); + QCOMPARE (queue.progress ().total_samples, qint64 (5)); + + // Pull 7 frames: 5 real samples concatenated in order, then silence padding. + QVector<qint16> got = readFrames (s, 7); + QCOMPARE (got.size (), 7); + QCOMPARE (got, (QVector<qint16> {10, 20, 30, 40, 50, 0, 0})); + + QCOMPARE (queue.progress ().served_samples, qint64 (5)); // padding is not counted as real + + // A late message resumes real audio after the silence (late-message path). + QVERIFY (queue.enqueue (QVector<qint16> {60}, epoch).accepted); + QCOMPARE (queue.progress ().total_samples, qint64 (6)); + QVector<qint16> more = readFrames (s, 2); + QCOMPARE (more, (QVector<qint16> {60, 0})); + QCOMPARE (queue.progress ().served_samples, qint64 (6)); +} + +void TestJttyTxStream::clearResetsCounters () +{ + TxAudioQueue queue; + auto const firstEpoch = queueEpoch (1); + queue.clear (firstEpoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, firstEpoch).accepted); + (void) readFrames (s, 2); + queue.clear (queueEpoch (2)); + QCOMPARE (queue.progress ().total_samples, qint64 (0)); + QCOMPARE (queue.progress ().served_samples, qint64 (0)); + // After clear the device pads pure silence. + QCOMPARE (readFrames (s, 3), (QVector<qint16> {0, 0, 0})); +} + +void TestJttyTxStream::clearThenEnqueueSkipsOldSamples () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 1)); + fifo.clear (2); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + + QVector<qint16> got; + for (int i = 0; i < 4; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {4, 5, 0, 0})); + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (2)); +} + +void TestJttyTxStream::clearDuringPartialPlaybackSkipsRemainder () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4, 5}, 1)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + + fifo.clear (2); + QCOMPARE (fifo.totalReal (), qint64 (0)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (0)); + + QVERIFY (fifo.enqueue (QVector<qint16> {6}, 2)); + QCOMPARE (fifo.pullSample (2), qint16 (6)); + QCOMPARE (fifo.pullSample (2), qint16 (0)); + QCOMPARE (fifo.totalReal (), qint64 (1)); + QCOMPARE (fifo.servedReal (), qint64 (1)); +} + +void TestJttyTxStream::pendingResetProgressExcludesAbortedAudio () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4, 5}, 1)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + + fifo.clear (2); + QVERIFY (fifo.enqueue (QVector<qint16> {6, 7}, 2)); + + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QCOMPARE (fifo.queuedReal (), qint64 (2)); + QCOMPARE (fifo.pullSample (2), qint16 (6)); + QCOMPARE (fifo.totalReal (), qint64 (2)); + QCOMPARE (fifo.servedReal (), qint64 (1)); + QCOMPARE (fifo.queuedReal (), qint64 (1)); +} + +void TestJttyTxStream::fifoOverflowRejectsWithoutTruncating () +{ + JttyPcmFifo fifo {4}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 11)); + QVERIFY (!fifo.enqueue (QVector<qint16> {4, 5}, 11)); + QCOMPARE (fifo.totalReal (), qint64 (3)); + + QVector<qint16> got; + for (int i = 0; i < 5; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {1, 2, 3, 0, 0})); +} + +void TestJttyTxStream::fifoWrappedEnqueuePreservesOrder () +{ + JttyPcmFifo fifo {5}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3, 4}, 11)); + QCOMPARE (fifo.pullSample (2), qint16 (1)); + QCOMPARE (fifo.pullSample (2), qint16 (2)); + QCOMPARE (fifo.pullSample (2), qint16 (3)); + + QVERIFY (fifo.enqueue (QVector<qint16> {5, 6, 7}, 11)); + + QVector<qint16> got; + for (int i = 0; i < 5; ++i) got.append (fifo.pullSample (2)); + QCOMPARE (got, (QVector<qint16> {4, 5, 6, 7, 0})); + QCOMPARE (fifo.totalReal (), qint64 (7)); + QCOMPARE (fifo.servedReal (), qint64 (7)); +} + +void TestJttyTxStream::enqueueFitPredicate () +{ + QVERIFY (jttyPcmEnqueueFits (4, 0, 4)); + QVERIFY (jttyPcmEnqueueFits (4, 2, 2)); + QVERIFY (jttyPcmEnqueueFits (4, 4, 0)); + QVERIFY (!jttyPcmEnqueueFits (4, 1, 4)); + QVERIFY (!jttyPcmEnqueueFits (4, 5, 1)); + QVERIFY (!jttyPcmEnqueueFits (0, 0, 1)); + QVERIFY (!jttyPcmEnqueueFits (4, -1, 1)); +} + +void TestJttyTxStream::fifoDrainStateCarriesEpochAndTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + for (int i = 0; i < 5; ++i) (void) fifo.pullSample (2); + + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (3)); + + QVERIFY (fifo.enqueue (QVector<qint16> {4}, 21)); + for (int i = 0; i < 3; ++i) (void) fifo.pullSample (2); + drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (4)); + + fifo.clear (22); + QCOMPARE (fifo.totalReal (), qint64 (0)); + QCOMPARE (fifo.servedReal (), qint64 (0)); + QVERIFY (!fifo.takeDrainReady ().ready); +} + +void TestJttyTxStream::fifoDrainAfterResetUsesNewEpochAndTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + fifo.clear (22); + QVERIFY (!fifo.takeDrainReady ().ready); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 22)); + + for (int i = 0; i < 4; ++i) (void) fifo.pullSample (2); + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (22)); + QCOMPARE (drain.totalAtDrain, qint64 (2)); +} + +void TestJttyTxStream::fifoEpochBoundaryAfterNaturalDrainResetsTotal () +{ + JttyPcmFifo fifo {16}; + QVERIFY (fifo.enqueue (QVector<qint16> {1, 2, 3}, 21)); + for (int i = 0; i < 5; ++i) (void) fifo.pullSample (2); + + auto drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (21)); + QCOMPARE (drain.totalAtDrain, qint64 (3)); + + fifo.clear (22); + QVERIFY (fifo.enqueue (QVector<qint16> {4, 5}, 22)); + for (int i = 0; i < 4; ++i) (void) fifo.pullSample (2); + + drain = fifo.takeDrainReady (); + QVERIFY (drain.ready); + QCOMPARE (drain.epoch, qint64 (22)); + QCOMPARE (drain.totalAtDrain, qint64 (2)); +} + +void TestJttyTxStream::drainedPredicate () +{ + // Nothing queued yet => not drained. + QVERIFY (!jttyTxDrained (0, 0, 100, 0, 10)); + + // Real audio still to be pulled => not drained. + QVERIFY (!jttyTxDrained (3, 5, 50, 5, 10)); + + // All pulled but trailing silence has not yet covered the buffer depth. + QVERIFY (!jttyTxDrained (5, 5, 12, 5, 10)); // 12-5 = 7 < 10 + + // All pulled and trailing silence covers the buffer depth => drained. + QVERIFY (jttyTxDrained (5, 5, 15, 5, 10)); // 15-5 = 10 >= 10 + QVERIFY (jttyTxDrained (5, 5, 99, 5, 10)); +} + +void TestJttyTxStream::readDoesNotEmitDrainedDirectly () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (31); + queue.clear (epoch); + JttyTxStream s {queue}; + QVERIFY (s.initialize (QIODevice::ReadOnly, AudioDevice::Mono)); + QSignalSpy spy (&s, &JttyTxStream::drained); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + (void) readFrames (s, 3 + DEFAULT_GUARD); + QCOMPARE (spy.count (), 0); +} + +void TestJttyTxStream::timerEmitsDrainedEdge () +{ + TxAudioQueue queue; + auto const epoch = queueEpoch (41); + queue.clear (epoch); + JttyTxStream s {queue}; + QSignalSpy spy (&s, &JttyTxStream::drained); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + s.start (jttyRequest (41, 1), nullptr); + + // Serve the 3 real samples plus exactly the guard worth of trailing silence. + (void) readFrames (s, 3 + DEFAULT_GUARD); + QTRY_COMPARE (spy.count (), 1); + auto drain = qvariant_cast<TxAudioQueueDrainState> (spy.at (0).at (0)); + QCOMPARE (drain.epoch, epoch); + QCOMPARE (drain.total_at_drain, qint64 (3)); + + // Further silence must not re-emit (edge-triggered). + (void) readFrames (s, 1000); + QCOMPARE (spy.count (), 1); + + // A new message clears the drain edge; draining again emits once more. + QVERIFY (queue.enqueue (QVector<qint16> {9}, epoch).accepted); + (void) readFrames (s, 1 + DEFAULT_GUARD); + QTRY_COMPARE (spy.count (), 2); + drain = qvariant_cast<TxAudioQueueDrainState> (spy.at (1).at (0)); + QCOMPARE (drain.epoch, epoch); + QCOMPARE (drain.total_at_drain, qint64 (4)); + s.stop (); +} + +void TestJttyTxStream::drainedEmittedFromWorkerThread () +{ + // Integration test: drive the stream the way the app does, with the object + // moved onto a dedicated worker thread (m_audioThread in production). The + // drain timer is a parented child, so it must ride to the worker thread and + // tick there; a value-member timer could not be started cross-thread and + // drained() would never fire (this test would then time out). start() and the + // audio pull run on the worker thread; drained() must cross back to the + // main-thread receiver. + TxAudioQueue queue; + auto const epoch = queueEpoch (51); + queue.clear (epoch); + auto * stream = new JttyTxStream {queue}; + QPointer<JttyTxStream> streamWitness {stream}; + qint64 drainedSession {-1}; + qint64 drainedTotal {-1}; + int drainedCount {0}; + QObject receiver; + // Qt 5's QSignalSpy records through a direct connection, so explicitly queue + // cross-thread test state onto a main-thread receiver. + connect (stream, &JttyTxStream::drained, &receiver, + [&drainedSession, &drainedTotal, &drainedCount] + (TxAudioQueueDrainState drain) { + drainedSession = drain.epoch.value (); + drainedTotal = drain.total_at_drain; + ++drainedCount; + }, Qt::QueuedConnection); + + QVERIFY (queue.enqueue (QVector<qint16> {7, 7, 7}, epoch).accepted); + + QThread worker; + stream->moveToThread (&worker); + connect (&worker, &QThread::finished, stream, &QObject::deleteLater); + + // Queue before starting the worker so thread creation establishes the + // cross-thread handoff. + QMetaObject::invokeMethod (stream, [stream] { + stream->start (jttyRequest (51, 1), nullptr); + QByteArray buf ((3 + DEFAULT_GUARD) * 2, '\0'); + stream->read (buf.data (), buf.size ()); + }, Qt::QueuedConnection); + worker.start (); + + QTRY_COMPARE_WITH_TIMEOUT (drainedCount, 1, 2000); + QCOMPARE (drainedSession, qint64 (51)); + QCOMPARE (drainedTotal, qint64 (3)); + + // The stream owns timers that must stop and be destroyed on their thread. + QVERIFY (QMetaObject::invokeMethod ( + stream, "stop", Qt::BlockingQueuedConnection)); + worker.quit (); + QVERIFY (worker.wait (2000)); + QVERIFY (streamWitness.isNull ()); +} + +void TestJttyTxStream::sourceCommitUsesCurrentRealExtent () +{ + auto const snapshot = makeJttyTxStartSnapshot (jttyRequest (61, 7), 3); + QCOMPARE (snapshot.session_id.value (), qint64 (61)); + QCOMPARE (snapshot.generation.value (), qint64 (7)); + QCOMPARE (snapshot.mode, QString {"JTTY"}); + QCOMPARE (snapshot.sample_rate_hz, 48000); + QCOMPARE (snapshot.committed_end_sample, qint64 (3)); + QVERIFY (!snapshot.target_known); + QVERIFY (!snapshot.diagnostic.isEmpty ()); + + TxAudioQueue queue; + auto const epoch = queueEpoch (61); + queue.clear (epoch); + JttyTxStream stream {queue}; + QVERIFY (queue.enqueue (QVector<qint16> {1, 2, 3}, epoch).accepted); + TxEvidence::TxStartSnapshot committed; + int commitCount {0}; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&committed, &commitCount] (TxEvidence::TxStartSnapshot snapshot) { + committed = snapshot; + ++commitCount; + }); + + stream.start (jttyRequest (61, 7), nullptr); + QCOMPARE (commitCount, 1); + QCOMPARE (committed.committed_end_sample, qint64 (2)); + (void) readFrames (stream, 3 + DEFAULT_GUARD); + QCOMPARE (queue.progress ().served_samples, qint64 (3)); + stream.stop (); +} + +void TestJttyTxStream::staleQueueEpochDoesNotStart () +{ + TxAudioQueue queue; + auto const current = queueEpoch (81); + queue.clear (current); + QVERIFY (queue.enqueue (QVector<qint16> {7, 8, 9}, current).accepted); + + JttyTxStream stream {queue}; + TxEvidence::TxStartSnapshot committed; + int commitCount {0}; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&committed, &commitCount] (TxEvidence::TxStartSnapshot snapshot) { + committed = snapshot; + ++commitCount; + }); + stream.start (jttyRequest (80, 1), nullptr); + QVERIFY (!stream.isActive ()); + QCOMPARE (commitCount, 0); + + stream.start (jttyRequest (81, 2), nullptr); + QVERIFY (stream.isActive ()); + QCOMPARE (commitCount, 1); + QCOMPARE (committed.committed_end_sample, qint64 (2)); + stream.stop (); +} + +void TestJttyTxStream::sourceCommitIsEmittedOncePerStart () +{ + TxAudioQueue queue; + JttyTxStream stream {queue}; + QVector<TxEvidence::TxStartSnapshot> commits; + connect (&stream, &JttyTxStream::txSourceCommitted, &stream, + [&commits] (TxEvidence::TxStartSnapshot snapshot) {commits.append (snapshot);}); + + queue.clear (queueEpoch (71)); + stream.start (jttyRequest (71, 1), nullptr); + stream.start (jttyRequest (71, 1), nullptr); + QCOMPARE (commits.size (), 1); + QCOMPARE (commits.at (0).committed_end_sample, qint64 (-1)); + stream.stop (); + + queue.clear (queueEpoch (72)); + stream.start (jttyRequest (72, 2), nullptr); + QCOMPARE (commits.size (), 2); + QCOMPARE (commits.at (0).session_id.value (), qint64 (71)); + QCOMPARE (commits.at (1).session_id.value (), qint64 (72)); + QCOMPARE (commits.at (1).generation.value (), qint64 (2)); + stream.stop (); +} + +QTEST_MAIN (TestJttyTxStream) +#include "test_jtty_txstream.moc" diff --git a/tests/unit/jtty/test_jtty_windowed_decode.f90 b/tests/unit/jtty/test_jtty_windowed_decode.f90 new file mode 100644 index 00000000..19bb345f --- /dev/null +++ b/tests/unit/jtty/test_jtty_windowed_decode.f90 @@ -0,0 +1,160 @@ +program test_jtty_windowed_decode + + ! rjtty_sub_windowed bounds the scan to [istart0,istop] instead of the + ! whole buffer -- used by MainWindow::jttyDecodeAgainAt() for a WideGraph + ! click-driven re-decode. Two messages placed far apart in time: a window + ! covering only one message must find only that one; a window covering + ! both (or the unwindowed rjtty_sub) must find both; and decoded content + ! for a message fully inside its window must match the unwindowed result + ! exactly (windowing must not corrupt what it does decode). + + use iso_fortran_env, only: int16 + use jtty_fec, only: is13, TOTAL_K + use jtty_mdec, only: npending,pending_updates,discard_pending_updates + use jtty_mod, only: MAX_FRAMES + implicit none + + character(len=*), parameter :: msg_a='MAYBE YOU SHOULD HELP' + character(len=*), parameter :: msg_b='CLAUDE CO 3 MIN TRANSITION' + integer, parameter :: nsps=384 + integer, parameter :: frame_symbols=size(is13)+TOTAL_K + real, parameter :: dt_a=0.2, dt_b=40.0 + integer :: failures + integer :: first_start,second_start,first_samples,second_samples,total_samples + integer(int16), allocatable :: pcm(:) + character(len=80) :: decoded_a_full,decoded_a_windowed + + failures=0 + + call build_pair(pcm,total_samples,first_start,first_samples,second_start,second_samples) + + ! Baseline: unwindowed scan finds both messages. + call rjtty_sub(pcm,1,nsps,200,2800,1500.0,50.0) + call rjtty_sub(pcm,total_samples,nsps,200,2800,1500.0,50.0) + call expect(found(msg_a),'unwindowed: first message found',failures) + call expect(found(msg_b),'unwindowed: second message found',failures) + decoded_a_full=decoded_text(msg_a) + + ! Window covering only the first message: second must not appear. + call discard_pending_updates() + call rjtty_sub_windowed(pcm,1,nsps,200,2800,1500.0,50.0,1,1) + call rjtty_sub_windowed(pcm,first_start+first_samples+2*chunk(), & + nsps,200,2800,1500.0,50.0,1,first_start+first_samples+2*chunk()) + call expect(found(msg_a),'window on first message: first message found',failures) + call expect(.not.found(msg_b),'window on first message: second message absent',failures) + decoded_a_windowed=decoded_text(msg_a) + call expect(trim(decoded_a_windowed).eq.trim(decoded_a_full), & + 'windowed decode content matches unwindowed content',failures) + + ! Window covering only the second message: first must not appear. + call discard_pending_updates() + call rjtty_sub_windowed(pcm,1,nsps,200,2800,1500.0,50.0, & + max(1,second_start-2*chunk()),total_samples) + call rjtty_sub_windowed(pcm,total_samples,nsps,200,2800,1500.0,50.0, & + max(1,second_start-2*chunk()),total_samples) + call expect(.not.found(msg_a),'window on second message: first message absent',failures) + call expect(found(msg_b),'window on second message: second message found',failures) + + if(failures.ne.0) then + write(*,'(a,i0)') 'test_jtty_windowed_decode: failures=',failures + stop 1 + endif + write(*,'(a)') 'test_jtty_windowed_decode: all checks passed' + +contains + + integer function chunk() + integer :: nframe + nframe=59*nsps + chunk=nframe+nframe/4 + end function chunk + + subroutine build_pair(pcm,total_samples,first_start,first_samples, & + second_start,second_samples) + integer(int16), allocatable, intent(out) :: pcm(:) + integer, intent(out) :: total_samples,first_start,first_samples + integer, intent(out) :: second_start,second_samples + integer :: first_tones(MAX_FRAMES*frame_symbols) + integer :: second_tones(MAX_FRAMES*frame_symbols) + integer :: first_symbols,second_symbols,i,idx,pcm_val + real, allocatable :: first_wave(:),second_wave(:) + complex, allocatable :: complex_wave(:) + character(len=80) :: first_input,second_input + + first_input=msg_a + call genjtty(first_input,first_tones,first_symbols) + first_samples=first_symbols*nsps + first_start=max(1,nint(dt_a*12000.0)+1) + + second_input=msg_b + call genjtty(second_input,second_tones,second_symbols) + second_samples=second_symbols*nsps + second_start=max(1,nint(dt_b*12000.0)+1) + + total_samples=max(first_start+first_samples-1, & + second_start+second_samples-1)+frame_symbols*nsps + allocate(pcm(total_samples)) + pcm=0_int16 + + allocate(first_wave(first_samples),complex_wave(first_samples)) + call gen_jttywave(first_tones,first_symbols,nsps,2.0,12000.0,1500.0, & + complex_wave,first_wave,0,first_samples) + do i=1,first_samples + idx=first_start+i-1 + pcm_val=nint(14000.0*first_wave(i)) + pcm(idx)=int(max(-32767,min(32767,pcm_val)),int16) + enddo + deallocate(first_wave,complex_wave) + + allocate(second_wave(second_samples),complex_wave(second_samples)) + call gen_jttywave(second_tones,second_symbols,nsps,2.0,12000.0,1504.0, & + complex_wave,second_wave,0,second_samples) + do i=1,second_samples + idx=second_start+i-1 + pcm_val=nint(14000.0*second_wave(i)) + pcm(idx)=int(max(-32767,min(32767,pcm_val)),int16) + enddo + deallocate(second_wave,complex_wave) + end subroutine build_pair + + logical function found(message) + character(len=*), intent(in) :: message + integer :: i + found=.false. + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message)) found=.true. + enddo + end function found + + function decoded_text(message) result(text) + character(len=*), intent(in) :: message + character(len=80) :: text + integer :: i + text='' + do i=1,npending + if(trim(normalized(pending_updates(i)%decoded)).eq.trim(message)) & + text=normalized(pending_updates(i)%decoded) + enddo + end function decoded_text + + function normalized(value) result(result_value) + character(len=*), intent(in) :: value + character(len=80) :: result_value + integer :: i + result_value=adjustl(value) + do i=1,len_trim(result_value) + if(result_value(i:i).eq.'~') result_value(i:i)=' ' + enddo + end function normalized + + subroutine expect(condition,description,count) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + integer, intent(inout) :: count + if(.not.condition) then + count=count+1 + write(*,'(a)') 'FAIL: '//description + endif + end subroutine expect + +end program test_jtty_windowed_decode diff --git a/tests/unit/jtty/test_mmttyif.cpp b/tests/unit/jtty/test_mmttyif.cpp new file mode 100644 index 00000000..8333d6c9 --- /dev/null +++ b/tests/unit/jtty/test_mmttyif.cpp @@ -0,0 +1,265 @@ +#include <QtTest> + +#include <memory> + +#include <QCoreApplication> +#include <QHostAddress> +#include <QSignalSpy> +#include <QTcpServer> +#include <QTcpSocket> + +#include "widgets/MMTTYIF.hpp" + +namespace +{ + int constexpr maximumHeaderBytes {64}; + int constexpr maximumPayloadBytes {64 * 1024}; +} + +class TestMMTTYIF final + : public QObject +{ + Q_OBJECT + +private slots: + void init () + { + server_.reset (new QTcpServer); + // MMTTYIF connects to 127.0.0.1 (IPv4). Bind the same family so Windows + // does not leave the server on ::1 while the client dials IPv4. + QVERIFY (server_->listen (QHostAddress {QStringLiteral ("127.0.0.1")}, 0)); + QCoreApplication::processEvents (); + + interface_.reset (new MMTTYIF); + interface_->initialize (server_->serverPort ()); + + QTRY_VERIFY_WITH_TIMEOUT (server_->hasPendingConnections (), 5000); + peer_ = server_->nextPendingConnection (); + QVERIFY (peer_); + QTRY_VERIFY_WITH_TIMEOUT (interface_->isConnected (), 5000); + } + + void cleanup () + { + interface_.reset (); + peer_ = nullptr; + server_.reset (); + QCoreApplication::processEvents (); + } + + void parsesFragmentedFrame () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + + QVERIFY (writeToInterface ("<TXTEXT:11>HELLO")); + QTest::qWait (20); + QCOMPARE (text.count (), 0); + + QVERIFY (writeToInterface (" WORLD")); + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 1000); + QCOMPARE (text.at (0).at (0).toString (), QString {"HELLO WORLD"}); + } + + void dispatchesFragmentedTaggedTextBeforeStart () + { + QStringList events; + connect (interface_.get (), &MMTTYIF::app_tx_string, this, + [&events] (QString const& message) { events.append ("text:" + message); }); + connect (interface_.get (), &MMTTYIF::app_start_tx, this, + [&events] { events.append (QStringLiteral ("start")); }); + + QByteArray const payload {"[[JTTY:CALL_EXCH]] W9XYZ 7"}; + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (payload.size ()); + frame += '>'; + frame += payload; + int const split = frame.size () - 5; + + QVERIFY (writeToInterface (frame.left (split))); + QTest::qWait (20); + QVERIFY (events.isEmpty ()); + + QVERIFY (writeToInterface (frame.mid (split) + "<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (events.size (), 2, 1000); + QCOMPARE (events.at (0), QStringLiteral ("text:[[JTTY:CALL_EXCH]] W9XYZ 7")); + QCOMPARE (events.at (1), QStringLiteral ("start")); + } + + void parsesCoalescedFrames () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + + QVERIFY (writeToInterface ("<TXTEXT:5>A<B>C<XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QCOMPARE (text.at (0).at (0).toString (), QString {"A<B>C"}); + } + + void dispatchesControlCommands () + { + QSignalSpy stop {interface_.get (), &MMTTYIF::app_stop_tx}; + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy close {interface_.get (), &MMTTYIF::app_is_quitting}; + + QVERIFY (writeToInterface ("<XMIT:3>OFF<ABORT>ABORT<CLOSE>CLOSE")); + + QTRY_COMPARE_WITH_TIMEOUT (stop.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (abort.count (), 1, 1000); + QTRY_COMPARE_WITH_TIMEOUT (close.count (), 1, 1000); + } + + void delaysOutputCompleteUntilDrainReport () + { + QSignalSpy stop {interface_.get (), &MMTTYIF::app_stop_tx}; + peer_->readAll (); + + QVERIFY (writeToInterface ("<XMIT:3>OFF")); + QTRY_COMPARE_WITH_TIMEOUT (stop.count (), 1, 1000); + QTest::qWait (20); + QCOMPARE (peer_->bytesAvailable (), qint64 {0}); + + interface_->report_output_complete (); + QTRY_VERIFY_WITH_TIMEOUT (peer_->bytesAvailable () > 0, 1000); + QCOMPARE (peer_->readAll (), QByteArray {"<OUTPUTCOMPLETE>"}); + } + + void parsesFragmentedImplicitControl () + { + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy received {interface_.get (), &MMTTYIF::message_received}; + + QVERIFY (writeToInterface ("<ABORT>AB")); + QTRY_VERIFY_WITH_TIMEOUT (received.count () >= 1, 1000); + QCOMPARE (abort.count (), 0); + + QVERIFY (writeToInterface ("ORT")); + QTRY_COMPARE_WITH_TIMEOUT (abort.count (), 1, 1000); + } + + void recoversAfterInvalidLength () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QVERIFY (writeToInterface ("<TXTEXT:-1><TXTEXT:nope><XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (logs.count () >= 2, 1000); + } + + void acceptsMaximumDeclaredPayload () + { + QSignalSpy text {interface_.get (), &MMTTYIF::app_tx_string}; + QByteArray const payload (maximumPayloadBytes, 'a'); + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (payload.size ()); + frame += '>'; + frame += payload; + + QVERIFY (writeToInterface (frame)); + + QTRY_COMPARE_WITH_TIMEOUT (text.count (), 1, 2000); + QCOMPARE (text.at (0).at (0).toString (), QString (maximumPayloadBytes, 'A')); + } + + void rejectsOversizedDeclaredPayload () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray frame {"<TXTEXT:"}; + frame += QByteArray::number (maximumPayloadBytes + 1); + frame += "><XMIT:2>ON"; + QVERIFY (writeToInterface (frame)); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload length exceeds"), 1000); + } + + void rejectsSignedMaximumLength () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QVERIFY (writeToInterface ("<TXTEXT:2147483647><XMIT:2>ON")); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload length exceeds"), 1000); + } + + void rejectsOversizedUndeclaredPayload () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy abort {interface_.get (), &MMTTYIF::app_abort_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + QSignalSpy received {interface_.get (), &MMTTYIF::message_received}; + + QByteArray firstFragment {"<ABORT>"}; + firstFragment += QByteArray (maximumPayloadBytes / 2, 'A'); + QVERIFY (writeToInterface (firstFragment)); + QTRY_VERIFY_WITH_TIMEOUT (received.count () >= 1, 1000); + QCOMPARE (abort.count (), 0); + + QByteArray secondFragment (maximumPayloadBytes / 2 + 1, 'A'); + secondFragment += "<XMIT:2>ON"; + QVERIFY (writeToInterface (secondFragment)); + + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 2000); + QCOMPARE (abort.count (), 0); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "payload exceeds"), 1000); + } + + void rejectsOverlongIncompleteHeader () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray header {"<"}; + header += QByteArray (maximumHeaderBytes, 'A'); + QVERIFY (writeToInterface (header)); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "header exceeds"), 1000); + + QVERIFY (writeToInterface ("<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + } + + void rejectsOverlongTerminatedHeader () + { + QSignalSpy start {interface_.get (), &MMTTYIF::app_start_tx}; + QSignalSpy logs {interface_.get (), &MMTTYIF::log_message}; + + QByteArray header {"<"}; + header += QByteArray (maximumHeaderBytes - 1, 'A'); + header += '>'; + QVERIFY (writeToInterface (header)); + QTRY_VERIFY_WITH_TIMEOUT (hasLogContaining (logs, "header exceeds"), 1000); + + QVERIFY (writeToInterface ("<XMIT:2>ON")); + QTRY_COMPARE_WITH_TIMEOUT (start.count (), 1, 1000); + } + +private: + static bool hasLogContaining (QSignalSpy const& logs, QString const& text) + { + for (auto const& arguments : logs) { + if (arguments.at (0).toString ().contains (text)) return true; + } + return false; + } + + bool writeToInterface (QByteArray const& data) + { + if (!peer_ || peer_->write (data) != data.size ()) return false; + return !peer_->bytesToWrite () || peer_->waitForBytesWritten (1000); + } + + std::unique_ptr<QTcpServer> server_; + std::unique_ptr<MMTTYIF> interface_; + QTcpSocket * peer_ {nullptr}; +}; + +QTEST_GUILESS_MAIN (TestMMTTYIF) + +#include "test_mmttyif.moc" diff --git a/tests/unit/jtty/test_tbcc.f90 b/tests/unit/jtty/test_tbcc.f90 new file mode 100644 index 00000000..97fe50d1 --- /dev/null +++ b/tests/unit/jtty/test_tbcc.f90 @@ -0,0 +1,141 @@ +program test_tbcc + + ! Transition invariants across supported memories and JTTY candidate acceptance. + + use, intrinsic :: iso_fortran_env, only: real32, int32 + use tbcc + implicit none + + call expect_incoming_tones() + call expect_empty_and_tied_candidates() + call expect_encode_decode_roundtrip() + call expect_reserved_zero_bit_filters_candidates() + + print *, 'test_tbcc: all checks passed' + +contains + + subroutine expect_incoming_tones() + integer, parameter :: memories(5) = [9, 12, 10, 11, 9] + integer, parameter :: gray_tones(0:3) = [0, 1, 3, 2] + integer :: n, predecessor, bit, destination, register_value, expected + + do n = 1, size(memories) + call tbcc_init(memories(n)) + if (size(incoming_tones, 2) /= num_states) error stop 'incorrect transition table size' + do predecessor = 0, num_states-1 + do bit = 0, 1 + register_value = 2*predecessor + bit + destination = mod(register_value, num_states) + expected = gray_tones(2*mod(popcnt(iand(register_value, g0_poly)), 2) + & + mod(popcnt(iand(register_value, g1_poly)), 2)) + if (incoming_tones(predecessor/(num_states/2), destination) /= expected) & + error stop 'incoming tone differs from encoder polynomial parity' + end do + end do + end do + end subroutine expect_incoming_tones + + subroutine expect_empty_and_tied_candidates() + integer :: decoded(PAYLOAD_BITS) + real(real32) :: energies(0:3, TOTAL_K) + logical :: success + + call tbcc_init(9) + energies = 1.0_real32 + call tbcc_wava_fsk_decode(energies, 0, 2, decoded, success) + if (success .or. any(decoded /= 0)) error stop 'empty candidate list must fail cleanly' + + ! Equal branch metrics select the all-one circular path, which fails CRC. + call tbcc_wava_fsk_decode(energies, 4, 2, decoded, success) + if (success .or. any(decoded /= 0)) error stop 'tied candidate CRC rejection changed' + end subroutine expect_empty_and_tied_candidates + + subroutine expect_encode_decode_roundtrip() + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + real(real32) :: tone_energies(0:3, TOTAL_K) + logical :: success + integer :: i, t + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) ! deterministic, not all-zero + end do + + call tbcc_encode(payload, tone_symbols) + + ! Noiseless channel: all of a symbol's energy on the transmitted tone. + tone_energies = 0.0_real32 + do t = 1, TOTAL_K + tone_energies(tone_symbols(t), t) = 1.0_real32 + end do + + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success) + if (.not. success) then + print *, 'test_tbcc: noiseless decode failed' + error stop 1 + end if + if (any(decoded /= payload)) then + print *, 'test_tbcc: noiseless decode mismatch' + error stop 1 + end if + end subroutine expect_encode_decode_roundtrip + + subroutine expect_reserved_zero_bit_filters_candidates() + integer(int32) :: payload(PAYLOAD_BITS), decoded(PAYLOAD_BITS) + integer(int32) :: tone_symbols(TOTAL_K) + real(real32) :: tone_energies(0:3, TOTAL_K) + logical :: success + integer :: i, t, one_bit_pos + + call tbcc_init(9) + + do i = 1, PAYLOAD_BITS + payload(i) = mod(i, 2) + end do + ! A payload-bit position this payload sets to 1, so requiring it to be + ! 0 must reject this exact (otherwise noiseless-decodable) codeword. + one_bit_pos = 0 + do i = 1, PAYLOAD_BITS + if (payload(i) == 1) then + one_bit_pos = i + exit + end if + end do + if (one_bit_pos == 0) then + print *, 'test_tbcc: test payload unexpectedly all-zero' + error stop 1 + end if + + call tbcc_encode(payload, tone_symbols) + tone_energies = 0.0_real32 + do t = 1, TOTAL_K + tone_energies(tone_symbols(t), t) = 1.0_real32 + end do + + ! Control case: no reserved_zero_bit, decode succeeds as above. + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success) + if (.not. success) then + print *, 'test_tbcc: control decode (no reserved_zero_bit) failed' + error stop 1 + end if + + ! With the filter on a bit this payload actually sets to 1, the only + ! codeword consistent with these noiseless tone energies fails the + ! filter, so decoding must now report failure. + decoded = huge(0_int32) + call tbcc_wava_fsk_decode(tone_energies, 4, 2, decoded, success, & + reserved_zero_bit=one_bit_pos) + if (success) then + print *, 'test_tbcc: reserved_zero_bit did not filter the candidate' + error stop 1 + end if + if (any(decoded /= 0_int32)) then + print *, 'test_tbcc: failed decode did not clear its payload' + error stop 1 + end if + end subroutine expect_reserved_zero_bit_filters_candidates + +end program test_tbcc diff --git a/tests/unit/legacy72/CMakeLists.txt b/tests/unit/legacy72/CMakeLists.txt new file mode 100644 index 00000000..10f31905 --- /dev/null +++ b/tests/unit/legacy72/CMakeLists.txt @@ -0,0 +1,5 @@ +add_executable (test_packjt_legacy72 test_packjt_legacy72.f90) +target_include_directories (test_packjt_legacy72 PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_packjt_legacy72) + +add_test (NAME test_packjt_legacy72 COMMAND test_packjt_legacy72) diff --git a/tests/unit/legacy72/test_packjt_legacy72.f90 b/tests/unit/legacy72/test_packjt_legacy72.f90 new file mode 100644 index 00000000..abf118c2 --- /dev/null +++ b/tests/unit/legacy72/test_packjt_legacy72.f90 @@ -0,0 +1,107 @@ +program test_packjt_legacy72 + + use packjt, only: packmsg, unpackmsg + implicit none + + integer :: ntests + + ntests=0 + call expect_control_suffix_falls_back(ntests) + call expect_type2_suffix_round_trip(ntests) + call expect_rr73_is_encoded_as_grid(ntests) + + write(*,1000) ntests +1000 format('Legacy 72-bit codec tests passed: ',i0) + +contains + + subroutine expect_control_suffix_falls_back(ntests) + integer, intent(inout) :: ntests + character(len=22) :: decoded,message + integer :: itype,symbols(12) + + message=' ' + message(1:1)='/' + message(2:2)=achar(1) + + call packmsg(message,symbols,itype) + call unpackmsg(symbols,decoded) + + if(itype.ne.6) then + write(*,1010) itype +1010 format('Control suffix returned type ',i0,' instead of free text') + error stop 1 + endif + if(any(symbols.lt.0) .or. any(symbols.gt.63)) then + write(*,1020) +1020 format('Control suffix produced an out-of-range symbol') + error stop 1 + endif + if(trim(decoded).ne.'/') then + write(*,1030) trim(decoded) +1030 format('Control suffix decoded as "',a,'" instead of "/"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_control_suffix_falls_back + + subroutine expect_type2_suffix_round_trip(ntests) + integer, intent(inout) :: ntests + character(len=*), parameter :: expected='CQ KA1ABC/VE6 -22' + character(len=22) :: decoded,message + integer :: itype,symbols(12) + + message=expected + call packmsg(message,symbols,itype) + call unpackmsg(symbols,decoded) + + if(itype.ne.5) then + write(*,1040) itype +1040 format('Type 2 suffix returned type ',i0,' instead of 5') + error stop 1 + endif + if(any(symbols.lt.0) .or. any(symbols.gt.63)) then + write(*,1050) +1050 format('Type 2 suffix produced an out-of-range symbol') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1060) trim(decoded),expected +1060 format('Type 2 suffix decoded as "',a,'" instead of "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_type2_suffix_round_trip + + subroutine expect_rr73_is_encoded_as_grid(ntests) + integer, intent(inout) :: ntests + character(len=*), parameter :: expected='K1ABC W9XYZ RR73' + character(len=22) :: decoded,message + integer :: itype,symbols(12) + + message=expected + call packmsg(message,symbols,itype) + call unpackmsg(symbols,decoded) + + if(itype.ne.1) then + write(*,1070) itype +1070 format('RR73 returned type ',i0,' instead of a standard message') + error stop 1 + endif + if(any(symbols.lt.0) .or. any(symbols.gt.63)) then + write(*,1080) +1080 format('RR73 produced an out-of-range symbol') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1090) trim(decoded),expected +1090 format('RR73 decoded as "',a,'" instead of "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_rr73_is_encoded_as_grid + +end program test_packjt_legacy72 diff --git a/tests/unit/logbook/CMakeLists.txt b/tests/unit/logbook/CMakeLists.txt new file mode 100644 index 00000000..611136de --- /dev/null +++ b/tests/unit/logbook/CMakeLists.txt @@ -0,0 +1,10 @@ +add_executable (test_logbook_adif + test_logbook_adif.cpp + ${CMAKE_SOURCE_DIR}/logbook/AdifQso.cpp +) +target_link_libraries (test_logbook_adif Qt5::Test) +add_test (NAME test_logbook_adif COMMAND test_logbook_adif) + +add_executable (test_worked_before_load_state test_worked_before_load_state.cpp) +target_link_libraries (test_worked_before_load_state Qt5::Test) +add_test (NAME test_worked_before_load_state COMMAND test_worked_before_load_state) diff --git a/tests/unit/logbook/test_logbook_adif.cpp b/tests/unit/logbook/test_logbook_adif.cpp new file mode 100644 index 00000000..36878226 --- /dev/null +++ b/tests/unit/logbook/test_logbook_adif.cpp @@ -0,0 +1,254 @@ +#include <QtTest> +#include <QByteArray> +#include <QDateTime> +#include <QString> + +#include "logbook/AdifQso.hpp" + +namespace +{ + //! QSO inputs for AdifQso::to_adif with sensible defaults; tests override + //! only the fields they exercise. + struct Qso + { + QString call = "K1ABC"; + QString grid = "FN42"; + QString mode = "FT8"; + QString rptSent = "-10"; + QString rptRcvd = "-12"; + QDateTime on = QDateTime (QDate (2024, 1, 2), QTime (3, 4, 5), Qt::UTC); + QDateTime off = QDateTime (QDate (2024, 1, 2), QTime (3, 5, 6), Qt::UTC); + QString band = "20m"; + QString comments; + QString name; + QString freq = "14.074000"; + QString myCall = "W1AW"; + QString myGrid = "FN31"; + QString txPower; + QString op; + QString xSent; + QString xRcvd; + QString prop; + QString sat; + QString satMode; + QString freqRx; + AdifQso::Contest contest = AdifQso::Contest::None; + }; + + QByteArray run (Qso const& q) + { + return AdifQso::to_adif (q.call, q.grid, q.mode, q.rptSent, q.rptRcvd, q.on, q.off, + q.band, q.comments, q.name, q.freq, q.myCall, q.myGrid, + q.txPower, q.op, q.xSent, q.xRcvd, q.prop, q.sat, q.satMode, + q.freqRx, q.contest); + } +} + +#define VERIFY_HAS(rec, sub) \ + QVERIFY2 ((rec).contains (QByteArray (sub)), \ + qPrintable (QStringLiteral ("missing \"%1\" in: %2") \ + .arg (QString::fromUtf8 (QByteArray (sub))) \ + .arg (QString::fromUtf8 (rec)))) + +#define VERIFY_LACKS(rec, sub) \ + QVERIFY2 (!(rec).contains (QByteArray (sub)), \ + qPrintable (QStringLiteral ("unexpected \"%1\" in: %2") \ + .arg (QString::fromUtf8 (QByteArray (sub))) \ + .arg (QString::fromUtf8 (rec)))) + +class TestLogbookAdif : public QObject +{ + Q_OBJECT + +private slots: + void record_structure () + { + auto r = run (Qso {}); + QVERIFY2 (r.startsWith ("<call:5>K1ABC"), r.constData ()); // no leading space on first field + VERIFY_HAS (r, "<gridsquare:4>FN42"); + VERIFY_HAS (r, "<mode:3>FT8"); + VERIFY_HAS (r, "<rst_sent:3>-10"); + VERIFY_HAS (r, "<rst_rcvd:3>-12"); + VERIFY_HAS (r, "<qso_date:8>20240102"); + VERIFY_HAS (r, "<time_on:6>030405"); + VERIFY_HAS (r, "<qso_date_off:8>20240102"); + VERIFY_HAS (r, "<time_off:6>030506"); + VERIFY_HAS (r, "<band:3>20m"); + VERIFY_HAS (r, "<freq:9>14.074000"); + VERIFY_HAS (r, "<station_callsign:4>W1AW"); + VERIFY_HAS (r, "<my_gridsquare:4>FN31"); + VERIFY_LACKS (r, "<eor>"); // terminator is the caller's responsibility + } + + void mfsk_modes_use_submode () + { + Qso q; q.mode = "FT4"; + VERIFY_HAS (run (q), "<mode:4>MFSK <submode:3>FT4"); + q.mode = "FST4"; + VERIFY_HAS (run (q), "<mode:4>MFSK <submode:4>FST4"); + q.mode = "Q65"; + VERIFY_HAS (run (q), "<mode:4>MFSK <submode:3>Q65"); + } + + void empty_gridsquare_still_emitted () + { + Qso q; q.grid = ""; + VERIFY_HAS (run (q), "<gridsquare:0>"); + } + + void empty_optionals_omitted () + { + auto r = run (Qso {}); // comments/name/op/txPower/prop/sat all empty by default + VERIFY_LACKS (r, "<comment:"); + VERIFY_LACKS (r, "<name:"); + VERIFY_LACKS (r, "<operator:"); + VERIFY_LACKS (r, "<tx_pwr:"); + VERIFY_LACKS (r, "<prop_mode:"); + VERIFY_LACKS (r, "<sat_name:"); + VERIFY_LACKS (r, "<sat_mode:"); + VERIFY_LACKS (r, "<freq_rx:"); + } + + void adi_output_replaces_non_ascii_text () + { + Qso q; + q.name = QString {"Jos"} + QChar {0x00e9}; + q.comments = QString {"M"} + QChar {0x00fc} + "ller " + QChar {0x0141}; + auto r = run (q); + VERIFY_HAS (r, "<comment:8>M?ller ?"); + VERIFY_HAS (r, "<name:4>Jos?"); + for (auto ch : r) + { + QVERIFY2 (ch >= ' ' && ch <= '~', r.constData ()); + } + } + + void free_text_delimiters_stripped () + { + Qso q; + q.comments = "hello <eor> there"; // 15 chars after removing '<' and '>' + q.name = "a>b<c"; + auto r = run (q); + VERIFY_HAS (r, "<comment:15>hello eor there"); + VERIFY_HAS (r, "<name:3>abc"); + VERIFY_LACKS (r, "<eor>"); + } + + void structured_field_delimiters_stripped () + { + Qso q; + q.call = "<K1ABC>"; + q.grid = "<FN42>"; + auto r = run (q); + VERIFY_HAS (r, "<call:5>K1ABC"); + VERIFY_HAS (r, "<gridsquare:4>FN42"); + VERIFY_LACKS (r, "<K1ABC>"); + VERIFY_LACKS (r, "<FN42>"); + } + + void sent_serial_exchange () + { + Qso q; q.xSent = "599 001"; + VERIFY_HAS (run (q), "<stx:3>001"); + } + + void sent_non_serial_exchange_kept () + { + Qso q; q.xSent = "2A NC"; q.contest = AdifQso::Contest::FieldDay; + VERIFY_HAS (run (q), "<STX_STRING:5>2A NC"); + } + + void sent_exchange_delimiters_stripped () + { + Qso q; q.xSent = "2A <eor> NC"; + auto r = run (q); + VERIFY_HAS (r, "<STX_STRING:9>2A eor NC"); + VERIFY_LACKS (r, "<eor>"); + } + + void sent_unknown_multiword_numeric_exchange_kept_as_string () + { + Qso q; q.xSent = "ABC DEF 123"; + auto r = run (q); + VERIFY_HAS (r, "<STX_STRING:11>ABC DEF 123"); + VERIFY_LACKS (r, "<stx:"); + } + + void sent_numeric_prefixed_multiword_exchange_kept_as_string () + { + Qso q; q.xSent = "59123 JN88 EXTRA"; + auto r = run (q); + VERIFY_HAS (r, "<STX_STRING:16>59123 JN88 EXTRA"); + VERIFY_LACKS (r, "<stx:"); + } + + void received_serial_exchange () + { + Qso q; q.xRcvd = "599 042"; + VERIFY_HAS (run (q), "<srx:3>042"); + } + + void received_eu_vhf_strips_report () + { + Qso q; q.xRcvd = "59123 JN88"; // report 59 + serial 123 + VERIFY_HAS (run (q), "<srx:3>123"); + } + + void received_field_day_exchange () + { + Qso q; q.xRcvd = "2A NC"; q.contest = AdifQso::Contest::FieldDay; + auto r = run (q); + VERIFY_HAS (r, "<contest_id:14>ARRL-FIELD-DAY"); + VERIFY_HAS (r, "<SRX_STRING:5>2A NC"); + VERIFY_HAS (r, "<class:2>2A"); + VERIFY_HAS (r, "<arrl_sect:2>NC"); + } + + void received_rtty_state () + { + Qso q; q.xRcvd = "599 MA"; q.contest = AdifQso::Contest::Rtty; + VERIFY_HAS (run (q), "<state:2>MA"); + } + + void received_multiword_exchange_kept () + { + Qso q; q.xRcvd = "59 123 JN88"; + VERIFY_HAS (run (q), "<SRX_STRING:11>59 123 JN88"); + VERIFY_LACKS (run (q), "<srx:"); + } + + void received_exchange_delimiters_stripped () + { + Qso q; q.xRcvd = "ABC <eor> DEF"; + auto r = run (q); + VERIFY_HAS (r, "<SRX_STRING:11>ABC eor DEF"); + VERIFY_LACKS (r, "<eor>"); + } + + void received_unknown_multiword_numeric_exchange_kept_as_string () + { + Qso q; q.xRcvd = "ABC DEF 123"; + auto r = run (q); + VERIFY_HAS (r, "<SRX_STRING:11>ABC DEF 123"); + VERIFY_LACKS (r, "<srx:"); + } + + void received_numeric_prefixed_multiword_exchange_kept_as_string () + { + Qso q; q.xRcvd = "59123 JN88 EXTRA"; + auto r = run (q); + VERIFY_HAS (r, "<SRX_STRING:16>59123 JN88 EXTRA"); + VERIFY_LACKS (r, "<srx:"); + } + + void received_single_word_not_emitted () + { + Qso q; q.xRcvd = "JN88"; // bare grid, handled as gridsquare elsewhere + auto r = run (q); + VERIFY_LACKS (r, "<srx:"); + VERIFY_LACKS (r, "<SRX_STRING:"); + } +}; + +QTEST_GUILESS_MAIN (TestLogbookAdif) +#include "test_logbook_adif.moc" diff --git a/tests/unit/logbook/test_worked_before_load_state.cpp b/tests/unit/logbook/test_worked_before_load_state.cpp new file mode 100644 index 00000000..e1ce8f8d --- /dev/null +++ b/tests/unit/logbook/test_worked_before_load_state.cpp @@ -0,0 +1,69 @@ +#include <QtTest> + +#include "logbook/WorkedBeforeLoadState.hpp" + +class TestWorkedBeforeLoadState final : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void starts_first_reload (); + void coalesces_repeated_reload_requests (); + void keeps_completion_active_for_reentrant_reload (); + void starts_a_fresh_reload_after_idle (); +}; + +void TestWorkedBeforeLoadState::starts_first_reload () +{ + WorkedBeforeLoadState state; + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Start); + QVERIFY (state.active ()); +} + +void TestWorkedBeforeLoadState::coalesces_repeated_reload_requests () +{ + WorkedBeforeLoadState state; + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Start); + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Coalesced); + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Coalesced); + + state.begin_completion (); + QCOMPARE (state.finish_completion (), WorkedBeforeLoadState::CompletionResult::Restart); + QVERIFY (state.active ()); + + state.begin_completion (); + QCOMPARE (state.finish_completion (), WorkedBeforeLoadState::CompletionResult::Idle); + QVERIFY (!state.active ()); +} + +void TestWorkedBeforeLoadState::keeps_completion_active_for_reentrant_reload () +{ + WorkedBeforeLoadState state; + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Start); + state.begin_completion (); + QVERIFY (state.active ()); + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Coalesced); + QCOMPARE (state.finish_completion (), WorkedBeforeLoadState::CompletionResult::Restart); + QVERIFY (state.active ()); +} + +void TestWorkedBeforeLoadState::starts_a_fresh_reload_after_idle () +{ + WorkedBeforeLoadState state; + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Start); + state.begin_completion (); + QCOMPARE (state.finish_completion (), WorkedBeforeLoadState::CompletionResult::Idle); + QVERIFY (!state.active ()); + + QCOMPARE (state.request_reload (), WorkedBeforeLoadState::ReloadResult::Start); + QVERIFY (state.active ()); +} + +QTEST_GUILESS_MAIN (TestWorkedBeforeLoadState) + +#include "test_worked_before_load_state.moc" diff --git a/tests/unit/map65/CMakeLists.txt b/tests/unit/map65/CMakeLists.txt new file mode 100644 index 00000000..88064d64 --- /dev/null +++ b/tests/unit/map65/CMakeLists.txt @@ -0,0 +1,22 @@ +add_executable (test_map65_decode_display_filter + test_map65_decode_display_filter.cpp + ${CMAKE_SOURCE_DIR}/map65/map65_decode_display_filter.cpp +) +target_include_directories (test_map65_decode_display_filter PRIVATE ${CMAKE_SOURCE_DIR}/map65) +target_link_libraries (test_map65_decode_display_filter Qt5::Test) +add_test (NAME test_map65_decode_display_filter COMMAND test_map65_decode_display_filter) + +add_executable (test_map65_half_symbol_scheduler + test_map65_half_symbol_scheduler.cpp +) +target_include_directories (test_map65_half_symbol_scheduler PRIVATE ${CMAKE_SOURCE_DIR}/map65) +target_link_libraries (test_map65_half_symbol_scheduler Qt5::Test) +add_test (NAME test_map65_half_symbol_scheduler COMMAND test_map65_half_symbol_scheduler) + +add_executable (test_map65_runtime_paths + test_map65_runtime_paths.cpp + ${CMAKE_SOURCE_DIR}/map65/runtime_paths.cpp +) +target_include_directories (test_map65_runtime_paths PRIVATE ${CMAKE_SOURCE_DIR}/map65) +target_link_libraries (test_map65_runtime_paths Qt5::Test) +add_test (NAME test_map65_runtime_paths COMMAND test_map65_runtime_paths) diff --git a/tests/unit/map65/decode_history/CMakeLists.txt b/tests/unit/map65/decode_history/CMakeLists.txt new file mode 100644 index 00000000..6c8dc65d --- /dev/null +++ b/tests/unit/map65/decode_history/CMakeLists.txt @@ -0,0 +1,18 @@ +# Compile the production control flow against deterministic DSP boundaries. +# Keep replacement module files out of the production module directory. +add_executable (test_map65_decode_history + decode_history_stubs.f90 + test_map65_decode_history.f90 + ${CMAKE_SOURCE_DIR}/map65/libm65/map65a.f90 + ${CMAKE_SOURCE_DIR}/map65/libm65/getdphi.f90) +target_include_directories (test_map65_decode_history BEFORE PRIVATE + ${CMAKE_CURRENT_BINARY_DIR} + ${PROJECT_BINARY_DIR}/map65/libm65) +target_link_libraries (test_map65_decode_history PRIVATE m65impl) +target_compile_options (test_map65_decode_history PRIVATE + $<$<COMPILE_LANG_AND_ID:Fortran,GNU>:-fcheck=bounds>) +set_source_files_properties (decode_history_stubs.f90 PROPERTIES + COMPILE_OPTIONS "$<$<COMPILE_LANG_AND_ID:Fortran,GNU>:-Wno-unused-dummy-argument>") +add_test (NAME test_map65_decode_history COMMAND test_map65_decode_history) +set_tests_properties (test_map65_decode_history PROPERTIES + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} TIMEOUT 30) diff --git a/tests/unit/map65/decode_history/decode_history_stubs.f90 b/tests/unit/map65/decode_history/decode_history_stubs.f90 new file mode 100644 index 00000000..9582e19a --- /dev/null +++ b/tests/unit/map65/decode_history/decode_history_stubs.f90 @@ -0,0 +1,159 @@ +! These stand-ins supply one successful signal per mode. The production +! map65a loop owns all JT65 suppression and both modes' history resets. +module decode_history_observations + implicit none + integer :: jt65_attempts = 0, q65_successes = 0 + integer :: phase_attempts(0:12) = 0 + integer :: summary_count = 0, fitted_phase = -999 + logical :: phase_has_signal(0:12) = .true. +end module + +module stdout_channel_mod + use decode_history_observations + implicit none +contains + subroutine write_stdout(line) + character(len=*), intent(in) :: line + if (index(line, '!Best-fit Dphi =') == 1) then + summary_count = summary_count + 1 + read(line(index(line, '=')+1:), *) fitted_phase + endif + end subroutine +end module + +module wideband_sync + implicit none + integer, parameter :: MAX_CANDIDATES = 50 + integer :: nkhz_center + type candidate + real :: snr, f, xdt, pol + integer :: ipol, iflip, indx + end type +contains + subroutine init_wideband_sync() + end subroutine + + subroutine get_candidates(ss, savg, xpol, jz, nfa, nfb, nts_jt65, nts_q65, cand, ncand) + use npar_ptrs_mod, only: nfft_active + real, intent(in) :: ss(4,322,nfft_active), savg(4,nfft_active) + logical, intent(in) :: xpol + integer, intent(in) :: jz, nfa, nfb, nts_jt65, nts_q65 + type(candidate), intent(out) :: cand(MAX_CANDIDATES) + integer, intent(out) :: ncand + ncand = 1 + ! With nfcal=-1270, this places the Q65 signal at the zero-kHz cursor. + cand(1) = candidate(10.0, 48.00046, 0.0, 0.0, 1, 0, 1) + end subroutine +end module + +module ccf65_legacy_mod + implicit none +contains + subroutine ccf65(ss_plane, nhsym, ssmax, sync1, ipol1, jpz, dt1, flipk, & + syncshort, snr2, ipol2, dt2) + real, intent(in) :: ss_plane(4,322), ssmax + integer, intent(in) :: nhsym, jpz + real, intent(out) :: sync1, dt1, flipk, syncshort, snr2, dt2 + integer, intent(out) :: ipol1, ipol2 + sync1 = 10.0 + dt1 = 0.0 + flipk = 1.0 + syncshort = -99.0 + snr2 = 0.0 + dt2 = 0.0 + ipol1 = 1 + ipol2 = 1 + end subroutine +end module + +module decode1a_mod + use iso_fortran_env, only: real64 + use decode_history_observations + implicit none +contains + subroutine decode1a(dd,newdat,f0,nflip,mode65,nfsample,xpol, & + mycall,hiscall,hisgrid,neme,ndepth,nqd,dphi,ndphi, & + nutc,nkhz,ndf,ipol,ntol,sync2,a,dt,pol,nkv,nhist,nsum,nsave,qual,decoded) + use npar_ptrs_mod, only: nsmax_active + real, intent(in) :: dd(4,nsmax_active), dphi + real(real64), intent(in) :: f0 + integer, intent(in) :: nflip, mode65, nfsample, neme, ndepth, nqd, ndphi, nutc, nkhz, ndf, ntol + logical, intent(in) :: xpol + character(len=12), intent(in) :: mycall, hiscall + character(len=6), intent(in) :: hisgrid + integer, intent(inout) :: newdat, ipol, nkv, nhist, nsum, nsave + real, intent(inout) :: sync2, a(5), dt, pol, qual + character(len=22), intent(out) :: decoded + integer :: trial + newdat = 0 + decoded = ' ' + if (mode65 == 0) return + jt65_attempts = jt65_attempts + 1 + trial = nint(dphi * 57.2957795 / 30.0) + if (ndphi == 1) then + phase_attempts(trial) = phase_attempts(trial) + 1 + if (.not. phase_has_signal(trial)) return + endif + decoded = 'K1ABC W9XYZ FN42' + sync2 = 100.0 + a = 0.0 + dt = 0.0 + pol = 0.0 + qual = 5.0 + 4.0*sin(dphi) + nkv = 1 + nhist = 0 + nsum = 0 + nsave = 0 + ipol = 1 + end subroutine +end module + +module q65b_mod + use iso_fortran_env, only: real64 + use decode_history_observations + implicit none +contains + subroutine q65b(nutc,nqd,nxant,fcenter,nfcal,nfsample,ikhz,mousedf,ntol,xpol,configured_dphi_deg, & + mycall,mygrid,hiscall,hisgrid,mode_q65,f0,fqso,newdat,nagain,max_drift,ndop00,idec,cursor_fallback) + use decodes_mod, only: ldecoded + use q65_decode, only: nsnr0 + integer, intent(in) :: nutc,nqd,nxant,nfcal,nfsample,ikhz,mousedf,ntol,mode_q65 + integer, intent(in) :: newdat,nagain,max_drift,ndop00,configured_dphi_deg + real(real64), intent(in) :: fcenter,f0 + real, intent(in) :: fqso + logical, intent(in) :: xpol + logical, optional, intent(in) :: cursor_fallback + character(len=12), intent(in) :: mycall,hiscall + character(len=6), intent(in) :: mygrid,hisgrid + integer, intent(out) :: idec + nsnr0 = -99 + idec = -1 + ! Model q65b's successful-bin guard, not its signal processing. This + ! observes whether the caller retained or discarded the Q65 history. + if (ldecoded(1)) return + ldecoded(1) = .true. + q65_successes = q65_successes + 1 + nsnr0 = -10 + idec = 1 + end subroutine +end module + +module display_mod + implicit none +contains + subroutine display(nkeep, ftol) + integer, intent(in) :: nkeep + real, intent(in) :: ftol + end subroutine +end module + +module sec0_mod + implicit none +contains + subroutine sec0(mode, t) + integer, intent(in) :: mode + real, intent(out) :: t + ! The tests cover state transitions, not elapsed-time abort policy. + t = 0.0 + end subroutine +end module diff --git a/tests/unit/map65/decode_history/test_map65_decode_history.f90 b/tests/unit/map65/decode_history/test_map65_decode_history.f90 new file mode 100644 index 00000000..eb5ce18c --- /dev/null +++ b/tests/unit/map65/decode_history/test_map65_decode_history.f90 @@ -0,0 +1,90 @@ +program test_map65_decode_history + use iso_fortran_env, only: real64 + use npar_ptrs_mod, only: nfft_active, nsmax_active, t_start, manualDecodeFlag, active_input_generation + use datcom_ptrs_mod, only: ss_old, savg_old + use decodes_mod, only: nhsym1, nhsym2 + use map65a_mod, only: map65a + use decode_history_observations + implicit none + real, allocatable :: samples(:,:) + integer :: unit, before_jt65, before_q65 + + ! Only the center bin has signal power; DSP stand-ins never read samples. + nfft_active = 1024 + nsmax_active = 1 + allocate(samples(4,nsmax_active), ss_old(4,322,nfft_active), savg_old(4,nfft_active)) + samples = 0.0 + ss_old = 1.0 + savg_old = 1.0 + savg_old(1,nfft_active/2+1) = 10.0 + nhsym1 = 280 + nhsym2 = 302 + manualDecodeFlag = 0 + do unit = 12, 27 + open(unit, status='scratch') + enddo + close(23) + + active_input_generation = 1 + call run_pass(nhsym1, 0, 0) + call require(jt65_attempts == 1 .and. q65_successes == 1, 'early pass decodes both signals') + call run_pass(nhsym2, 0, 0) + call require(jt65_attempts == 1 .and. q65_successes == 1, 'final pass retains early successes') + + jt65_attempts = 0 + q65_successes = 0 + call run_pass(nhsym2, 1, 1) + call require(all(phase_attempts == 1), 'each JT65 trial remains eligible after an earlier success') + call require(jt65_attempts == 13, 'JT65 runs once per trial, without replaying prior successes') + call require(q65_successes == 1, 'unchanged Q65 input is decoded once across phase trials') + call require(summary_count == 1 .and. fitted_phase == 90, 'later better trials determine the fitted phase') + + ! A second calibration must not inherit quality scores from the first. + phase_has_signal = .false. + phase_has_signal(6) = .true. + phase_attempts = 0 + call run_pass(nhsym2, 1, 1) + call require(all(phase_attempts == 1), 'unsuccessful trials remain eligible in a new calibration') + call require(summary_count == 2 .and. abs(fitted_phase) == 180, 'missing trials do not retain old quality scores') + + before_jt65 = jt65_attempts + before_q65 = q65_successes + active_input_generation = 2 + call run_pass(nhsym1, 0, 0) + call require(jt65_attempts == before_jt65+1 .and. q65_successes == before_q65+1, & + 'next receive period makes both frequencies eligible') + active_input_generation = 3 + call run_pass(nhsym1, 0, 0) + call require(jt65_attempts == before_jt65+2 .and. q65_successes == before_q65+2, & + 'next early pass resets history even without a preceding final pass') + call run_pass(nhsym2, 0, 0) + call require(jt65_attempts == before_jt65+2 .and. q65_successes == before_q65+2, & + 'final pass retains successes after a skipped-period boundary') + print '(a)', 'MAP65 decode history tests passed.' + +contains + subroutine run_pass(half_symbols, again, find_phase) + integer, intent(in) :: half_symbols, again, find_phase + integer :: newdat, utc, done, ndphi, mcall3b, nsum, nsave + newdat = 1 + utc = 1200 + int(active_input_generation) + done = 0 + ndphi = find_phase + mcall3b = 0 + nsum = 0 + nsave = 0 + call system_clock(t_start) + call map65a(samples,newdat,utc,144.0_real64,100,0,0,0,0,0,again,done,0,ndphi,0, & + -1270,20,mcall3b,nsum,nsave,0,'K1ABC ','FN42 ',0,3,0, & + 'W9XYZ ','EN50 ',half_symbols,96000,0,1,11,0) + end subroutine + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + endif + end subroutine +end program diff --git a/tests/unit/map65/test_map65_astro.f90 b/tests/unit/map65/test_map65_astro.f90 new file mode 100644 index 00000000..275106d7 --- /dev/null +++ b/tests/unit/map65/test_map65_astro.f90 @@ -0,0 +1,62 @@ +program test_map65_astro + use iso_fortran_env, only: real64 + use astro_mod, only: astro, nt144 + implicit none + + integer :: ntsky_144, ntsky_1296 + real :: db_moon_144, degradation_144 + real :: db_moon_1296, degradation_1296 + real(real64) :: expected_tsky, expected_degradation + + call run_astro(144, ntsky_144, db_moon_144, degradation_144) + call require(any(int(nt144) == ntsky_144), & + '144 MHz sky temperature comes from the lookup table') + + call run_astro(1296, ntsky_1296, db_moon_1296, degradation_1296) + expected_tsky = (real(ntsky_144, real64) - 2.7_real64) * & + (144.0_real64 / 1296.0_real64)**2.6_real64 + 2.7_real64 + call require(ntsky_1296 == nint(expected_tsky), & + 'sky temperature scales from 144 MHz to the selected band') + + expected_degradation = -10.0_real64 * log10( & + (real(ntsky_144, real64) + 80.0_real64) / & + (13.0_real64 * (408.0_real64 / 144.0_real64)**2.6_real64 + 80.0_real64)) + & + real(db_moon_144, real64) + call require(abs(real(degradation_144, real64) - expected_degradation) < 1.0e-4_real64, & + 'degradation uses the cold-sky temperature for the selected band') + + print '(a)', 'MAP65 Astro tests passed.' + +contains + + subroutine run_astro(frequency_mhz, ntsky, db_moon, degradation) + integer, intent(in) :: frequency_mhz + integer, intent(out) :: ntsky + real, intent(out) :: db_moon, degradation + real :: az_sun, el_sun, az_moon, el_moon + real :: doppler00, doppler, ra_moon, dec_moon, hour_angle + real :: semidiameter, polarization_offset, nonreciprocal_loss + real :: day, longitude, latitude, local_sidereal_time + + call astro(2025, 1, 15, 12.0, frequency_mhz, 'FN20rx', 2, 0.0, & + az_sun, el_sun, az_moon, el_moon, ntsky, doppler00, doppler, & + db_moon, ra_moon, dec_moon, hour_angle, degradation, semidiameter, & + polarization_offset, nonreciprocal_loss, day, longitude, latitude, & + local_sidereal_time) + call astro(2025, 1, 15, 12.0, frequency_mhz, 'FN20rx', 1, 0.0, & + az_sun, el_sun, az_moon, el_moon, ntsky, doppler00, doppler, & + db_moon, ra_moon, dec_moon, hour_angle, degradation, semidiameter, & + polarization_offset, nonreciprocal_loss, day, longitude, latitude, & + local_sidereal_time) + end subroutine run_astro + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_map65_astro diff --git a/tests/unit/map65/test_map65_decode_display_filter.cpp b/tests/unit/map65/test_map65_decode_display_filter.cpp new file mode 100644 index 00000000..ad7ec1e1 --- /dev/null +++ b/tests/unit/map65/test_map65_decode_display_filter.cpp @@ -0,0 +1,94 @@ +#include "map65_decode_display_filter.h" + +#include <QtTest> + +namespace +{ +QString jt65Line(int frequencyHz, int utc, QString const& message) +{ + QByteArray const text = message.leftJustified(22, ' ').toLatin1(); + return QString::asprintf("%3d%5d%4d%6.4d%5.1f%5d # %-22s", + frequencyHz / 1000, frequencyHz % 1000, 0, utc, + 0.0, -20, text.constData()); +} + +QString q65Line(int frequencyHz, int utc, QString const& message) +{ + QByteArray const text = message.leftJustified(28, ' ').toLatin1(); + return QString::asprintf("%3d%5d%4d%6.4d%5.1f%5d : %-28s", + frequencyHz / 1000, frequencyHz % 1000, 0, utc, + 0.0, -20, text.constData()); +} +} + +class TestMap65DecodeDisplayFilter final : public QObject +{ + Q_OBJECT + +private slots: + void suppressesOnlyMatchingFinalDecode() + { + Map65DecodeDisplayFilter filter; + QVERIFY(filter.handleControlLine("<Map65DecodePass> early\n")); + QVERIFY(filter.shouldDisplay(jt65Line(125000, 1234, "CQ K1ABC FN42"))); + filter.completeEarlyPass(); + + QVERIFY(filter.handleControlLine("<Map65DecodePass> final\n")); + QVERIFY(!filter.shouldDisplay(jt65Line(125020, 1234, "CQ K1ABC FN42"))); + QVERIFY(filter.shouldDisplay(jt65Line(125021, 1234, "CQ K1ABC FN42"))); + QVERIFY(filter.shouldDisplay(jt65Line(125000, 1235, "CQ K1ABC FN42"))); + QVERIFY(filter.shouldDisplay(jt65Line(125000, 1234, "CQ K2XYZ EM00"))); + QVERIFY(filter.shouldDisplay(q65Line(125000, 1234, "CQ K1ABC FN42"))); + } + + void displaysFinalOnlyDecode() + { + Map65DecodeDisplayFilter filter; + QVERIFY(filter.handleControlLine("<Map65DecodePass> early")); + filter.completeEarlyPass(); + QVERIFY(filter.handleControlLine("<Map65DecodePass> final")); + + QString const decode = q65Line(125000, 2, "W1AAA K2BBB EM00"); + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.shouldDisplay(decode)); + } + + void manualDiskAndUnknownPassesFailOpen() + { + Map65DecodeDisplayFilter filter; + QString const decode = jt65Line(125000, 2, "CQ K1ABC FN42"); + + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.handleControlLine("<Map65DecodePass> manual")); + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.handleControlLine("<Map65DecodePass> disk")); + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.handleControlLine("<Map65DecodePass> invalid")); + QVERIFY(filter.shouldDisplay(decode)); + QVERIFY(filter.shouldDisplay("Signal too strong, or suspect data?")); + + QString malformed = decode; + malformed.replace(28, 3, " ? "); + QVERIFY(filter.shouldDisplay(malformed)); + } + + void completedCycleDoesNotRetainDuplicates() + { + Map65DecodeDisplayFilter filter; + QString const decode = q65Line(125000, 2, "W1AAA K2BBB EM00"); + + QVERIFY(filter.handleControlLine("<Map65DecodePass> early")); + QVERIFY(filter.shouldDisplay(decode)); + filter.completeEarlyPass(); + QVERIFY(filter.handleControlLine("<Map65DecodePass> final")); + QVERIFY(!filter.shouldDisplay(decode)); + filter.completeCycle(); + QVERIFY(filter.handleControlLine("<Map65DecodePass> final")); + QVERIFY(filter.shouldDisplay(decode)); + } +}; + +QTEST_APPLESS_MAIN(TestMap65DecodeDisplayFilter) + +#include "test_map65_decode_display_filter.moc" diff --git a/tests/unit/map65/test_map65_decode_requests.f90 b/tests/unit/map65/test_map65_decode_requests.f90 new file mode 100644 index 00000000..e06c4c6d --- /dev/null +++ b/tests/unit/map65/test_map65_decode_requests.f90 @@ -0,0 +1,112 @@ +program test_map65_decode_requests + use iso_c_binding + use npar_ptrs_mod + implicit none + + integer(c_int64_t) :: early_id, final_id, manual_id + character(kind=c_char) :: dx(12) + + call set_nhsym(280) + call set_nagain(0) + call set_ndepth(1) + call set_fcenter(144.125_c_double) + dx = transfer('K1ABC ', dx) + call set_hiscall(dx) + early_id = publish_decode_request() + if (.not. claim_decode_request()) error stop 'early request missing' + if (active_request_id /= early_id .or. nhsym /= 280) error stop 'early identity changed' + if (claim_decode_request()) error stop 'early request repeated' + + ! Publish the final pass while the early pass is still using its parameters. + call set_decoder_ready(0) + call set_nhsym(302) + call set_ndepth(3) + call set_fcenter(144.135_c_double) + dx = transfer('K2DEF ', dx) + call set_hiscall(dx) + final_id = publish_decode_request() + if (nhsym /= 280 .or. ndepth /= 1 .or. hiscall /= 'K1ABC') error stop 'active parameters changed' + if (abs(fcenter - 144.125_c_double) > 1.e-8_c_double) error stop 'active center frequency changed' + if (is_current_decode_request(early_id)) error stop 'stale early completion accepted' + newdat = 0 + if (.not. claim_decode_request()) error stop 'pending final lost' + if (active_request_id /= final_id .or. nhsym /= 302 .or. newdat /= 1) error stop 'final identity changed' + if (ndepth /= 3 .or. hiscall /= 'K2DEF') error stop 'final parameters changed' + if (.not. is_current_decode_request(final_id)) error stop 'current final completion rejected' + if (claim_decode_request()) error stop 'final request repeated' + + ! Both automatic triggers can arrive before the decoder claims either. + call set_nhsym(280) + early_id = publish_decode_request() + call set_nhsym(302) + final_id = publish_decode_request() + call set_decoder_ready(0) + if (claim_decode_request()) error stop 'unready request claimed' + call set_decoder_ready(1) + if (.not. claim_decode_request()) error stop 'queued early missing' + if (active_request_id /= early_id .or. nhsym /= 280) error stop 'queued early out of order' + if (.not. claim_decode_request()) error stop 'queued final missing' + if (active_request_id /= final_id .or. nhsym /= 302) error stop 'queued final out of order' + if (claim_decode_request()) error stop 'queue did not drain' + + ! Completing a manual request cannot clear a newer automatic request. + call set_manual_decode_flag(1) + call set_nagain(1) + manual_id = publish_decode_request() + if (get_manual_decode_flag() /= 0) error stop 'manual flag not consumed' + if (.not. claim_decode_request()) error stop 'manual request missing' + if (manualDecodeFlag /= 1 .or. nagain /= 1) error stop 'manual parameters changed' + call set_nagain(0) + final_id = publish_decode_request() + if (manualDecodeFlag /= 1 .or. nagain /= 1) error stop 'pending update changed active manual' + manualDecodeFlag = 0 + newdat = 0 + if (is_current_decode_request(manual_id)) error stop 'stale manual completion accepted' + if (.not. claim_decode_request()) error stop 'final lost after manual completion' + if (active_request_id /= final_id .or. manualDecodeFlag /= 0 .or. nagain /= 0) error stop 'final inherited manual parameters' + if (claim_decode_request()) error stop 'manual sequence did not drain' + + ! A final request waiting beyond rollover must not decode the next interval. + call set_ndiskdat(0) + call set_nagain(0) + final_id = publish_decode_request() + call advance_live_input_generation() + if (.not. claim_decode_request()) error stop 'expired final missing' + if (active_request_id /= final_id .or. .not. active_request_expired) error stop 'old final did not expire' + if (.not. is_current_decode_request(final_id)) error stop 'expired current request cannot clear busy' + early_id = publish_decode_request() + if (is_current_decode_request(final_id)) error stop 'old skipped completion accepted' + if (.not. claim_decode_request()) error stop 'current interval request missing' + if (active_request_id /= early_id .or. active_request_expired) error stop 'current interval request expired' + if (active_input_generation /= live_input_generation) error stop 'claimed input generation changed' + + call set_nagain(1) + manual_id = publish_decode_request() + call advance_live_input_generation() + if (.not. claim_decode_request()) error stop 'manual repeat missing after rollover' + if (active_request_id /= manual_id .or. active_request_expired) error stop 'manual repeat expired on rollover' + call set_nagain(0) + call set_manual_decode_flag(1) + manual_id = publish_decode_request() + call advance_live_input_generation() + if (.not. claim_decode_request()) error stop 'freeze request missing after rollover' + if (active_request_id /= manual_id .or. active_request_expired) error stop 'freeze request expired on rollover' + call set_ndiskdat(1) + final_id = publish_decode_request() + call advance_live_input_generation() + if (.not. claim_decode_request()) error stop 'disk request missing after rollover' + if (active_request_id /= final_id .or. active_request_expired) error stop 'disk request expired on rollover' + call set_ndiskdat(0) + + early_id = publish_decode_request() + final_id = publish_decode_request() + call cancel_pending_decode_requests() + if (claim_decode_request()) error stop 'canceled request claimed' + if (is_current_decode_request(final_id)) error stop 'canceled completion accepted' + final_id = publish_decode_request() + if (.not. claim_decode_request()) error stop 'request missing after cancel' + if (active_request_id /= final_id) error stop 'wrong request after cancel' + early_id = publish_decode_request() + call set_stop_m65(1) + if (get_stop_m65() /= 1 .or. claim_decode_request()) error stop 'shutdown did not discard requests' +end program diff --git a/tests/unit/map65/test_map65_deep_search_cache.f90 b/tests/unit/map65/test_map65_deep_search_cache.f90 new file mode 100644 index 00000000..6479bcad --- /dev/null +++ b/tests/unit/map65/test_map65_deep_search_cache.f90 @@ -0,0 +1,188 @@ +program test_map65_deep_search_cache + use decodes_mod, only: mcall3a + use deep65_mod, only: build_call3_candidates, testmsg, ncode, ntot + use encode65_mod, only: encode65 + implicit none + + character(len=12), parameter :: mycall = 'K1ABC', hiscall = 'W9XYZ', no_call = '' + character(len=6), parameter :: hisgrid = 'EN37' + integer :: fixture_unit, ios + logical :: fixture_owned = .false. + + ! Run in a dedicated test directory; never overwrite an existing callsign database. + open(newunit=fixture_unit, file='CALL3.TXT', status='new', action='write', iostat=ios) + call require(ios == 0, 'create an isolated CALL3.TXT fixture') + fixture_owned = .true. + call write_fixture(fixture_unit, 'G4XYZ,IO91,NONE,') + close(fixture_unit) + + call test_startup_transition + call test_mycall_transition + call test_hiscall_transition + call test_grid_transition + call test_eme_transition + call test_file_invalidation + + call remove_fixture + print '(a)', 'MAP65 Deep Search cache tests passed.' + +contains + + subroutine build_fresh(local_call, dx_call, dx_grid, eme_only) + character(len=12), intent(in) :: local_call, dx_call + character(len=6), intent(in) :: dx_grid + integer, intent(in) :: eme_only + + mcall3a = 1 + call build_call3_candidates(local_call, dx_call, dx_grid, eme_only) + call require(mcall3a == 0, 'building consumes file invalidation') + end subroutine build_fresh + + subroutine test_startup_transition + call build_fresh(mycall, no_call, hisgrid, 0) + call require(.not. any(testmsg(1:ntot) == 'K1ABC W9XYZ R-01'), & + 'startup without a DX call has no directed report candidates') + call build_call3_candidates(mycall, hiscall, hisgrid, 0) + call require(ntot == 132, 'a supplied DX call adds all report variants and file candidates') + call require_message('K1ABC W9XYZ EN37') + call require_message('K1ABC W9XYZ -01') + call require_message('K1ABC W9XYZ R-30') + call require_message('K1ABC W9XYZ 73') + call require_message('CQ K2ABC FN20') + call require_message('CQ G4XYZ IO91') + call require_fresh_equivalent(mycall, hiscall, hisgrid, 0, 'startup DX entry') + call build_call3_candidates(mycall, hiscall, hisgrid, 0) + call require_fresh_equivalent(mycall, hiscall, hisgrid, 0, 'unchanged settings') + end subroutine test_startup_transition + + subroutine test_mycall_transition + character(len=12), parameter :: changed_call = 'K3ABC' + + call build_fresh(mycall, hiscall, hisgrid, 0) + call build_call3_candidates(changed_call, hiscall, hisgrid, 0) + call require_message('K3ABC W9XYZ EN37') + call require_message('K3ABC K2ABC FN20') + call require(.not. any(index(testmsg(1:ntot), 'K1ABC ') == 1), 'old MyCall candidates disappear') + call require_fresh_equivalent(changed_call, hiscall, hisgrid, 0, 'MyCall change') + end subroutine test_mycall_transition + + subroutine test_hiscall_transition + character(len=12), parameter :: changed_call = 'W8XYZ' + + call build_fresh(mycall, hiscall, hisgrid, 0) + call build_call3_candidates(mycall, changed_call, hisgrid, 0) + call require_message('K1ABC W8XYZ EN37') + call require_message('K1ABC W8XYZ R-01') + call require(.not. any(index(testmsg(1:ntot), 'W9XYZ') > 0), 'old DX call candidates disappear') + call require_fresh_equivalent(mycall, changed_call, hisgrid, 0, 'DX call change') + end subroutine test_hiscall_transition + + subroutine test_grid_transition + character(len=6), parameter :: changed_grid = 'FN42' + + call build_fresh(mycall, hiscall, hisgrid, 0) + call build_call3_candidates(mycall, hiscall, changed_grid, 0) + call require_message('K1ABC W9XYZ FN42') + call require_message('CQ W9XYZ FN42') + call require(.not. any(testmsg(1:ntot) == 'K1ABC W9XYZ EN37'), 'old DX grid candidate disappears') + call require_fresh_equivalent(mycall, hiscall, changed_grid, 0, 'DX grid change') + end subroutine test_grid_transition + + subroutine test_eme_transition + call build_fresh(mycall, hiscall, hisgrid, 0) + call build_call3_candidates(mycall, hiscall, hisgrid, 1) + call require(ntot == 130, 'EME filtering removes only the non-EME file entry') + call require_message('K1ABC K2ABC FN20') + call require_message('K1ABC W9XYZ R-01') + call require(.not. any(index(testmsg(1:ntot), 'G4XYZ') > 0), 'non-EME candidates disappear') + call require_fresh_equivalent(mycall, hiscall, hisgrid, 1, 'enable EME filter') + call build_call3_candidates(mycall, hiscall, hisgrid, 0) + call require_message('CQ G4XYZ IO91') + call require_fresh_equivalent(mycall, hiscall, hisgrid, 0, 'disable EME filter') + end subroutine test_eme_transition + + subroutine test_file_invalidation + call build_fresh(mycall, hiscall, hisgrid, 0) + close(23) + open(newunit=fixture_unit, file='CALL3.TXT', status='replace', action='write') + call write_fixture(fixture_unit, 'G3ABC,IO92,NONE,') + close(fixture_unit) + + call build_call3_candidates(mycall, hiscall, hisgrid, 0) + call require_message('CQ G4XYZ IO91') + call require(.not. any(testmsg(1:ntot) == 'CQ G3ABC IO92'), & + 'unchanged settings reuse the cache until explicit file invalidation') + mcall3a = 1 + call build_call3_candidates(mycall, hiscall, hisgrid, 0) + call require(mcall3a == 0, 'a file reload consumes its invalidation flag') + call require_message('CQ G3ABC IO92') + call require(.not. any(index(testmsg(1:ntot), 'G4XYZ') > 0), 'file reload removes deleted stations') + call require_fresh_equivalent(mycall, hiscall, hisgrid, 0, 'CALL3.TXT reload') + end subroutine test_file_invalidation + + subroutine require_fresh_equivalent(local_call, dx_call, dx_grid, eme_only, description) + character(len=12), intent(in) :: local_call, dx_call + character(len=6), intent(in) :: dx_grid + integer, intent(in) :: eme_only + character(len=*), intent(in) :: description + character(len=22), allocatable :: cached_messages(:) + integer, allocatable :: cached_symbols(:, :) + integer :: cached_count + + cached_count = ntot + cached_messages = testmsg(1:ntot) + cached_symbols = ncode(:, 1:ntot) + call build_fresh(local_call, dx_call, dx_grid, eme_only) + call require(ntot == cached_count, description//': cached and fresh candidate counts match') + call require(all(testmsg(1:ntot) == cached_messages), description//': cached and fresh messages match') + call require(all(ncode(:, 1:ntot) == cached_symbols), description//': cached and fresh encoded symbols match') + end subroutine require_fresh_equivalent + + subroutine require_message(message) + character(len=*), intent(in) :: message + character(len=22) :: padded_message + integer :: i, expected_symbols(63) + + padded_message = message + call encode65(padded_message, expected_symbols) + do i = 1, ntot + if (testmsg(i) /= message) cycle + call require(all(ncode(:, i) == expected_symbols), 'matching encoded symbols for '//message) + return + end do + call require(.false., 'expected candidate '//message) + end subroutine require_message + + subroutine write_fixture(unit, terrestrial_entry) + integer, intent(in) :: unit + character(len=*), intent(in) :: terrestrial_entry + + write(unit, '(a)') '// Controlled Deep Search candidates', 'K2ABC,FN20,EME,', terrestrial_entry, 'ZZZZ' + end subroutine write_fixture + + subroutine remove_fixture + logical :: opened + integer :: unit, status + + if (.not. fixture_owned) return + inquire(file='CALL3.TXT', opened=opened, number=unit, iostat=status) + if (status /= 0) return + if (.not. opened) then + open(newunit=unit, file='CALL3.TXT', status='old', iostat=status) + if (status /= 0) return + end if + close(unit, status='delete', iostat=status) + if (status == 0) fixture_owned = .false. + end subroutine remove_fixture + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + call remove_fixture + error stop 1 + end if + end subroutine require +end program test_map65_deep_search_cache diff --git a/tests/unit/map65/test_map65_half_symbol_scheduler.cpp b/tests/unit/map65/test_map65_half_symbol_scheduler.cpp new file mode 100644 index 00000000..984c37a8 --- /dev/null +++ b/tests/unit/map65/test_map65_half_symbol_scheduler.cpp @@ -0,0 +1,61 @@ +#include "half_symbol_scheduler.h" + +#include <QtTest/QtTest> + +class TestMap65HalfSymbolScheduler final : public QObject +{ + Q_OBJECT + +private slots: + void retries_busy_half_symbols (); + void catches_up_one_half_symbol_at_a_time (); + void resets_for_the_next_period (); +}; + +void TestMap65HalfSymbolScheduler::retries_busy_half_symbols () +{ + Map65HalfSymbolScheduler scheduler; + std::atomic_bool busy {false}; + + QVERIFY (scheduler.claim_next (1, busy)); + QCOMPARE (scheduler.scheduled_half_symbol (), 1); + QVERIFY (!scheduler.claim_next (2, busy)); + QCOMPARE (scheduler.scheduled_half_symbol (), 1); + + busy.store (false, std::memory_order_release); + QVERIFY (scheduler.claim_next (2, busy)); + QCOMPARE (scheduler.scheduled_half_symbol (), 2); +} + +void TestMap65HalfSymbolScheduler::catches_up_one_half_symbol_at_a_time () +{ + Map65HalfSymbolScheduler scheduler; + std::atomic_bool busy {false}; + + for (int expected = 1; expected <= 5; ++expected) + { + QVERIFY (scheduler.claim_next (5, busy)); + QCOMPARE (scheduler.scheduled_half_symbol (), expected); + busy.store (false, std::memory_order_release); + } + + QVERIFY (!scheduler.claim_next (5, busy)); + QVERIFY (!busy.load (std::memory_order_acquire)); +} + +void TestMap65HalfSymbolScheduler::resets_for_the_next_period () +{ + Map65HalfSymbolScheduler scheduler; + std::atomic_bool busy {false}; + + QVERIFY (scheduler.claim_next (1, busy)); + busy.store (false, std::memory_order_release); + scheduler.reset (); + + QCOMPARE (scheduler.scheduled_half_symbol (), 0); + QVERIFY (scheduler.claim_next (1, busy)); +} + +QTEST_GUILESS_MAIN (TestMap65HalfSymbolScheduler) + +#include "test_map65_half_symbol_scheduler.moc" diff --git a/tests/unit/map65/test_map65_q65_dphi.f90 b/tests/unit/map65/test_map65_q65_dphi.f90 new file mode 100644 index 00000000..a9c0527d --- /dev/null +++ b/tests/unit/map65/test_map65_q65_dphi.f90 @@ -0,0 +1,126 @@ +program test_map65_q65_dphi + use iso_fortran_env, only: int8, real32, real64 + use datcom_ptrs_mod, only: dd, ss, savg + use decodes_mod, only: decodes_init + use filbig_mod, only: filbig, MAXFFT2 + use ftninit_mod, only: ftninit + use gen_q65_cwave_mod, only: gen_q65_cwave + use npar_ptrs_mod, only: abort_decode, fcenter, idphi, manualDecodeFlag, ndepth, & + nfft_active, nsmax_active, set_runtime_params, t_start + use q65_decode, only: msg0, nsnr0 + use q65b_mod, only: q65b + use symspec_mod, only: symspec + use timer_impl, only: init_timer, fini_timer + use wideband_sync, only: candidate, get_candidates, init_wideband_sync, & + MAX_CANDIDATES, nkhz_center + implicit none + + integer, parameter :: sample_rate = 96000, fft_size = 32768 + character(len=24), parameter :: message = 'W1AAA K2BBB EM00' + complex(real32), allocatable :: waveform(:), c4a(:), c4b(:) + real(real32), allocatable :: display_spectrum(:) + integer, allocatable :: seed(:) + type(candidate) :: candidates(MAX_CANDIDATES) + character(len=24) :: sent_message + integer(int8) :: lstrong(0:1023) + integer :: i, k, nwave, seed_size, ncand, selected, newdat, n4, idec + integer :: nb, nbslider, ihsym, nzap, nkh + real(real32) :: gainx, gainy, phasex, phasey, rejectx, rejecty, pxdb, pydb, slimit + + call set_runtime_params(sample_rate, fft_size, 56 * sample_rate) + allocate(dd(4, nsmax_active), ss(4, 322, nfft_active), savg(4, nfft_active)) + allocate(waveform(nsmax_active), display_spectrum(nfft_active)) + allocate(c4a(MAXFFT2), c4b(MAXFFT2)) + ss = 0.0 + savg = 0.0 + waveform = cmplx(0.0, 0.0) + + call random_seed(size=seed_size) + allocate(seed(seed_size)) + seed = 104729 + call random_seed(put=seed) + call random_number(dd) + dd = 60.0 * (dd - 0.5) + + ! The capture is centered at 48 kHz; transmission starts one second in. + call gen_q65_cwave(message, 48000 + 1270, 2, real(sample_rate, real64), & + sent_message, waveform, nwave) + call require(nwave > 0 .and. trim(sent_message) == trim(message), 'generate the Q65 message') + call require(sample_rate + nwave <= nsmax_active, 'waveform fits in the capture') + do i = 1, nwave + k = sample_rate + i + ! Equal signal amplitudes with a 180-degree receiver phase offset. + dd(1,k) = dd(1,k) + real(waveform(i)) + dd(2,k) = dd(2,k) + aimag(waveform(i)) + dd(3,k) = dd(3,k) - real(waveform(i)) + dd(4,k) = dd(4,k) - aimag(waveform(i)) + end do + dd = real(nint(dd), real32) + deallocate(waveform) + + call init_timer() + call ftninit('.') + open(unit=19, status='scratch') + open(unit=20, status='scratch') + call decodes_init() + call init_wideband_sync() + abort_decode = .false. + manualDecodeFlag = 0 + ndepth = 1 + idphi = 180 + fcenter = 144.125_real64 + nkhz_center = 125 + + nb = 0 + nbslider = 40 + gainx = 1.0 + gainy = 1.0 + phasex = 0.0 + phasey = 0.0 + slimit = 0.0 + ihsym = 0 + nzap = 0 + do i = 1, 302 + k = fft_size + nint(real(i - 1, real64) * 2048.0_real64 * sample_rate / 11025.0_real64) + call symspec(k, 1, 1, nb, nbslider, idphi, 0, 0, gainx, gainy, & + phasex, phasey, rejectx, rejecty, pxdb, pydb, display_spectrum, & + nkh, ihsym, nzap, slimit, lstrong) + end do + call require(ihsym == 302, 'complete the symbol spectra') + + call get_candidates(ss, savg, .true., ihsym, 48, 56, 0, 2, candidates, ncand) + selected = 0 + do i = 1, ncand + if (candidates(i)%iflip /= 0) cycle + if (abs(1000.0 * candidates(i)%f - 49270.0) > 10.0) cycle + selected = i + exit + end do + call require(selected > 0, 'acquire the Q65 signal with calibrated spectra') + + newdat = 1 + call filbig(dd, nsmax_active, 1000.0_real64 * candidates(selected)%f, newdat, & + sample_rate, .true., c4a, c4b, n4) + call system_clock(t_start) + call q65b(1, 0, 0, fcenter, 0, sample_rate, nkhz_center, 0, 100, .true., idphi, & + 'N0CALL ', 'FN31 ', ' ', ' ', 2, & + real(candidates(selected)%f, real64), 1.270, newdat, 0, 0, 0, idec) + + call require(.not. logical(abort_decode), 'decode within the time budget') + call require(nsnr0 > -99 .and. trim(msg0) == trim(message), & + 'recover the Q65 message despite opposite-phase receiver channels') + call fini_timer() + print '(a)', 'MAP65 Q65 Dphi test passed.' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_map65_q65_dphi diff --git a/tests/unit/map65/test_map65_q65b_timeout.f90 b/tests/unit/map65/test_map65_q65b_timeout.f90 new file mode 100644 index 00000000..bf7b2c9c --- /dev/null +++ b/tests/unit/map65/test_map65_q65b_timeout.f90 @@ -0,0 +1,46 @@ +program test_map65_q65b_timeout + use iso_fortran_env, only: real64 + use npar_ptrs_mod, only: abort_decode, t_start + use q65_decode, only: cq0, msg0, nfreq0, nsnr0, xdt0 + use q65b_mod, only: q65b + implicit none + + integer :: idec, now, rate + + call system_clock(now, rate) + t_start = now - 41*rate + abort_decode = .false. + idec = 123 + nsnr0 = 7 + msg0 = 'STALE MESSAGE' + cq0 = 'q1 ' + xdt0 = 2.5 + nfreq0 = 1000 + + call q65b(1, 0, 0, 144.125_real64, 0, 96000, 125, 0, 100, .false., 0, & + 'K1ABC ', 'FN42 ', 'W9XYZ ', 'EN50 ', 2, 1000.0_real64, 125.0, & + 1, 0, 0, 0, idec) + + if (.not. abort_decode) then + print '(a)', 'FAIL: expired decode budget sets the abort flag' + error stop 1 + end if + call require(idec == -1, 'timeout returns a defined failure status') + call require(nsnr0 == -99, 'timeout clears stale Q65 SNR state') + call require(len_trim(msg0) == 0 .and. len_trim(cq0) == 0, & + 'timeout clears stale Q65 message state') + call require(xdt0 == 0.0 .and. nfreq0 == 0, 'timeout clears stale Q65 signal state') + print '(a)', 'MAP65 Q65 timeout test passed.' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_map65_q65b_timeout diff --git a/tests/unit/map65/test_map65_result_selection.f90 b/tests/unit/map65/test_map65_result_selection.f90 new file mode 100644 index 00000000..dd76ea4c --- /dev/null +++ b/tests/unit/map65/test_map65_result_selection.f90 @@ -0,0 +1,96 @@ +program test_map65_result_selection + use trimlist_mod, only: select_unique_decodes + implicit none + + integer, parameter :: MAXMSG = 1000 + real :: sig(MAXMSG, 30) + character(len=22) :: msg(MAXMSG) + integer :: indx(MAXMSG), nz + + call test_result_identity + call test_empty_and_full_lists + print '(a)', 'MAP65 result selection tests passed.' + +contains + + subroutine test_result_identity + sig = 0.0 + msg = ' ' + + call set_result(1, 1, 100.000, 0.20, 1, 'K1ABC W9XYZ FN42', 1.0) + call set_result(2, 1, 100.005, 0.25, 1, 'K1ABC W9XYZ FN42', 2.0) + call set_result(3, 1, 100.005, 0.20, 1, 'W1AAA K2BBB EM00') + call set_result(4, 1, 100.005, 0.50, 1, 'K1ABC W9XYZ FN42') + call set_result(5, 1, 100.005, 0.20, -1, 'K1ABC W9XYZ FN42') + call set_result(6, 1, 100.020, 0.20, 1, 'K1ABC W9XYZ FN42') + call set_result(7, 1, 100.005, 0.20, 1, ' ') + call set_result(8, 2, 100.005, 0.20, 1, 'K1ABC W9XYZ FN42') + + call select_unique_decodes(sig, msg, 8, 0.010, 0.2, indx, nz) + call require(nz == 6, 'only a matching message and signal identity is deduplicated') + call require(selected_count('W1AAA K2BBB EM00', 1, 1) == 1, & + 'a different message at the same frequency survives') + call require(selected_count('K1ABC W9XYZ FN42', 1, -1) == 1, & + 'opposite-sync results survive') + call require(selected_count('K1ABC W9XYZ FN42', 2, 1) == 1, & + 'results from another UTC survive') + call require(any(indx(1:nz) == 2) .and. .not. any(indx(1:nz) == 1), & + 'the stronger duplicate supplies the displayed metrics') + end subroutine test_result_identity + + subroutine test_empty_and_full_lists + integer :: i + + sig = 0.0 + msg = ' ' + call select_unique_decodes(sig, msg, 0, 0.010, 0.2, indx, nz) + call require(nz == 0, 'an empty result list stays empty') + + do i = 1, MAXMSG + sig(i, 2) = 1.0 + sig(i, 3) = 0.020*i + sig(i, 5) = 0.2 + sig(i, 7) = 1.0 + write(msg(i), '("MSG",I4.4)') i + end do + call select_unique_decodes(sig, msg, MAXMSG, 0.010, 0.2, indx, nz) + call require(nz == MAXMSG, 'the maximum result list does not overrun selection storage') + end subroutine test_empty_and_full_lists + + subroutine set_result(index, utc, frequency, dt, flip, message, strength) + integer, intent(in) :: index, utc, flip + real, intent(in) :: frequency, dt + character(len=*), intent(in) :: message + real, intent(in), optional :: strength + + sig(index, 2) = utc + sig(index, 3) = frequency + sig(index, 5) = dt + sig(index, 7) = flip + if (present(strength)) sig(index, 8) = strength + msg(index) = message + end subroutine set_result + + integer function selected_count(message, utc, flip) + character(len=*), intent(in) :: message + integer, intent(in) :: utc, flip + integer :: i, source + + selected_count = 0 + do i = 1, nz + source = indx(i) + if (msg(source) == message .and. nint(sig(source, 2)) == utc .and. & + nint(sig(source, 7)) == flip) selected_count = selected_count + 1 + end do + end function selected_count + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require +end program test_map65_result_selection diff --git a/tests/unit/map65/test_map65_runtime_paths.cpp b/tests/unit/map65/test_map65_runtime_paths.cpp new file mode 100644 index 00000000..7cca6ca4 --- /dev/null +++ b/tests/unit/map65/test_map65_runtime_paths.cpp @@ -0,0 +1,225 @@ +#include "runtime_paths.h" + +#include <QDir> +#include <QFile> +#include <QFileInfo> +#include <QTemporaryDir> +#include <QtTest> + +namespace +{ +bool writeFile(QString const& path, QByteArray const& contents) +{ + QFile file {path}; + if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { + return false; + } + return file.write(contents) == contents.size(); +} + +QByteArray readFile(QString const& path) +{ + QFile file {path}; + if (!file.open(QIODevice::ReadOnly)) { + return {}; + } + return file.readAll(); +} + +class CurrentDirectoryGuard +{ +public: + explicit CurrentDirectoryGuard(QString const& path) + : previous_ {QDir::currentPath()} + , changed_ {QDir::setCurrent(path)} + { + } + + ~CurrentDirectoryGuard() + { + if (changed_) { + QDir::setCurrent(previous_); + } + } + + bool changed() const { return changed_; } + +private: + QString previous_; + bool changed_; +}; +} + +class TestMap65RuntimePaths final : public QObject +{ + Q_OBJECT + +private slots: + void canonicalSourcePrecedesLegacyCandidates() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app/resources")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const canonical = dir.absoluteFilePath("installed/eclipse.txt"); + QString const legacy = dir.absoluteFilePath("app/resources/eclipse.txt"); + QVERIFY(writeFile(canonical, "canonical")); + QVERIFY(writeFile(legacy, "legacy")); + + QCOMPARE(map65RuntimeSourceFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), "eclipse.txt"), + QFileInfo {canonical}.absoluteFilePath()); + } + + void legacySourceRemainsAvailable() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app/resources")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const legacy = dir.absoluteFilePath("app/resources/eclipse.txt"); + QVERIFY(writeFile(legacy, "legacy")); + + QCOMPARE(map65RuntimeSourceFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), "eclipse.txt"), + QFileInfo {legacy}.absoluteFilePath()); + } + + void writableEclipseCannotShadowPackagedData() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const canonical = dir.absoluteFilePath("installed/eclipse.txt"); + QString const stale = dir.absoluteFilePath("writable/eclipse.txt"); + QVERIFY(writeFile(canonical, "current package")); + QVERIFY(writeFile(stale, "stale copy")); + CurrentDirectoryGuard cwd {dir.absoluteFilePath("writable")}; + QVERIFY(cwd.changed()); + + QCOMPARE(map65RuntimeSourceFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), "eclipse.txt"), + QFileInfo {canonical}.absoluteFilePath()); + QCOMPARE(readFile(stale), QByteArray {"stale copy"}); + } + + void writableDirectoryIsNotASourceFallback() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const stale = dir.absoluteFilePath("writable/unique-runtime-data.txt"); + QVERIFY(writeFile(stale, "stale copy")); + CurrentDirectoryGuard cwd {dir.absoluteFilePath("writable")}; + QVERIFY(cwd.changed()); + + QCOMPARE(map65RuntimeSourceFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), + "unique-runtime-data.txt"), + dir.absoluteFilePath("installed/unique-runtime-data.txt")); + } + + void writableDirectoryAliasIsNotASourceFallback() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const writable = dir.absoluteFilePath("writable"); + QString const writableAlias = dir.absoluteFilePath("writable-alias"); + if (!QFile::link(writable, writableAlias)) { + QSKIP("Directory links are unavailable"); + } + QString const stale = QDir {writable}.absoluteFilePath("unique-runtime-data.txt"); + QVERIFY(writeFile(stale, "stale copy")); + QString const aliasedStale = + QDir {writableAlias}.absoluteFilePath("unique-runtime-data.txt"); + if (QFileInfo {aliasedStale}.canonicalFilePath() + != QFileInfo {stale}.canonicalFilePath()) { + QSKIP("Traversable directory links are unavailable"); + } + CurrentDirectoryGuard cwd {writable}; + QVERIFY(cwd.changed()); + + QCOMPARE(map65RuntimeSourceFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), writableAlias, + "unique-runtime-data.txt"), + dir.absoluteFilePath("installed/unique-runtime-data.txt")); + } + + void seedsMissingWritableFile() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QVERIFY(writeFile(dir.absoluteFilePath("installed/CALL3.TXT"), "packaged calls")); + + QString const writable = ensureMap65RuntimeFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), + "CALL3.TXT"); + QCOMPARE(writable, dir.absoluteFilePath("writable/CALL3.TXT")); + QCOMPARE(readFile(writable), QByteArray {"packaged calls"}); + } + + void replacesEmptyWritableFile() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const writable = dir.absoluteFilePath("writable/CALL3.TXT"); + QVERIFY(writeFile(dir.absoluteFilePath("installed/CALL3.TXT"), "packaged calls")); + QVERIFY(writeFile(writable, {})); + + QCOMPARE(ensureMap65RuntimeFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), "CALL3.TXT"), + writable); + QCOMPARE(readFile(writable), QByteArray {"packaged calls"}); + } + + void preservesNonemptyWritableFile() + { + QTemporaryDir root; + QVERIFY(root.isValid()); + QDir dir {root.path()}; + QVERIFY(dir.mkpath("app")); + QVERIFY(dir.mkpath("installed")); + QVERIFY(dir.mkpath("writable")); + QString const writable = dir.absoluteFilePath("writable/CALL3.TXT"); + QVERIFY(writeFile(dir.absoluteFilePath("installed/CALL3.TXT"), "packaged calls")); + QVERIFY(writeFile(writable, "user calls")); + + QCOMPARE(ensureMap65RuntimeFile(dir.absoluteFilePath("app"), + dir.absoluteFilePath("installed"), + dir.absoluteFilePath("writable"), "CALL3.TXT"), + writable); + QCOMPARE(readFile(writable), QByteArray {"user calls"}); + } +}; + +QTEST_APPLESS_MAIN(TestMap65RuntimePaths) + +#include "test_map65_runtime_paths.moc" diff --git a/tests/unit/message_filter/CMakeLists.txt b/tests/unit/message_filter/CMakeLists.txt new file mode 100644 index 00000000..e698f955 --- /dev/null +++ b/tests/unit/message_filter/CMakeLists.txt @@ -0,0 +1,14 @@ +add_executable (test_message_filter + test_message_filter.cpp + ${CMAKE_SOURCE_DIR}/MessageFilter.cpp +) +target_link_libraries (test_message_filter Qt5::Test) +add_test (NAME test_message_filter COMMAND test_message_filter) + +add_executable (test_msk144_filter_rules + test_msk144_filter_rules.cpp + ${CMAKE_SOURCE_DIR}/MessageFilter.cpp + ${CMAKE_SOURCE_DIR}/MessageFilterRules.cpp +) +target_link_libraries (test_msk144_filter_rules Qt5::Test) +add_test (NAME test_msk144_filter_rules COMMAND test_msk144_filter_rules) diff --git a/tests/unit/message_filter/test_message_filter.cpp b/tests/unit/message_filter/test_message_filter.cpp new file mode 100644 index 00000000..36cfb2fe --- /dev/null +++ b/tests/unit/message_filter/test_message_filter.cpp @@ -0,0 +1,37 @@ +#include <QtTest> +#include "MessageFilter.hpp" + +class TestMessageFilter : public QObject +{ + Q_OBJECT + +private slots: + void testContainsAny() + { + QString text = "The quick brown fox jumps over the lazy dog"; + QStringList keywords = QStringList() << "fox" << "cat" << ""; + QVERIFY(MessageFilter::containsAny(text, keywords)); + + keywords = QStringList() << "cat" << "bird"; + QVERIFY(!MessageFilter::containsAny(text, keywords)); + + keywords = QStringList(); + QVERIFY(!MessageFilter::containsAny(text, keywords)); + } + + void testStartsWithAny() + { + QString text = "WSJT-X is great"; + QStringList keywords = QStringList() << "WSJT" << "GWS" << ""; + QVERIFY(MessageFilter::startsWithAny(text, keywords)); + + keywords = QStringList() << "is" << "great"; + QVERIFY(!MessageFilter::startsWithAny(text, keywords)); + + keywords = QStringList(); + QVERIFY(!MessageFilter::startsWithAny(text, keywords)); + } +}; + +QTEST_MAIN(TestMessageFilter) +#include "test_message_filter.moc" diff --git a/tests/unit/message_filter/test_msk144_filter_rules.cpp b/tests/unit/message_filter/test_msk144_filter_rules.cpp new file mode 100644 index 00000000..5ab1c5b2 --- /dev/null +++ b/tests/unit/message_filter/test_msk144_filter_rules.cpp @@ -0,0 +1,99 @@ +#include <QtTest> + +#include "MessageFilterRules.hpp" + +class TestMSK144FilterRules : public QObject +{ + Q_OBJECT + +private slots: + void testBlacklist() + { + MessageFilterLogic::FilterContext ctx; + ctx.filtersForWord2 = true; + ctx.blacklisted = true; + ctx.blacklistKeywords = QStringList() << "K1ABC"; + + auto result = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(result.filtered); + QVERIFY(result.shouldReturn); + } + + void testWhitelist() + { + MessageFilterLogic::FilterContext ctx; + ctx.filtersForWord2 = true; + ctx.whitelisted = true; + ctx.whitelistKeywords = QStringList() << "K1ABC"; + + auto result1 = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(!result1.filtered); + QVERIFY(!result1.shouldReturn); + + auto result2 = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ W1AW FN20", ctx).result; + QVERIFY(result2.filtered); + QVERIFY(result2.shouldReturn); + } + + void testBypass() + { + MessageFilterLogic::FilterContext ctx; + ctx.bypass = true; + ctx.filtersForWord2 = true; + ctx.blacklisted = true; + ctx.blacklistKeywords = QStringList() << "K1ABC"; + + auto result = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(!result.filtered); + QVERIFY(!result.shouldReturn); + } + + void testDirectionalCQ() + { + MessageFilterLogic::FilterContext ctx; + ctx.filtersForWord2 = true; + ctx.blacklisted = true; + ctx.blacklistKeywords = QStringList() << "K1ABC"; + + auto result = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ DX K1ABC FN20", ctx).result; + QVERIFY(result.filtered); + QVERIFY(result.shouldReturn); + } + + void testAlwaysPass() + { + MessageFilterLogic::FilterContext ctx; + ctx.filtersForWord2 = true; + ctx.alwaysPass = true; + ctx.blacklisted = true; + ctx.passKeywords = QStringList() << "K1ABC"; + ctx.blacklistKeywords = QStringList() << "K1ABC"; + + auto result = MessageFilterRules::evaluateMSK144Text("060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(!result.filtered); + QVERIFY(!result.shouldReturn); + } + + void testScoringPounceResetsScores() + { + MessageFilterLogic::FilterContext ctx; + ctx.filtersForWord2 = true; + ctx.filtersForWaitAndPounceOnly = true; + ctx.blacklisted = true; + ctx.blacklistKeywords = QStringList() << "K1ABC"; + ctx.pounce = true; + ctx.respondPolicy = AutoRespondPolicy::MaxDistance; + + auto result = MessageFilterRules::evaluateMSK144Text( + "060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(result.resetPoints); + + ctx.respondPolicy = AutoRespondPolicy::First; + result = MessageFilterRules::evaluateMSK144Text( + "060522 -10 0.3 815 # CQ K1ABC FN20", ctx).result; + QVERIFY(!result.resetPoints); + } +}; + +QTEST_MAIN(TestMSK144FilterRules) +#include "test_msk144_filter_rules.moc" diff --git a/tests/unit/msk/CMakeLists.txt b/tests/unit/msk/CMakeLists.txt new file mode 100644 index 00000000..92c7762d --- /dev/null +++ b/tests/unit/msk/CMakeLists.txt @@ -0,0 +1,15 @@ +add_executable (test_msk_spectrum_edges test_msk_spectrum_edges.f90) +wsjt_link_common_fortran (test_msk_spectrum_edges) +add_test (NAME test_msk_spectrum_edges COMMAND test_msk_spectrum_edges) + +add_executable (test_hspec_committed_boundary test_hspec_committed_boundary.f90) +set_source_files_properties (test_hspec_committed_boundary.f90 PROPERTIES + COMPILE_FLAGS "-Wno-unused-dummy-argument") +wsjt_link_common_fortran (test_hspec_committed_boundary) +add_test (NAME test_hspec_committed_boundary COMMAND test_hspec_committed_boundary) +set_tests_properties (test_hspec_committed_boundary PROPERTIES + TIMEOUT 30 LABELS "receive-handoff") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_hspec_committed_boundary PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/msk/test_hspec_committed_boundary.f90 b/tests/unit/msk/test_hspec_committed_boundary.f90 new file mode 100644 index 00000000..c9e7c432 --- /dev/null +++ b/tests/unit/msk/test_hspec_committed_boundary.f90 @@ -0,0 +1,69 @@ +! hspec is production code. Substitute only its downstream decoder with a +! recording probe: verify the actual slice delivered, not decoder success. +module hspec_input_probe + implicit none + integer :: calls=0 + integer*2 :: received(7168) +end module + +program test_hspec_committed_boundary + use hspec_input_probe + implicit none + integer*2 :: samples(0:120*12000-1) + real :: green(0:702), spectrum(0:63,0:702), pxmax, dbnogain + real*8 :: coefficients(5) + integer :: i, jh, k + character*80 :: line + + samples=0 + coefficients=0 + green=0 + spectrum=0 + jh=0 + k=7168 ! Detector emits an end-exclusive count, not a last-sample index. + call run_hspec(.true.) + if(calls.ne.0) stop 1 ! Silence must not invoke the downstream decoder. + + ! Reset hspec's saved sequence position, then provide two nonzero blocks. + k=512 + call run_hspec(.false.) + do i=0,7167 + samples(i)=int(1+mod(i,30000),kind=2) + enddo + samples(7168)=-12345 ! The first uncommitted sample must never be consumed. + k=7168 + call run_hspec(.true.) + if(calls.ne.1) stop 2 + if(any(received.ne.samples(0:7167))) then + print *, 'FAIL: MSK input must be the completed range [k-7168,k).' + print *, 'Expected first/last:',samples(0),samples(7167) + print *, 'Observed first/last:',received(1),received(7168) + stop 3 + endif + print *, 'MSK committed-boundary test passed' + +contains + subroutine run_hspec(msk) + logical, intent(in) :: msk + logical*1 :: enabled + enabled=msk + call hspec(samples,k,0,15,1500,100,enabled,.false._1,coefficients, & + 0,'K1ABC ','W9XYZ ',.false._1,.false._1,'.', & + green,spectrum,jh,pxmax,dbnogain,line) + end subroutine +end program + +subroutine mskrtd(id2,nutc0,tsec,ntol,nrxfreq,ndepth,mycall,hiscall, & + bshmsg,btrain,pcoeffs,bswl,datadir,line) + use hspec_input_probe + implicit none + integer*2 :: id2(7168) + integer :: nutc0, ntol, nrxfreq, ndepth + real :: tsec + real*8 :: pcoeffs(5) + logical*1 :: bshmsg,btrain,bswl + character*(*) :: mycall,hiscall,datadir,line + received=id2 + calls=calls+1 + line=char(0) +end subroutine diff --git a/tests/unit/msk/test_msk_spectrum_edges.f90 b/tests/unit/msk/test_msk_spectrum_edges.f90 new file mode 100644 index 00000000..61a2b548 --- /dev/null +++ b/tests/unit/msk/test_msk_spectrum_edges.f90 @@ -0,0 +1,297 @@ +program test_msk_spectrum_edges + use msk_spectrum, only: msk_clip_spectrum_window,msk_peak_offset + use packjt77, only: MAXRECENT + use, intrinsic :: iso_fortran_env, only: real64 + use, intrinsic :: ieee_arithmetic, only: ieee_quiet_nan,ieee_value + implicit none + + call test_windows + call test_peak_offsets + call test_frequency_searches + call test_msk40_sync_column + call test_short_ping_input_bounds + + print *, 'MSK spectrum edge tests passed' + +contains + + subroutine test_windows + integer :: lo,hi + logical :: usable + + call msk_clip_spectrum_window(240,-3d0,2d0,lo,hi,usable) + call assert_true(usable .and. lo.eq.1 .and. hi.eq.2, & + 'lower partial window is clipped') + + call msk_clip_spectrum_window(864,863d0,867d0,lo,hi,usable) + call assert_true(usable .and. lo.eq.863 .and. hi.eq.864, & + 'upper partial window is clipped') + + call msk_clip_spectrum_window(240,1d0,1d0,lo,hi,usable) + call assert_true(usable .and. lo.eq.1 .and. hi.eq.1, & + 'first FFT bin is usable') + + call msk_clip_spectrum_window(864,864d0,864d0,lo,hi,usable) + call assert_true(usable .and. lo.eq.864 .and. hi.eq.864, & + 'last FFT bin is usable') + + call assert_rejected_window(240,-5d0,0d0,'window below the FFT is rejected') + call assert_rejected_window(240,241d0,245d0,'window above the FFT is rejected') + call assert_rejected_window(240,20d0,10d0,'reversed window is rejected') + call assert_rejected_window(0,1d0,1d0,'invalid FFT size is rejected') + end subroutine test_windows + + subroutine assert_rejected_window(nfft,requested_lo,requested_hi,message) + integer, intent(in) :: nfft + real(real64), intent(in) :: requested_lo,requested_hi + character(len=*), intent(in) :: message + integer :: lo,hi + logical :: usable + + call msk_clip_spectrum_window(nfft,requested_lo,requested_hi,lo,hi,usable) + call assert_true(.not.usable .and. lo.eq.1 .and. hi.eq.0,message) + end subroutine assert_rejected_window + + subroutine test_peak_offsets + integer, parameter :: NFFT40=240,NFFT144=864 + complex :: spectrum40(NFFT40),spectrum144(NFFT144) + real :: offset + + spectrum40=cmplx(0.0,0.0) + spectrum144=cmplx(0.0,0.0) + spectrum40(1)=cmplx(2.0,1.0) + spectrum40(NFFT40)=cmplx(3.0,-1.0) + spectrum144(1)=cmplx(2.0,1.0) + spectrum144(NFFT144)=cmplx(3.0,-1.0) + call assert_close(msk_peak_offset(spectrum40,1),0.0, & + 'MSK40 first-bin offset is zero') + call assert_close(msk_peak_offset(spectrum40,NFFT40),0.0, & + 'MSK40 last-bin offset is zero') + call assert_close(msk_peak_offset(spectrum144,1),0.0, & + 'MSK144 first-bin offset is zero') + call assert_close(msk_peak_offset(spectrum144,NFFT144),0.0, & + 'MSK144 last-bin offset is zero') + + spectrum40=cmplx(0.0,0.0) + offset=msk_peak_offset(spectrum40,120) + call assert_close(offset,0.0,'all-zero offset is zero') + + spectrum40(119:121)=cmplx(2.0,1.0) + offset=msk_peak_offset(spectrum40,120) + call assert_close(offset,0.0,'flat offset is zero') + + spectrum40=cmplx(0.0,0.0) + spectrum40(119)=cmplx(1.0,0.0) + spectrum40(120)=cmplx(2.0,0.0) + spectrum40(121)=cmplx(3.0,0.0) + offset=msk_peak_offset(spectrum40,120) + call assert_close(offset,0.0,'zero-curvature offset is zero') + + spectrum40(119)=cmplx(1.0,0.0) + spectrum40(120)=cmplx(4.0,0.0) + spectrum40(121)=cmplx(3.0,0.0) + offset=msk_peak_offset(spectrum40,120) + call assert_close(offset,0.5,'ordinary interpolation is preserved') + end subroutine test_peak_offsets + + subroutine test_frequency_searches + integer, parameter :: NSPM40=240,NFRAMES40=3 + integer, parameter :: NSPM144=864,NFRAMES144=8 + complex :: cb40(42),cb144(42) + complex :: cdat40(NSPM40*NFRAMES40),cdat2_40(NSPM40*NFRAMES40) + complex :: cdat144(NSPM144*NFRAMES144),cdat2_144(NSPM144*NFRAMES144) + complex :: cs40(NSPM40),cs144(NSPM144) + integer :: navmask40(NFRAMES40),navmask144(NFRAMES144) + real :: bestf,nan_value,xccs40(0:NSPM40-1),xccs144(0:NSPM144-1),xmax + + cb144=cmplx(0.0,0.0) + cdat144=cmplx(0.0,0.0) + cdat2_144=cmplx(1.0,1.0) + cs144=cmplx(1.0,1.0) + xccs144=1.0 + navmask144=1 + xmax=1.0 + bestf=1.0 + call msk144_freq_search(cdat144,0.0,-1,1,2.0,NFRAMES144,navmask144, & + cb144,cdat2_144,xmax,bestf,cs144,xccs144) + call assert_close(xmax,0.0,'MSK144 zero correlation has zero metric') + call assert_close(bestf,-2.0,'MSK144 zero correlation selects first frequency') + call assert_true(all(cs144.eq.cmplx(0.0,0.0)), & + 'MSK144 zero correlation initializes averaged data') + call assert_true(all(xccs144.eq.0.0), & + 'MSK144 zero correlation initializes correlation data') + + cb40=cmplx(0.0,0.0) + cdat40=cmplx(0.0,0.0) + cdat2_40=cmplx(1.0,1.0) + cs40=cmplx(1.0,1.0) + xccs40=1.0 + navmask40=0 + xmax=1.0 + bestf=1.0 + call msk40_freq_search(cdat40,0.0,0,0,1.0,NFRAMES40,navmask40,cb40, & + cdat2_40,xmax,bestf,cs40,xccs40) + call assert_close(xmax,0.0,'empty MSK40 average has zero metric') + call assert_close(bestf,0.0,'empty MSK40 average has zero frequency') + call assert_true(all(cs40.eq.cmplx(0.0,0.0)), & + 'empty MSK40 average initializes averaged data') + call assert_true(all(xccs40.eq.0.0), & + 'empty MSK40 average initializes correlation data') + + nan_value=ieee_value(0.0,ieee_quiet_nan) + cdat40=cmplx(0.0,0.0) + cdat40(1)=cmplx(nan_value,0.0) + cs40=cmplx(1.0,1.0) + xccs40=1.0 + navmask40=1 + xmax=1.0 + bestf=1.0 + call msk40_freq_search(cdat40,0.0,0,0,1.0,NFRAMES40,navmask40,cb40, & + cdat2_40,xmax,bestf,cs40,xccs40) + call assert_close(xmax,0.0,'non-finite MSK40 correlation has zero metric') + call assert_close(bestf,0.0,'non-finite MSK40 correlation has zero frequency') + call assert_true(all(cs40.eq.cmplx(0.0,0.0)), & + 'non-finite MSK40 correlation keeps averaged data initialized') + call assert_true(all(xccs40.eq.0.0), & + 'non-finite MSK40 correlation keeps correlation data initialized') + end subroutine test_frequency_searches + + subroutine test_msk40_sync_column + integer, parameter :: NSPM=240 + complex :: cb(42),c(NSPM),cdat(NSPM) + integer :: navmask(1),npklocs(1),nsuccess + real :: fest + + call make_msk40_sync_word(cb) + cdat=cmplx(0.0,0.0) + cdat(1:42)=cb + navmask=1 + call msk40sync(cdat,1,0,1.0,navmask,1,0.0,fest,npklocs,nsuccess,c) + call assert_true(npklocs(1).eq.1, & + 'MSK40 lag-zero correlation remains in the first column bin') + end subroutine test_msk40_sync_column + + subroutine make_msk40_sync_word(cb) + complex, intent(out) :: cb(42) + integer :: i,s8r(8) + real :: angle,cbi(42),cbq(42),pi,pp(12) + + pi=4.0*atan(1.0) + do i=1,12 + angle=(i-1)*pi/12.0 + pp(i)=sin(angle) + enddo + s8r=(/1,0,1,1,0,0,0,1/) + s8r=2*s8r-1 + cbq(1:6)=pp(7:12)*s8r(1) + cbq(7:18)=pp*s8r(3) + cbq(19:30)=pp*s8r(5) + cbq(31:42)=pp*s8r(7) + cbi(1:12)=pp*s8r(2) + cbi(13:24)=pp*s8r(4) + cbi(25:36)=pp*s8r(6) + cbi(37:42)=pp(1:6)*s8r(8) + cb=cmplx(cbi,cbq) + end subroutine make_msk40_sync_word + + subroutine test_short_ping_input_bounds + integer, parameter :: NSPM40=240,MAXSTEPS40=150 + integer, parameter :: NSPM144=864,MAXSTEPS144=100 + integer, parameter :: N40=NSPM40+(MAXSTEPS40+1)*60 + integer, parameter :: N144=NSPM144+(MAXSTEPS144+1)*216 + character(len=12) :: hiscall,mycall + character(len=37) :: message + complex, allocatable :: c40(:),c144(:) + complex :: ct(NSPM144) + integer :: navg,nhasharray(MAXRECENT,MAXRECENT),nsuccess + logical(kind=1) :: bswl + real :: fret,nan_value,softbits(144),tret + + allocate(c40(N40),c144(N144)) + c144=cmplx(0.0,0.0) + c40=cmplx(0.0,0.0) + mycall='K1ABC' + hiscall='W9XYZ' + bswl=.false. + nhasharray=0 + + nsuccess=-1 + call msk144spd(c144,1,50,nsuccess,message,1500.0,fret,tret,navg,ct, & + softbits) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'short MSK144 input returns no decode') + + nsuccess=-1 + call msk40spd(c40,1,50,mycall,hiscall,bswl,nhasharray,nsuccess, & + message,1500.0,fret,tret,navg) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'short MSK40 input returns no decode') + + nsuccess=-1 + call msk144spd(c144,N144,50,nsuccess,message,1500.0,fret,tret,navg,ct, & + softbits) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'oversized MSK144 input returns no decode within metric bounds') + + nsuccess=-1 + call msk40spd(c40,N40,50,mycall,hiscall,bswl,nhasharray,nsuccess, & + message,1500.0,fret,tret,navg) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'oversized MSK40 input returns no decode within metric bounds') + + nsuccess=-1 + call msk144spd(c144,N144,-1,nsuccess,message,1500.0,fret,tret,navg,ct, & + softbits) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'reversed MSK144 windows return no decode') + + nsuccess=-1 + call msk40spd(c40,N40,-1,mycall,hiscall,bswl,nhasharray,nsuccess, & + message,1500.0,fret,tret,navg) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'reversed MSK40 windows return no decode') + + nsuccess=-1 + call msk144spd(c144,N144,huge(0),nsuccess,message,1500.0,fret,tret,navg, & + ct,softbits) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'extreme MSK144 tolerance returns no decode without overflow') + + nsuccess=-1 + call msk40spd(c40,N40,huge(0),mycall,hiscall,bswl,nhasharray,nsuccess, & + message,1500.0,fret,tret,navg) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'extreme MSK40 tolerance returns no decode without overflow') + + nsuccess=-1 + call msk144spd(c144,N144,50,nsuccess,message,huge(1.0),fret,tret,navg, & + ct,softbits) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'out-of-range MSK144 frequency returns no decode') + + nan_value=ieee_value(0.0,ieee_quiet_nan) + nsuccess=-1 + call msk40spd(c40,N40,50,mycall,hiscall,bswl,nhasharray,nsuccess, & + message,nan_value,fret,tret,navg) + call assert_true(nsuccess.eq.0 .and. len_trim(message).eq.0, & + 'non-finite MSK40 frequency returns no decode') + end subroutine test_short_ping_input_bounds + + subroutine assert_close(actual,expected,message) + real, intent(in) :: actual,expected + character(len=*), intent(in) :: message + + call assert_true(abs(actual-expected).lt.1.0e-6,message) + end subroutine assert_close + + subroutine assert_true(condition,message) + logical, intent(in) :: condition + character(len=*), intent(in) :: message + + if(.not.condition) then + write(*,'(a)') message + error stop 1 + endif + end subroutine assert_true + +end program test_msk_spectrum_edges diff --git a/tests/unit/network/CMakeLists.txt b/tests/unit/network/CMakeLists.txt new file mode 100644 index 00000000..6087a11d --- /dev/null +++ b/tests/unit/network/CMakeLists.txt @@ -0,0 +1,77 @@ +add_executable (test_pskreporter_ipfix + test_pskreporter_ipfix.cpp + ${CMAKE_SOURCE_DIR}/Network/PSKReporterIPFIX.cpp + ) +target_link_libraries (test_pskreporter_ipfix Qt5::Test) +add_test (NAME test_pskreporter_ipfix COMMAND test_pskreporter_ipfix) + +add_executable (test_pskreporter_transport + test_pskreporter_transport.cpp + ${CMAKE_SOURCE_DIR}/Network/PSKReporter.cpp + ${CMAKE_SOURCE_DIR}/Network/PSKReporterIPFIX.cpp + ) +target_link_libraries (test_pskreporter_transport wsjt_cxx Qt5::Test Qt5::Network) +add_test (NAME test_pskreporter_transport COMMAND test_pskreporter_transport) + +add_executable (test_map65_pskreporter_settings + test_map65_pskreporter_settings.cpp + ${CMAKE_SOURCE_DIR}/map65/pskreporter_settings.cpp + ) +target_link_libraries (test_map65_pskreporter_settings Qt5::Test) +add_test (NAME test_map65_pskreporter_settings COMMAND test_map65_pskreporter_settings) + +add_executable (test_map65_pskreporter_decode + test_map65_pskreporter_decode.cpp + ${CMAKE_SOURCE_DIR}/map65/pskreporter_decode.cpp + ${CMAKE_SOURCE_DIR}/Network/DecodedTime.cpp + ${CMAKE_SOURCE_DIR}/validators/LiveCQCallsign.cpp +) +target_link_libraries (test_map65_pskreporter_decode Qt5::Test) +add_test (NAME test_map65_pskreporter_decode COMMAND test_map65_pskreporter_decode) + +add_executable (test_wsprnet_upload + test_wsprnet_upload.cpp + ${CMAKE_SOURCE_DIR}/Network/wsprnet.cpp + ) +target_link_libraries (test_wsprnet_upload Qt5::Test Qt5::Network) +add_test (NAME test_wsprnet_upload COMMAND test_wsprnet_upload) + +add_executable (test_message_client_replay + test_message_client_replay.cpp + ) +target_link_libraries (test_message_client_replay wsjt_qt Qt5::Test Qt5::Network) +add_test (NAME test_message_client_replay COMMAND test_message_client_replay) + +add_executable (test_message_client_inhibit_status + test_message_client_inhibit_status.cpp + ) +target_link_libraries (test_message_client_inhibit_status wsjt_qt Qt5::Test Qt5::Network) +add_test (NAME test_message_client_inhibit_status COMMAND test_message_client_inhibit_status) + +add_executable (test_message_server + test_message_server.cpp + ) +target_link_libraries (test_message_server wsjtx_udp-static Qt5::Test Qt5::Network) +add_test (NAME test_message_server COMMAND test_message_server) + +add_executable (test_cloudlog_connection_check + test_cloudlog_connection_check.cpp + test_cloudlog_revision_stub.cpp + ${CMAKE_SOURCE_DIR}/Network/Cloudlog.cpp + ) +add_dependencies (test_cloudlog_connection_check revisiontag) +target_include_directories (test_cloudlog_connection_check PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_cloudlog_connection_check Boost::log Qt5::Test Qt5::Network Qt5::Widgets) +add_test (NAME test_cloudlog_connection_check COMMAND test_cloudlog_connection_check) + +if (WSJT_ENABLE_TSAN) + set (wsjt_tsan_network_test_environment + "QT_QPA_PLATFORM=offscreen" + "TSAN_OPTIONS=${wsjt_tsan_network_options}") + set_tests_properties ( + test_pskreporter_transport + test_message_client_replay + test_message_server + test_cloudlog_connection_check + PROPERTIES ENVIRONMENT "${wsjt_tsan_network_test_environment}") +endif () diff --git a/tests/unit/network/test_cloudlog_connection_check.cpp b/tests/unit/network/test_cloudlog_connection_check.cpp new file mode 100644 index 00000000..b9808ac5 --- /dev/null +++ b/tests/unit/network/test_cloudlog_connection_check.cpp @@ -0,0 +1,650 @@ +#include <QtTest> + +#include <QJsonDocument> +#include <QJsonObject> +#include <QNetworkAccessManager> +#include <QNetworkReply> +#include <QPointer> +#include <QTimer> + +#include "Network/Cloudlog.hpp" + +class TestCloudlogConfiguration final + : public CloudlogConfiguration +{ +public: + TestCloudlogConfiguration (QString const& url, QString const& apiKey, qint32 stationId) + : url {url} + , apiKey {apiKey} + , stationId {stationId} + { + } + + QString url; + QString apiKey; + qint32 stationId {0}; + + QString cloudlog_api_url () const override + { + return url; + } + + QString cloudlog_api_key () const override + { + return apiKey; + } + + qint32 cloudlog_api_station_id () const override + { + return stationId; + } +}; + +namespace +{ + struct FakeResponse + { + FakeResponse () = default; + FakeResponse (int status, QByteArray const& body, QNetworkReply::NetworkError error = QNetworkReply::NoError, + QString const& errorString = {}, bool autoFinish = true) + : status {status} + , body {body} + , error {error} + , errorString {errorString} + , autoFinish {autoFinish} + { + } + + int status {200}; + QByteArray body; + QNetworkReply::NetworkError error {QNetworkReply::NoError}; + QString errorString; + bool autoFinish {true}; + }; + + struct CapturedRequest + { + QString method; + QUrl url; + QByteArray payload; + QByteArray contentType; + QByteArray accept; + }; + + class FakeReply final + : public QNetworkReply + { + Q_OBJECT + + public: + FakeReply (QNetworkRequest const& request, FakeResponse const& response, QObject * parent) + : QNetworkReply {parent} + , data_ {response.body} + { + setRequest (request); + setUrl (request.url ()); + setOpenMode (QIODevice::ReadOnly); + if (response.status) + { + setAttribute (QNetworkRequest::HttpStatusCodeAttribute, response.status); + } + if (QNetworkReply::NoError != response.error) + { + setError (response.error, response.errorString); + } + + if (response.autoFinish) + { + QTimer::singleShot (0, this, [this] { + finishNow (); + }); + } + } + + void finishNow () + { + if (finished_) + { + return; + } + finished_ = true; + setFinished (true); + Q_EMIT readyRead (); + Q_EMIT finished (); + } + + void abort () override + { + setError (QNetworkReply::OperationCanceledError, QStringLiteral ("operation canceled")); + } + + qint64 bytesAvailable () const override + { + return data_.size () - offset_ + QNetworkReply::bytesAvailable (); + } + + protected: + qint64 readData (char * buffer, qint64 maxSize) override + { + auto const remaining = data_.size () - offset_; + if (remaining <= 0) + { + return -1; + } + auto const size = qMin (maxSize, static_cast<qint64> (remaining)); + memcpy (buffer, data_.constData () + offset_, static_cast<size_t> (size)); + offset_ += size; + return size; + } + + private: + QByteArray data_; + qint64 offset_ {0}; + bool finished_ {false}; + }; + + class FakeNetworkAccessManager final + : public QNetworkAccessManager + { + Q_OBJECT + + public: + void queueResponse (FakeResponse const& response) + { + responses_.append (response); + } + + void queueJson (int status, QByteArray const& body, QNetworkReply::NetworkError error = QNetworkReply::NoError, + QString const& errorString = {}) + { + queueResponse ({status, body, error, errorString}); + } + + void queueWritableJsonAuth () + { + queueJson (200, QByteArray {R"({"status":"valid","rights":"rw"})"}); + } + + void queueStationInfo (QByteArray const& body) + { + queueJson (200, body); + } + + void queueManifest (QByteArray const& body, int status = 200) + { + queueJson (status, body, status >= 400 ? QNetworkReply::ContentNotFoundError : QNetworkReply::NoError, + status >= 400 ? QStringLiteral ("not found") : QString {}); + } + + QList<CapturedRequest> requests () const + { + return requests_; + } + + QList<QPointer<FakeReply>> replies () const + { + return replies_; + } + + protected: + QNetworkReply * createRequest (Operation operation, QNetworkRequest const& request, QIODevice * outgoingData) override + { + CapturedRequest captured; + captured.method = operation == GetOperation ? QStringLiteral ("GET") : QStringLiteral ("POST"); + captured.url = request.url (); + captured.contentType = request.header (QNetworkRequest::ContentTypeHeader).toByteArray (); + captured.accept = request.rawHeader ("Accept"); + if (outgoingData) + { + captured.payload = outgoingData->readAll (); + } + requests_.append (captured); + + auto response = responses_.isEmpty () ? FakeResponse {404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")} : responses_.takeFirst (); + auto * reply = new FakeReply {request, response, this}; + replies_.append (reply); + return reply; + } + + private: + QList<FakeResponse> responses_; + QList<CapturedRequest> requests_; + QList<QPointer<FakeReply>> replies_; + }; + + Cloudlog::ConnectionCheckResult runCheck (FakeNetworkAccessManager& network, int stationId = 7) + { + Cloudlog cloudlog {nullptr, &network}; + QSignalSpy spy {&cloudlog, &Cloudlog::connection_check_finished}; + cloudlog.checkConnection ({QStringLiteral (" https://example.test/api/qso/ "), + QStringLiteral ("secret/key"), + stationId}); + if (spy.isEmpty ()) + { + spy.wait (1000); + } + Q_ASSERT (!spy.isEmpty ()); + return qvariant_cast<Cloudlog::ConnectionCheckResult> (spy.takeFirst ().at (0)); + } + + QByteArray json (QString const& text) + { + return text.toUtf8 (); + } + + Cloudlog::UploadResult runLogQso (FakeNetworkAccessManager& network, FakeResponse const& response) + { + TestCloudlogConfiguration configuration { + QStringLiteral (" https://example.test/index.php/api/qso/ "), + QStringLiteral ("secret/key"), + 7}; + network.queueResponse (response); + + Cloudlog cloudlog {&configuration, &network}; + QSignalSpy spy {&cloudlog, &Cloudlog::qso_upload_finished}; + cloudlog.logQso (QByteArray {"<call:5>K1ABC"}); + if (spy.isEmpty ()) + { + spy.wait (1000); + } + Q_ASSERT (!spy.isEmpty ()); + return qvariant_cast<Cloudlog::UploadResult> (spy.takeFirst ().at (0)); + } + + int qsoTruePostCount (QList<CapturedRequest> const& requests) + { + int count {0}; + for (auto const& request : requests) + { + if (request.method == QStringLiteral ("POST") && request.url.path ().endsWith (QStringLiteral ("/qso/true"))) + { + ++count; + } + } + return count; + } +} + +class TestCloudlogConnectionCheck final + : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void initTestCase () + { + qRegisterMetaType<Cloudlog::ConnectionCheckResult> ("Cloudlog::ConnectionCheckResult"); + qRegisterMetaType<Cloudlog::ConnectionCheckResult> ("ConnectionCheckResult"); + qRegisterMetaType<Cloudlog::UploadResult> ("Cloudlog::UploadResult"); + qRegisterMetaType<Cloudlog::UploadResult> ("UploadResult"); + } + + void normalizesBaseUrl_data () + { + QTest::addColumn<QString> ("input"); + QTest::addColumn<QString> ("expected"); + + QTest::newRow ("base") << "https://log.example" << "https://log.example"; + QTest::newRow ("trailing slash") << "https://log.example/" << "https://log.example"; + QTest::newRow ("api qso") << " https://log.example/api/qso/ " << "https://log.example"; + QTest::newRow ("index qso") << "https://log.example/index.php/api/qso/" << "https://log.example"; + } + + void normalizesBaseUrl () + { + QFETCH (QString, input); + QFETCH (QString, expected); + + QCOMPARE (Cloudlog::normalizeBaseUrl (input), expected); + } + + void buildsEscapedJsonPayload () + { + auto const payload = Cloudlog::qsoUploadPayload (QStringLiteral ("key\"with\\chars"), 42, QByteArray {"<call:6>K1\"ABC<comment:8>a\\b\nc"}); + auto const document = QJsonDocument::fromJson (payload); + QVERIFY (document.isObject ()); + auto const object = document.object (); + QCOMPARE (object.value (QStringLiteral ("key")).toString (), QStringLiteral ("key\"with\\chars")); + QCOMPARE (object.value (QStringLiteral ("station_profile_id")).toString (), QStringLiteral ("42")); + QCOMPARE (object.value (QStringLiteral ("type")).toString (), QStringLiteral ("adif")); + QCOMPARE (object.value (QStringLiteral ("string")).toString (), QStringLiteral ("<call:6>K1\"ABC<comment:8>a\\b\nc<eor>")); + } + + void classifiesQsoUploadReplies_data () + { + QTest::addColumn<int> ("httpStatus"); + QTest::addColumn<int> ("networkError"); + QTest::addColumn<QString> ("errorString"); + QTest::addColumn<QByteArray> ("body"); + QTest::addColumn<Cloudlog::UploadStatus> ("expectedStatus"); + QTest::addColumn<QString> ("expectedDetail"); + + QTest::newRow ("success created") + << 201 + << static_cast<int> (QNetworkReply::NoError) + << QString {} + << json (R"({"status":"created"})") + << Cloudlog::UploadStatus::Success + << QString {}; + + QTest::newRow ("transport") + << 0 + << static_cast<int> (QNetworkReply::HostNotFoundError) + << QStringLiteral ("host not found") + << QByteArray {} + << Cloudlog::UploadStatus::NetworkError + << QStringLiteral ("host not found"); + + QTest::newRow ("http non-json") + << 500 + << static_cast<int> (QNetworkReply::InternalServerError) + << QStringLiteral ("server error") + << QByteArray {"internal error"} + << Cloudlog::UploadStatus::HttpError + << QStringLiteral ("HTTP status 500"); + + QTest::newRow ("http json") + << 403 + << static_cast<int> (QNetworkReply::ContentAccessDenied) + << QStringLiteral ("forbidden") + << json (R"({"message":"missing upload rights"})") + << Cloudlog::UploadStatus::HttpError + << QStringLiteral ("missing upload rights"); + + QTest::newRow ("server failed") + << 200 + << static_cast<int> (QNetworkReply::NoError) + << QString {} + << json (R"({"status":"failed","reason":"bad ADIF"})") + << Cloudlog::UploadStatus::Rejected + << QStringLiteral ("bad ADIF"); + + QTest::newRow ("non-json success code") + << 200 + << static_cast<int> (QNetworkReply::NoError) + << QString {} + << QByteArray {"ok"} + << Cloudlog::UploadStatus::UnexpectedResponse + << QStringLiteral ("illegal value"); + } + + void classifiesQsoUploadReplies () + { + QFETCH (int, httpStatus); + QFETCH (int, networkError); + QFETCH (QString, errorString); + QFETCH (QByteArray, body); + QFETCH (Cloudlog::UploadStatus, expectedStatus); + QFETCH (QString, expectedDetail); + + FakeNetworkAccessManager network; + auto const result = runLogQso (network, {httpStatus, body, static_cast<QNetworkReply::NetworkError> (networkError), errorString}); + + QCOMPARE (result.status, expectedStatus); + QCOMPARE (result.httpStatusCode, httpStatus); + QCOMPARE (network.requests ().size (), 1); + QCOMPARE (network.requests ().at (0).method, QStringLiteral ("POST")); + QCOMPARE (network.requests ().at (0).url.path (), QStringLiteral ("/index.php/api/qso")); + QCOMPARE (network.requests ().at (0).contentType, QByteArray {"application/json"}); + QCOMPARE (network.requests ().at (0).accept, QByteArray {"application/json"}); + if (!expectedDetail.isEmpty ()) + { + QVERIFY2 (result.detail.contains (expectedDetail), qPrintable (result.detail)); + } + } + + void emitsOnlySuccessForAcceptedQsoUpload () + { + FakeNetworkAccessManager network; + auto const result = runLogQso (network, {201, json (R"({"status":"created"})")}); + + QCOMPARE (result.status, Cloudlog::UploadStatus::Success); + QVERIFY (result.message.isEmpty ()); + QVERIFY (result.detail.isEmpty ()); + QCOMPARE (result.httpStatusCode, 201); + } + + void acceptsWritableClassicWithoutDryRun () + { + FakeNetworkAccessManager network; + network.queueResponse ({404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")}); + network.queueResponse ({404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")}); + network.queueResponse ({200, QByteArray {"<auth><status>Valid</status><rights>rw</rights></auth>"}}); + network.queueResponse ({200, json (R"([{"station_id":"7","station_profile_name":"Home","station_callsign":"K1ABC"}])")}); + network.queueResponse ({200, json (R"({"name":"Cloudlog","short_name":"Cloudlog"})")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::Success); + QVERIFY (result.detail.contains (QStringLiteral ("No safe dry-run QSO endpoint"))); + auto const requests = network.requests (); + QCOMPARE (requests.size (), 5); + QCOMPARE (requests.at (0).url.path (QUrl::FullyEncoded), QStringLiteral ("/api/check_auth/secret%2Fkey")); + QCOMPARE (requests.at (2).url.path (QUrl::FullyEncoded), QStringLiteral ("/index.php/api/auth/secret%2Fkey")); + QCOMPARE (requests.at (3).url.path (QUrl::FullyEncoded), QStringLiteral ("/index.php/api/station_info/secret%2Fkey")); + QCOMPARE (requests.at (4).url.path (), QStringLiteral ("/manifest.json")); + QCOMPARE (qsoTruePostCount (requests), 0); + } + + void acceptsJsonCloudlogWithoutDryRun () + { + FakeNetworkAccessManager network; + network.queueWritableJsonAuth (); + network.queueStationInfo (json (R"([{"station_id":7,"station_profile_name":"Home"}])")); + network.queueManifest (json (R"({"name":"Cloudlog"})")); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::Success); + QVERIFY (result.detail.contains (QStringLiteral ("No safe dry-run QSO endpoint"))); + auto const requests = network.requests (); + QCOMPARE (requests.size (), 3); + QCOMPARE (requests.at (2).url.path (), QStringLiteral ("/manifest.json")); + QCOMPARE (qsoTruePostCount (requests), 0); + } + + void reportsReadOnlyKey () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"r"})")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::ReadOnlyKey); + QVERIFY (result.detail.contains (QStringLiteral ("read/write API key"))); + QCOMPARE (network.requests ().size (), 1); + } + + void reportsInvalidKey () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"invalid","message":"bad key"})")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::InvalidKey); + QCOMPARE (result.detail, QStringLiteral ("bad key")); + } + + void rejectsAuthWithoutRights () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid"})")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::UnexpectedResponse); + QVERIFY (result.detail.contains (QStringLiteral ("rights"))); + } + + void rejectsXmlAuthWithoutRights () + { + FakeNetworkAccessManager network; + network.queueResponse ({404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")}); + network.queueResponse ({404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")}); + network.queueResponse ({200, QByteArray {"<auth><status>Valid</status></auth>"}}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::UnexpectedResponse); + QVERIFY (result.detail.contains (QStringLiteral ("rights"))); + } + + void reportsMissingStationProfile () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})")}); + network.queueResponse ({200, json (R"([{"station_id":"8","station_profile_name":"Portable","station_callsign":"K1ABC/P"}])")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::StationProfileUnavailable); + QVERIFY (result.detail.contains (QStringLiteral ("8 - Portable - K1ABC/P"))); + QCOMPARE (result.stationProfiles.size (), 1); + QCOMPARE (result.stationProfiles.at (0).id, 8); + QCOMPARE (result.stationProfiles.at (0).name, QStringLiteral ("Portable")); + QCOMPARE (result.stationProfiles.at (0).callsign, QStringLiteral ("K1ABC/P")); + } + + void ignoresNestedNonStationObjects () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})")}); + network.queueResponse ({200, json (R"({"metadata":{"id":7,"name":"Not a station"},"stations":[{"station_id":8,"station_profile_name":"Portable"}]})")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::StationProfileUnavailable); + QVERIFY (!result.detail.contains (QStringLiteral ("Not a station"))); + QVERIFY (result.detail.contains (QStringLiteral ("8 - Portable"))); + QCOMPARE (result.stationProfiles.size (), 1); + QCOMPARE (result.stationProfiles.at (0).id, 8); + } + + void acceptsCurrentWavelogDryRunResponse () + { + FakeNetworkAccessManager network; + network.queueWritableJsonAuth (); + network.queueStationInfo (json (R"({"stations":[{"station_id":7,"station_profile_name":"Home"}]})")); + network.queueManifest (json (R"({"name":"Wavelog","short_name":"Wavelog"})")); + network.queueJson (201, json (R"({"status":"created","type":"adif","string":"","adif_count":0,"adif_errors":0,"messages":["Dryrun works"]})")); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::Success); + QVERIFY (result.detail.contains (QStringLiteral ("dry-run QSO upload"))); + QCOMPARE (result.stationProfiles.size (), 1); + QCOMPARE (result.stationProfiles.at (0).id, 7); + auto const requests = network.requests (); + QCOMPARE (requests.size (), 4); + QCOMPARE (requests.at (2).method, QStringLiteral ("GET")); + QCOMPARE (requests.at (2).url.path (), QStringLiteral ("/manifest.json")); + QCOMPARE (requests.at (3).method, QStringLiteral ("POST")); + QCOMPARE (requests.at (3).url.path (), QStringLiteral ("/api/qso/true")); + QCOMPARE (requests.at (3).contentType, QByteArray {"application/json"}); + QCOMPARE (requests.at (3).accept, QByteArray {"application/json"}); + auto const payload = QJsonDocument::fromJson (requests.at (3).payload).object (); + QCOMPARE (payload.value (QStringLiteral ("station_profile_id")).toString (), QStringLiteral ("7")); + QCOMPARE (payload.value (QStringLiteral ("type")).toString (), QStringLiteral ("adif")); + } + + void acceptsUnknownManifestWithoutDryRun () + { + FakeNetworkAccessManager network; + network.queueWritableJsonAuth (); + network.queueStationInfo (json (R"([{"station_id":7}])")); + network.queueManifest (QByteArray {"not found"}, 404); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::Success); + QVERIFY (result.detail.contains (QStringLiteral ("No safe dry-run QSO endpoint"))); + QCOMPARE (qsoTruePostCount (network.requests ()), 0); + } + + void reportsDryRunForbidden () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})")}); + network.queueResponse ({200, json (R"([{"station_id":7}])")}); + network.queueResponse ({200, json (R"({"short_name":"Wavelog"})")}); + network.queueResponse ({403, json (R"({"status":"failed","reason":"read-only upload key"})"), QNetworkReply::ContentAccessDenied, QStringLiteral ("forbidden")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::UploadShapeRejected); + QCOMPARE (result.detail, QStringLiteral ("read-only upload key")); + } + + void reportsDryRunAdifMessages () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})")}); + network.queueResponse ({200, json (R"([{"station_id":7}])")}); + network.queueResponse ({200, json (R"({"name":"Wavelog"})")}); + network.queueResponse ({400, json (R"({"status":"failed","messages":["station_profile_id is required","bad ADIF"]})"), QNetworkReply::ProtocolInvalidOperationError, QStringLiteral ("bad request")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::UploadShapeRejected); + QVERIFY (result.detail.contains (QStringLiteral ("station_profile_id is required"))); + QVERIFY (result.detail.contains (QStringLiteral ("bad ADIF"))); + } + + void reportsNetworkFailure () + { + FakeNetworkAccessManager network; + network.queueResponse ({0, {}, QNetworkReply::HostNotFoundError, QStringLiteral ("host not found")}); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::NetworkError); + QCOMPARE (result.detail, QStringLiteral ("host not found")); + } + + void reportsStationInfoNotJson () + { + FakeNetworkAccessManager network; + network.queueWritableJsonAuth (); + network.queueJson (404, QByteArray {"not found"}, QNetworkReply::ContentNotFoundError, QStringLiteral ("not found")); + + auto const result = runCheck (network); + + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::UnexpectedResponse); + QVERIFY (result.message.contains (QStringLiteral ("Station profile response"))); + } + + void ignoresStaleOverlappingConnectionCheckReply () + { + FakeNetworkAccessManager network; + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})"), QNetworkReply::NoError, {}, false}); + network.queueResponse ({200, json (R"({"status":"valid","rights":"rw"})")}); + network.queueResponse ({200, json (R"([{"station_id":9}])")}); + network.queueResponse ({200, json (R"({"name":"Cloudlog"})")}); + + Cloudlog cloudlog {nullptr, &network}; + QSignalSpy spy {&cloudlog, &Cloudlog::connection_check_finished}; + cloudlog.checkConnection ({QStringLiteral ("https://first.example"), QStringLiteral ("first"), 7}); + auto replies = network.replies (); + QCOMPARE (replies.size (), 1); + QVERIFY (replies.at (0)); + auto * stale = replies.at (0).data (); + + cloudlog.checkConnection ({QStringLiteral ("https://second.example"), QStringLiteral ("second"), 9}); + stale->finishNow (); + + if (spy.isEmpty ()) + { + spy.wait (1000); + } + QCOMPARE (spy.size (), 1); + auto const result = qvariant_cast<Cloudlog::ConnectionCheckResult> (spy.takeFirst ().at (0)); + QCOMPARE (result.status, Cloudlog::ConnectionCheckStatus::Success); + QCOMPARE (result.normalizedBaseUrl, QStringLiteral ("https://second.example")); + QCOMPARE (qsoTruePostCount (network.requests ()), 0); + } +}; + +QTEST_GUILESS_MAIN (TestCloudlogConnectionCheck) + +#include "test_cloudlog_connection_check.moc" diff --git a/tests/unit/network/test_cloudlog_revision_stub.cpp b/tests/unit/network/test_cloudlog_revision_stub.cpp new file mode 100644 index 00000000..9b63084c --- /dev/null +++ b/tests/unit/network/test_cloudlog_revision_stub.cpp @@ -0,0 +1,6 @@ +#include "revision_utils.hpp" + +QString http_user_agent () +{ + return QStringLiteral ("WSJT-X/test"); +} diff --git a/tests/unit/network/test_map65_pskreporter_decode.cpp b/tests/unit/network/test_map65_pskreporter_decode.cpp new file mode 100644 index 00000000..a2c847d9 --- /dev/null +++ b/tests/unit/network/test_map65_pskreporter_decode.cpp @@ -0,0 +1,166 @@ +#include <QtTest> + +#include <QDateTime> + +#include "map65/pskreporter_decode.h" + +namespace +{ + QDateTime nowUtc() + { + return {QDate {2026, 8, 17}, QTime {12, 34, 56}, Qt::UTC}; + } + + QString decodeLine(QStringList const& message, QString const& time = "1234") + { + return (QStringList {"50313.0", "1000", "0.1", time, "-12"} + message) + .join(' '); + } + +} + +class TestMap65PSKReporterDecode final : public QObject +{ + Q_OBJECT + +private slots: + void acceptsMap65Callsigns() + { + const auto valid = QStringList { + "K1ABC", "YW18FIFA", "QU1RK", "<K1ABC>", "K1ABC/P", "N5L", "GM/N5L" + }; + for (auto const& callsign : valid) { + QVERIFY2(Map65PSKReporter::isValidMap65Callsign(callsign), + qPrintable(callsign)); + } + + const auto invalid = QStringList { + "", "N", "N5", "KABC", "Q1ABC", "K1AB1", "K1ABCDE", "K1AB-C", "K1AB?" + }; + for (auto const& callsign : invalid) { + QVERIFY2(!Map65PSKReporter::isValidMap65Callsign(callsign), + qPrintable(callsign)); + } + } + + void parsesFourDecodeLayouts() + { + QStringList seen; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + { + decodeLine({"CQ", "K1ABC", "1200.0", "#A"}), + decodeLine({"CQ", "K1ABC", "FN20", "1200.0", ":B"}), + decodeLine({"CQ", "DX", "K1ABC", "1200.0", "#C"}), + decodeLine({"CQ", "DX", "K1ABC", "FN20", "1200.0", ":D"}) + }, "N0CALL", "FN21", nowUtc(), seen); + + QCOMPARE(spots.size(), 4); + QCOMPARE(spots.at(0).callsign, QString {"K1ABC"}); + QCOMPARE(spots.at(0).locator, QString {"--"}); + QCOMPARE(spots.at(0).mode, QString {"JT65A"}); + QCOMPARE(spots.at(1).locator, QString {"FN20"}); + QCOMPARE(spots.at(1).mode, QString {"Q65-60B"}); + QCOMPARE(spots.at(2).locator, QString {"--"}); + QCOMPARE(spots.at(2).mode, QString {"JT65C"}); + QCOMPARE(spots.at(3).locator, QString {"FN20"}); + QCOMPARE(spots.at(3).mode, QString {"Q65-60D"}); + } + + void acceptsAllReportableMessageTypes() + { + QStringList seen; + QStringList lines; + for (auto const& type : {QString {"CQ"}, QString {"QRZ"}, QString {"CQV"}, + QString {"CQH"}, QString {"QRT"}}) { + lines.append(decodeLine({type, "K1ABC", "1200.0", "#A"})); + } + lines.append(decodeLine({"DE", "K1ABC", "1200.0", "#A"})); + + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + lines, "N0CALL", "FN21", nowUtc(), seen); + QCOMPARE(spots.size(), 5); + } + + void preservesSpotFieldsAndLegacySnr() + { + QStringList seen; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + {decodeLine({"CQ", "k1abc", "1200.0", "#A"})}, + "N0CALL", "FN21", nowUtc(), seen); + QCOMPARE(spots.size(), 1); + auto const& spot = spots.first(); + QCOMPARE(spot.callsign, QString {"K1ABC"}); + QCOMPARE(spot.frequency, Radio::Frequency {50313000000LL}); + QCOMPARE(spot.snr, -10); + auto const expectedTime = QDateTime { + QDate {2026, 8, 17}, QTime {12, 34, 0}, Qt::UTC}; + QCOMPARE(spot.time, expectedTime); + } + + void rollsLateDecodeToPreviousUtcDate() + { + QStringList seen; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + {decodeLine({"CQ", "K1ABC", "235940.0", "#A"}, "235940")}, + "N0CALL", "FN21", nowUtc(), seen); + QCOMPARE(spots.size(), 1); + auto const expectedTime = QDateTime { + QDate {2026, 8, 16}, QTime {23, 59, 40}, Qt::UTC}; + QCOMPARE(spots.first().time, expectedTime); + } + + void acceptsThreeCharacterCallsignDecode() + { + QStringList seen; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + {decodeLine({"CQ", "N5L", "1200.0", "#A"})}, + "N0CALL", "FN21", nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(spots.first().callsign, QString {"N5L"}); + } + + void suppressesDuplicateDecodeKeys() + { + auto const first = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}) + + " trailing-one"; + auto const second = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}) + + " trailing-two"; + QCOMPARE(first.left(53), second.left(53)); + + QStringList seen; + auto const spots = Map65PSKReporter::parseMap65PSKReporterSpots( + {first, second}, "N0CALL", "FN21", nowUtc(), seen); + QCOMPARE(spots.size(), 1); + QCOMPARE(seen.size(), 1); + } + + void rejectsMalformedInput() + { + const auto valid = decodeLine({"CQ", "K1ABC", "1200.0", "#A"}); + const auto malformed = QStringList { + QString {}, + "50313.0 1000 0.1 1234 -12 CQ", + decodeLine({"DE", "K1ABC", "1200.0", "#A"}), + decodeLine({"CQ", "KABC", "1200.0", "#A"}), + decodeLine({"CQ", "K1ABC", "not-a-time", "#A"}), + decodeLine({"CQ", "K1ABC", "1200.0", "?A"}) + }; + + for (auto const& line : malformed) { + QStringList seen; + QVERIFY(Map65PSKReporter::parseMap65PSKReporterSpots( + {line}, "N0CALL", "FN21", nowUtc(), seen).isEmpty()); + } + + QStringList seen; + QVERIFY(Map65PSKReporter::parseMap65PSKReporterSpots( + {valid}, "NO", "FN21", nowUtc(), seen).isEmpty()); + QVERIFY(seen.isEmpty()); + QVERIFY(Map65PSKReporter::parseMap65PSKReporterSpots( + {valid}, "N0CALL", "FN", nowUtc(), seen).isEmpty()); + } +}; + +QTEST_APPLESS_MAIN(TestMap65PSKReporterDecode) + +#include "test_map65_pskreporter_decode.moc" diff --git a/tests/unit/network/test_map65_pskreporter_settings.cpp b/tests/unit/network/test_map65_pskreporter_settings.cpp new file mode 100644 index 00000000..432d533e --- /dev/null +++ b/tests/unit/network/test_map65_pskreporter_settings.cpp @@ -0,0 +1,49 @@ +#include <QtTest> + +#include <QSettings> +#include <QTemporaryDir> + +#include "map65/pskreporter_settings.h" + +class TestMap65PSKReporterSettings final : public QObject +{ + Q_OBJECT + +private slots: + void defaultsToEnabledUdp() + { + QTemporaryDir directory; + QVERIFY(directory.isValid()); + + QSettings settings {directory.filePath("map65.ini"), QSettings::IniFormat}; + auto const values = readMap65PSKReporterSettings(settings); + + QVERIFY(values.enabled); + QVERIFY(!values.use_tcpip); + } + + void preservesExplicitEnableAndTransportValues() + { + QTemporaryDir directory; + QVERIFY(directory.isValid()); + auto const filename = directory.filePath("map65.ini"); + { + QSettings settings {filename, QSettings::IniFormat}; + settings.beginGroup("Common"); + settings.setValue("spotPSK", false); + settings.setValue("PSKReporterTCPIP", true); + settings.endGroup(); + settings.sync(); + } + + QSettings settings {filename, QSettings::IniFormat}; + auto const values = readMap65PSKReporterSettings(settings); + + QVERIFY(!values.enabled); + QVERIFY(values.use_tcpip); + } +}; + +QTEST_MAIN(TestMap65PSKReporterSettings) + +#include "test_map65_pskreporter_settings.moc" diff --git a/tests/unit/network/test_message_client_inhibit_status.cpp b/tests/unit/network/test_message_client_inhibit_status.cpp new file mode 100644 index 00000000..6dc77367 --- /dev/null +++ b/tests/unit/network/test_message_client_inhibit_status.cpp @@ -0,0 +1,315 @@ +#include <QtTest> + +#include <QHostAddress> +#include <QNetworkDatagram> +#include <QUdpSocket> + +#include <memory> + +#include "Network/MessageClient.hpp" +#include "Network/NetworkMessage.hpp" + +class TestMessageClientInhibitStatus final + : public QObject +{ + Q_OBJECT + +private: + static QByteArray command (quint32 ttl = 1000, QByteArray controller = "key-agent", + QByteArray station = "W2SZ", QString id = "test-client", + quint32 schema = 2) + { + QByteArray message; + NetworkMessage::Builder out {&message, NetworkMessage::TxInhibit, id, schema}; + out << controller << ttl << station; + return message; + } + +private Q_SLOTS: + void acceptUdpRequestsAuthorizesCommands () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", + receiver.localPort (), {}, 1}; + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + auto const endpoint = receiver.receiveDatagram (); + QSignalSpy commands {&client, &MessageClient::tx_inhibit_command}; + QSignalSpy clears {&client, &MessageClient::clear_decodes}; + QSignalSpy invalid {&client, &MessageClient::tx_inhibit_invalid}; + QByteArray clear; + NetworkMessage::Builder out {&clear, NetworkMessage::Clear, "test-client", 2}; + out << quint8 {2}; + auto send = [&] (QByteArray const& bytes) { + QCOMPARE (receiver.writeDatagram (bytes, endpoint.senderAddress (), endpoint.senderPort ()), + qint64 (bytes.size ())); + }; + send (command ()); + send (command (99)); + send (clear); + QTest::qWait (150); + QCOMPARE (commands.size (), 0); + QCOMPARE (invalid.size (), 0); + QCOMPARE (clears.size (), 0); + client.enable (true); + send (command (100)); + send (command (30000, "key-agent", "Priority", "test-client", 3)); + send (command (0, "key-agent", {})); + QTRY_COMPARE (commands.size (), 3); + QCOMPARE (commands[0][0].toString (), QString {"key-agent"}); + QCOMPARE (commands[0][1].toUInt (), 100u); + QCOMPARE (commands[1][1].toUInt (), 30000u); + QCOMPARE (commands[1][2].toString (), QString {"Priority"}); + QCOMPARE (commands[2][1].toUInt (), 0u); + QVERIFY (commands[2][2].toString ().isEmpty ()); + send (command (1000, "key-agent", {}, "other-instance")); + send (clear); + QTRY_COMPARE (clears.size (), 1); + QCOMPARE (commands.size (), 3); + client.enable (false); + send (command ()); + send (command (99)); + send (clear); + QTest::qWait (150); + QCOMPARE (commands.size (), 3); + QCOMPARE (invalid.size (), 0); + QCOMPARE (clears.size (), 1); + } + + void rejectsMalformedCommands () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", + receiver.localPort (), {}, 1}; + client.enable (true); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + auto const endpoint = receiver.receiveDatagram (); + QSignalSpy commands {&client, &MessageClient::tx_inhibit_command}; + QSignalSpy invalid {&client, &MessageClient::tx_inhibit_invalid}; + QList<QByteArray> bad { + command (99), command (30001), command (0xffffffff), command (1000, {}), + command (1000, "two words"), command (1000, QByteArray (129, 'a')), + command (1000, QByteArray ("\xc0\xaf", 2)), command (1000, "key", QByteArray (129, 'a')), + command (1000, "key", QByteArray ("\xff", 1)), command (1000, "key", "line\nbreak"), + command (1000, "key", {}, "test-client", 1), command () + QByteArray (4096, 'a') + }; + auto const valid = command (); + for (int length = 12; length < valid.size (); ++length) bad.append (valid.left (length)); + auto corrupt = valid; + corrupt[0] = 0; + bad.append (corrupt); + corrupt = valid; + corrupt[7] = 99; + bad.append (corrupt); + corrupt = valid; + for (int index = 12; index < 16; ++index) corrupt[index] = char (0xff); + bad.append (corrupt); + for (auto const& bytes : bad) + QCOMPARE (receiver.writeDatagram (bytes, endpoint.senderAddress (), endpoint.senderPort ()), + qint64 (bytes.size ())); + auto count = [&] { + quint64 result {0}; + for (auto const& event : invalid) result += event[0].toULongLong (); + return result; + }; + QTRY_COMPARE (count (), quint64 (bad.size ())); + QCOMPARE (commands.size (), 0); + QVERIFY (invalid.size () < bad.size ()); + auto extended = command () + QByteArray {"future fields"}; + receiver.writeDatagram (extended, endpoint.senderAddress (), endpoint.senderPort ()); + QTRY_COMPARE (commands.size (), 1); + } + + void receivesCommandsWhenOutgoingReportingIsDisabled () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", + receiver.localPort (), {}, 1}; + client.enable (true); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + auto const endpoint = receiver.receiveDatagram (); + QSignalSpy commands {&client, &MessageClient::tx_inhibit_command}; + client.set_server_port (0); + auto const bytes = command (); + QCOMPARE (receiver.writeDatagram (bytes, endpoint.senderAddress (), endpoint.senderPort ()), + qint64 (bytes.size ())); + QTRY_COMPARE (commands.size (), 1); + } + + void reportsInvalidServerThroughExistingErrorSignal () + { + MessageClient client {"test-client", "version", "revision", "", 0, {}, 1}; + QSignalSpy errors {&client, &MessageClient::error}; + client.set_server ("255.255.255.255", {}); + QCOMPARE (errors.size (), 1); + QVERIFY (errors[0][0].toString ().contains ("IPv4 broadcast not supported")); + } + + void portChangeDuringLookupDoesNotCloseClient () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::Any}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", 0, {}, 1}; + QSignalSpy closed {&client, &MessageClient::close}; + client.set_server ("localhost", {}); + client.set_server_port (receiver.localPort ()); + QCOMPARE (closed.size (), 0); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + QCOMPARE (closed.size (), 0); + } + + void advertisementTracksRequestAuthorization () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", + receiver.localPort (), {}, 1}; + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + while (receiver.hasPendingDatagrams ()) receiver.receiveDatagram (); + + client.inhibit_status (true, true, QStringLiteral ("W2SZ"), 11, 12, 13, 14); + QTest::qWait (50); + QVERIFY (!receiver.hasPendingDatagrams ()); + + client.enable (true); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + NetworkMessage::Reader available {receiver.receiveDatagram ().data ()}; + bool supported {false}; + bool inhibited {false}; + QByteArray source; + quint32 hold_rx {0}; + quint32 release_rx {0}; + quint32 expiries {0}; + quint32 invalid {0}; + available >> supported >> inhibited >> source >> hold_rx >> release_rx + >> expiries >> invalid; + QCOMPARE (available.type (), NetworkMessage::InhibitStatus); + QVERIFY (supported); + QVERIFY (inhibited); + QCOMPARE (source, QByteArrayLiteral ("W2SZ")); + + client.enable (false); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + NetworkMessage::Reader withdrawn {receiver.receiveDatagram ().data ()}; + withdrawn >> supported >> inhibited >> source >> hold_rx >> release_rx + >> expiries >> invalid; + QCOMPARE (withdrawn.type (), NetworkMessage::InhibitStatus); + QVERIFY (!supported); + QVERIFY (inhibited); + QCOMPARE (source, QByteArrayLiteral ("W2SZ")); + QCOMPARE (hold_rx, 11u); + QCOMPARE (release_rx, 12u); + QCOMPARE (expiries, 13u); + QCOMPARE (invalid, 14u); + + client.inhibit_status (true, false, QString {}, 15, 16, 17, 18); + QTest::qWait (50); + QVERIFY (!receiver.hasPendingDatagrams ()); + } + + void heartbeatRefreshesAvailableStatus () + { + QUdpSocket original_receiver; + QVERIFY (original_receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + MessageClient client {"test-client", "version", "revision", "127.0.0.1", + original_receiver.localPort (), {}, 1}; + client.enable (true); + client.inhibit_status (true, false, QString {}, 1, 2, 3, 4); + QTRY_VERIFY (original_receiver.hasPendingDatagrams ()); + QTest::qWait (25); + while (original_receiver.hasPendingDatagrams ()) original_receiver.receiveDatagram (); + + QUdpSocket refreshed_receiver; + QVERIFY (refreshed_receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + client.set_server_port (refreshed_receiver.localPort ()); + QTRY_VERIFY (refreshed_receiver.hasPendingDatagrams ()); + NetworkMessage::Reader heartbeat {refreshed_receiver.receiveDatagram ().data ()}; + QCOMPARE (heartbeat.type (), NetworkMessage::Heartbeat); + QTRY_VERIFY (refreshed_receiver.hasPendingDatagrams ()); + NetworkMessage::Reader refreshed {refreshed_receiver.receiveDatagram ().data ()}; + QCOMPARE (refreshed.type (), NetworkMessage::InhibitStatus); + bool supported {false}; + bool inhibited {true}; + QByteArray source; + quint32 hold_rx {0}; + quint32 release_rx {0}; + quint32 expiries {0}; + quint32 invalid {0}; + refreshed >> supported >> inhibited >> source >> hold_rx >> release_rx + >> expiries >> invalid; + QVERIFY (supported); + QVERIFY (!inhibited); + QVERIFY (source.isEmpty ()); + QCOMPARE (hold_rx, 1u); + QCOMPARE (release_rx, 2u); + QCOMPARE (expiries, 3u); + QCOMPARE (invalid, 4u); + + client.inhibit_status (false, false, QString {}, 0, 0, 0, 0); + QTRY_VERIFY (refreshed_receiver.hasPendingDatagrams ()); + NetworkMessage::Reader withdrawn {refreshed_receiver.receiveDatagram ().data ()}; + supported = true; + withdrawn >> supported; + QCOMPARE (withdrawn.type (), NetworkMessage::InhibitStatus); + QVERIFY (!supported); + + QUdpSocket unsupported_receiver; + QVERIFY (unsupported_receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + client.set_server_port (unsupported_receiver.localPort ()); + QTRY_VERIFY (unsupported_receiver.hasPendingDatagrams ()); + NetworkMessage::Reader unsupported_heartbeat { + unsupported_receiver.receiveDatagram ().data ()}; + QCOMPARE (unsupported_heartbeat.type (), NetworkMessage::Heartbeat); + QTest::qWait (50); + QVERIFY (!unsupported_receiver.hasPendingDatagrams ()); + } + + void preservesType17FieldOrder () + { + QUdpSocket receiver; + QVERIFY (receiver.bind (QHostAddress {QHostAddress::LocalHost}, 0)); + + auto client = std::unique_ptr<MessageClient> {new MessageClient { + "test-client", "test-version", "test-revision", + "127.0.0.1", receiver.localPort (), {}, 1}}; + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + while (receiver.hasPendingDatagrams ()) + { + receiver.receiveDatagram (); + } + + client->enable (true); + client->inhibit_status (true, true, QStringLiteral ("W2SZ"), 11, 12, 13, 14); + QTRY_VERIFY (receiver.hasPendingDatagrams ()); + auto const datagram = receiver.receiveDatagram ().data (); + + NetworkMessage::Reader reader {datagram}; + QCOMPARE (reader.type (), NetworkMessage::InhibitStatus); + QCOMPARE (reader.id (), QStringLiteral ("test-client")); + + bool supported {false}; + bool inhibited {false}; + QByteArray source; + quint32 hold_rx {0}; + quint32 release_rx {0}; + quint32 expiries {0}; + quint32 invalid {0}; + reader >> supported >> inhibited >> source >> hold_rx >> release_rx + >> expiries >> invalid; + + QCOMPARE (reader.status (), QDataStream::Ok); + QVERIFY (supported); + QVERIFY (reader.atEnd ()); + QVERIFY (inhibited); + QCOMPARE (source, QByteArrayLiteral ("W2SZ")); + QCOMPARE (hold_rx, 11u); + QCOMPARE (release_rx, 12u); + QCOMPARE (expiries, 13u); + QCOMPARE (invalid, 14u); + } +}; + +QTEST_GUILESS_MAIN (TestMessageClientInhibitStatus) +#include "test_message_client_inhibit_status.moc" diff --git a/tests/unit/network/test_message_client_replay.cpp b/tests/unit/network/test_message_client_replay.cpp new file mode 100644 index 00000000..a13b74d4 --- /dev/null +++ b/tests/unit/network/test_message_client_replay.cpp @@ -0,0 +1,326 @@ +#include <QtTest> + +#include <QCoreApplication> +#include <QElapsedTimer> +#include <QSignalSpy> +#include <QTimer> +#include <QUdpSocket> +#include <QVector> + +#include <memory> + +#include "Network/MessageClient.hpp" +#include "Network/NetworkMessage.hpp" + +namespace +{ + class DatagramReceiver final + { + public: + DatagramReceiver () + { + QObject::connect (&socket_, &QUdpSocket::readyRead, [&] {drain ();}); + } + + bool bind () + { + return socket_.bind (QHostAddress {QHostAddress::LocalHost}, 0); + } + + quint16 port () const + { + return socket_.localPort (); + } + + QUdpSocket * socket () + { + return &socket_; + } + + bool hasPendingDatagrams () const + { + return socket_.hasPendingDatagrams (); + } + + QVector<QByteArray> const& datagrams () const + { + return datagrams_; + } + + QHostAddress senderAddress () const + { + return sender_address_; + } + + quint16 senderPort () const + { + return sender_port_; + } + + void clear () + { + drain (); + datagrams_.clear (); + } + + private: + void drain () + { + while (socket_.hasPendingDatagrams ()) + { + QByteArray datagram; + datagram.resize (static_cast<int> (socket_.pendingDatagramSize ())); + if (0 <= socket_.readDatagram (datagram.data (), datagram.size (), + &sender_address_, &sender_port_)) + { + datagrams_.append (datagram); + } + } + } + + QUdpSocket socket_; + QVector<QByteArray> datagrams_; + QHostAddress sender_address_; + quint16 sender_port_ {0}; + }; + + NetworkMessage::Type messageType (QByteArray const& datagram) + { + NetworkMessage::Reader reader {datagram}; + return reader.type (); + } + + bool decodeIsNew (QByteArray const& datagram) + { + NetworkMessage::Reader reader {datagram}; + bool is_new {false}; + reader >> is_new; + return is_new; + } + + void sendDecode (MessageClient& client, bool is_new, int sequence) + { + client.decode (is_new, QTime {12, 0, sequence % 60}, -10, 0.1f, + static_cast<quint32> (1000 + sequence), "FT8", + QString {"CQ TEST%1 AA00"}.arg (sequence), false, false); + } + + void sendStatus (MessageClient& client, QString const& tx_message = QString {}) + { + client.status_update (static_cast<MessageClient::Frequency> (14074000), "FT8", QString {}, QString {}, + "FT8", false, false, false, 1500, 1500, "N0CALL", "AA00", + QString {}, false, QString {}, false, static_cast<quint8> (0), + 50, 15, "Default", tx_message); + } + + void sendReply (DatagramReceiver& receiver, QTime time, qint32 snr, float delta_time, + quint32 delta_frequency, QString const& mode, QString const& message, + bool low_confidence = false) + { + QByteArray datagram; + NetworkMessage::Builder out {&datagram, NetworkMessage::Reply, "test-client", 2}; + out << time << snr << delta_time << delta_frequency << mode.toUtf8 () << message.toUtf8 () + << low_confidence << quint8 {0}; + QCOMPARE (receiver.socket ()->writeDatagram (datagram, receiver.senderAddress (), + receiver.senderPort ()), + static_cast<qint64> (datagram.size ())); + } + + std::unique_ptr<MessageClient> makeClient (quint16 port) + { + return std::unique_ptr<MessageClient> {new MessageClient { + "test-client", "test-version", "test-revision", "127.0.0.1", port, QStringList {}, 1}}; + } + + void discardInitialHeartbeat (DatagramReceiver& receiver) + { + QTRY_VERIFY (!receiver.datagrams ().isEmpty ()); + QCOMPARE (messageType (receiver.datagrams ().front ()), NetworkMessage::Heartbeat); + receiver.clear (); + } +} + +class TestMessageClientReplay final + : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void replyMatchesSentDecodeIndependentlyOfDisplay () + { + DatagramReceiver receiver; + QVERIFY (receiver.bind ()); + auto client = makeClient (receiver.port ()); + client->enable (true); + discardInitialHeartbeat (receiver); + + QSignalSpy replies {client.get (), &MessageClient::reply}; + QTime const time {12, 34, 45}; + QString const message {"K1ABC N0CALL -10"}; + client->decode (true, time, -12, 0.2f, 1425, "~", message, false, false); + QTRY_COMPARE (receiver.datagrams ().size (), 1); + + sendReply (receiver, time, -12, 0.2f, 1425, "~", message); + + QTRY_COMPARE (replies.size (), 1); + QCOMPARE (replies.front ().at (5).toString (), message); + } + + void replyRequiresUnclearedExactDecode () + { + DatagramReceiver receiver; + QVERIFY (receiver.bind ()); + auto client = makeClient (receiver.port ()); + client->enable (true); + discardInitialHeartbeat (receiver); + + QSignalSpy replies {client.get (), &MessageClient::reply}; + QTime const time {12, 34, 45}; + QString const message {"CQ K1ABC FN42"}; + client->decode (true, time, -12, 0.2f, 1425, "~", message, false, false); + QTRY_COMPARE (receiver.datagrams ().size (), 1); + + sendReply (receiver, time, -12, 0.2f, 1425, "~", "CQ K1ABC FN43"); + QTest::qWait (20); + QCOMPARE (replies.size (), 0); + + sendReply (receiver, time, -12, 0.2f, 1425, "~", message); + QTRY_COMPARE (replies.size (), 1); + + client->decodes_cleared (); + sendReply (receiver, time, -12, 0.2f, 1425, "~", message); + QTest::qWait (20); + QCOMPARE (replies.size (), 1); + } + + void replayIsDeferredPacedAndOrdered () + { + DatagramReceiver receiver; + QVERIFY (receiver.bind ()); + auto client = makeClient (receiver.port ()); + discardInitialHeartbeat (receiver); + QElapsedTimer replay_clock; + QVector<int> replay_batch_sizes; + QVector<qint64> replay_batch_times; + QObject::connect (client.get (), &MessageClient::replay_batch_processed, + [&] (int message_count) { + replay_batch_sizes.append (message_count); + replay_batch_times.append (replay_clock.elapsed ()); + }); + + QVERIFY (client->begin_replay ()); + for (int sequence = 0; sequence != 24; ++sequence) + { + sendDecode (*client, false, sequence); + } + client->WSPR_decode (false, QTime {12, 1}, -20, 0.2f, + static_cast<MessageClient::Frequency> (14095600), 0, + "K1ABC", "FN42", 37, false); + sendStatus (*client, "replay-status"); + replay_clock.start (); + client->end_replay (); + + sendDecode (*client, true, 24); + client->decodes_cleared (); + + QVERIFY (!receiver.hasPendingDatagrams ()); + QCOMPARE (replay_batch_sizes.size (), 0); + bool yielded_to_event_loop {false}; + QTimer::singleShot (0, [&] {yielded_to_event_loop = true;}); + + QTRY_COMPARE (receiver.datagrams ().size (), 28); + QVERIFY (yielded_to_event_loop); + + for (int index = 0; index != 24; ++index) + { + QCOMPARE (messageType (receiver.datagrams ()[index]), NetworkMessage::Decode); + QVERIFY (!decodeIsNew (receiver.datagrams ()[index])); + } + QCOMPARE (messageType (receiver.datagrams ()[24]), NetworkMessage::WSPRDecode); + QVERIFY (!decodeIsNew (receiver.datagrams ()[24])); + QCOMPARE (messageType (receiver.datagrams ()[25]), NetworkMessage::Status); + QCOMPARE (messageType (receiver.datagrams ()[26]), NetworkMessage::Decode); + QVERIFY (decodeIsNew (receiver.datagrams ()[26])); + QCOMPARE (messageType (receiver.datagrams ()[27]), NetworkMessage::Clear); + + int replayed_messages {0}; + for (auto const batch_size : replay_batch_sizes) + { + QVERIFY (batch_size > 0); + QVERIFY (batch_size <= 10); + replayed_messages += batch_size; + } + QCOMPARE (replayed_messages, 28); + QVERIFY (replay_batch_sizes.size () >= 3); + QVERIFY (replay_batch_times.front () >= 8); + QVERIFY (replay_batch_times.back () - replay_batch_times.front () >= 15); + } + + void repeatedReplayIsCoalesced () + { + DatagramReceiver receiver; + QVERIFY (receiver.bind ()); + auto client = makeClient (receiver.port ()); + discardInitialHeartbeat (receiver); + + QVERIFY (client->begin_replay ()); + for (int sequence = 0; sequence != 11; ++sequence) + { + sendDecode (*client, false, sequence); + } + sendStatus (*client); + client->end_replay (); + + QVERIFY (!client->begin_replay ()); + QTRY_COMPARE (receiver.datagrams ().size (), 12); + QVERIFY (client->begin_replay ()); + sendStatus (*client); + client->end_replay (); + QTRY_COMPARE (receiver.datagrams ().size (), 13); + } + + void destinationChangeCancelsReplay () + { + DatagramReceiver original_receiver; + DatagramReceiver new_receiver; + QVERIFY (original_receiver.bind ()); + QVERIFY (new_receiver.bind ()); + auto client = makeClient (original_receiver.port ()); + discardInitialHeartbeat (original_receiver); + + QSignalSpy first_batch {original_receiver.socket (), &QUdpSocket::readyRead}; + QVERIFY (client->begin_replay ()); + for (int sequence = 0; sequence != 25; ++sequence) + { + sendDecode (*client, false, sequence); + } + sendStatus (*client); + client->end_replay (); + + QVERIFY (first_batch.wait (1000)); + QVERIFY (original_receiver.datagrams ().size () > 0); + + // Cancel as soon as the first paced batch is observed. Packets already + // written to the OS before cancel can still arrive after the first + // readyRead, so settle the original socket before taking a baseline. + client->set_server_port (new_receiver.port ()); + QTest::qWait (50); + QCoreApplication::processEvents (); + auto const delivered_after_cancel = original_receiver.datagrams ().size (); + QVERIFY (delivered_after_cancel > 0); + QVERIFY (delivered_after_cancel <= 10); + + sendDecode (*client, true, 25); + + QTRY_COMPARE (new_receiver.datagrams ().size (), 2); + QTest::qWait (50); + QCOMPARE (original_receiver.datagrams ().size (), delivered_after_cancel); + QCOMPARE (messageType (new_receiver.datagrams ().front ()), NetworkMessage::Heartbeat); + QCOMPARE (messageType (new_receiver.datagrams ().back ()), NetworkMessage::Decode); + QVERIFY (decodeIsNew (new_receiver.datagrams ().back ())); + } +}; + +QTEST_GUILESS_MAIN (TestMessageClientReplay) + +#include "test_message_client_replay.moc" diff --git a/tests/unit/network/test_message_server.cpp b/tests/unit/network/test_message_server.cpp new file mode 100644 index 00000000..bde89f09 --- /dev/null +++ b/tests/unit/network/test_message_server.cpp @@ -0,0 +1,96 @@ +#include <QtTest> + +#include <QSignalSpy> +#include <QUdpSocket> + +#include "Network/NetworkMessage.hpp" +#include "UDPExamples/MessageServer.hpp" + +namespace +{ + QByteArray heartbeat (QString const& id) + { + QByteArray message; + NetworkMessage::Builder out {&message, NetworkMessage::Heartbeat, id, 2}; + out << quint32 {2} << QByteArray {"test"} << QByteArray {}; + return message; + } + + QByteArray decode (QString const& id, QTime time, qint32 snr, float delta_time + , quint32 delta_frequency, QByteArray const& mode + , QByteArray const& text) + { + QByteArray message; + NetworkMessage::Builder out {&message, NetworkMessage::Decode, id, 2}; + out << true << time << snr << delta_time << delta_frequency << mode << text + << false << false; + return message; + } + + QByteArray receiveDatagram (QUdpSocket& socket) + { + QByteArray message; + message.resize (socket.pendingDatagramSize ()); + socket.readDatagram (message.data (), message.size ()); + return message; + } +} + +class TestMessageServer final + : public QObject +{ + Q_OBJECT + +private slots: + void refreshesClientEndpointWhenSourcePortChanges () + { + qRegisterMetaType<MessageServer::ClientKey> ("ClientKey"); + + QHostAddress const loopback {QHostAddress::LocalHost}; + QUdpSocket port_reservation; + QVERIFY (port_reservation.bind (loopback, 0)); + auto const server_port = port_reservation.localPort (); + port_reservation.close (); + + QObject owner; + auto *server = new MessageServer {&owner}; + QSignalSpy clients {server, &MessageServer::client_opened}; + QSignalSpy decodes {server, &MessageServer::decode}; + server->start (server_port); + + QString const id {"WSJT-X"}; + QUdpSocket original_client; + QVERIFY (original_client.bind (loopback, 0)); + auto const heartbeat_message = heartbeat (id); + QCOMPARE (original_client.writeDatagram (heartbeat_message, loopback, server_port) + , qint64 (heartbeat_message.size ())); + QTRY_COMPARE (clients.count (), 1); + auto const client_key = clients.at (0).at (0).value<MessageServer::ClientKey> (); + + QTime const time {18, 6}; + qint32 constexpr snr {-5}; + float constexpr delta_time {-0.5f}; + quint32 constexpr delta_frequency {1269}; + QByteArray const mode {"~"}; + QByteArray const text {"CQ NP4TX FK68"}; + + QUdpSocket restarted_client; + QVERIFY (restarted_client.bind (loopback, 0)); + QVERIFY (restarted_client.localPort () != original_client.localPort ()); + auto const decode_message = decode (id, time, snr, delta_time, delta_frequency, mode, text); + QCOMPARE (restarted_client.writeDatagram (decode_message, loopback, server_port) + , qint64 (decode_message.size ())); + QTRY_COMPARE (decodes.count (), 1); + + server->reply (client_key, time, snr, delta_time, delta_frequency + , QString::fromUtf8 (mode), QString::fromUtf8 (text), false, 0); + + QTRY_VERIFY_WITH_TIMEOUT (restarted_client.hasPendingDatagrams (), 1000); + NetworkMessage::Reader reply {receiveDatagram (restarted_client)}; + QCOMPARE (reply.type (), NetworkMessage::Reply); + } +}; + +QTEST_GUILESS_MAIN (TestMessageServer) + +#include "test_message_server.moc" diff --git a/tests/unit/network/test_pskreporter_ipfix.cpp b/tests/unit/network/test_pskreporter_ipfix.cpp new file mode 100644 index 00000000..94125299 --- /dev/null +++ b/tests/unit/network/test_pskreporter_ipfix.cpp @@ -0,0 +1,222 @@ +#include <QtTest> + +#include "Network/PSKReporterIPFIX.hpp" + +namespace +{ + quint16 u16 (QByteArray const& bytes, int offset) + { + return (static_cast<quint8> (bytes[offset]) << 8) + | static_cast<quint8> (bytes[offset + 1]); + } + + quint32 u32 (QByteArray const& bytes, int offset) + { + return (static_cast<quint32> (static_cast<quint8> (bytes[offset])) << 24) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 1])) << 16) + | (static_cast<quint32> (static_cast<quint8> (bytes[offset + 2])) << 8) + | static_cast<quint8> (bytes[offset + 3]); + } + + QList<quint16> setIds (QByteArray const& payload) + { + QList<quint16> ids; + int offset = 16; + while (offset + 4 <= payload.size ()) + { + auto const id = u16 (payload, offset); + auto const length = u16 (payload, offset + 2); + ids.append (id); + if (length < 4) + { + break; + } + offset += length; + } + return ids; + } + + PSKReporterIPFIX::Receiver receiver () + { + return {"K1ABC", "FN20", "WSJT-X test", "N/A", "N/A"}; + } + + PSKReporterIPFIX::Spot spot (int index) + { + return { + QString {"K%1ABC"}.arg (index), + "FN21", + -10, + 14074000u + static_cast<quint64> (index), + "FT8", + QDateTime {{2026, 5, 6}, {12, 0, 0}, Qt::UTC} + }; + } + + QList<PSKReporterIPFIX::Packet> buildUdpPackets (PSKReporterIPFIX::Receiver const& rx + , QList<PSKReporterIPFIX::Spot> const& spots + , bool include_descriptors + , quint32 sequence_number + , quint32 observation_id + , quint32 export_time) + { + return PSKReporterIPFIX::buildPackets ( + rx, spots, include_descriptors, sequence_number, observation_id, export_time + , PSKReporterIPFIX::maxUdpIpfixPayloadBytes ()); + } + + QList<PSKReporterIPFIX::Packet> buildTcpPackets (PSKReporterIPFIX::Receiver const& rx + , QList<PSKReporterIPFIX::Spot> const& spots + , bool include_descriptors + , quint32 sequence_number + , quint32 observation_id + , quint32 export_time) + { + return PSKReporterIPFIX::buildPackets ( + rx, spots, include_descriptors, sequence_number, observation_id, export_time + , PSKReporterIPFIX::maxTcpIpfixPayloadBytes ()); + } +} + +class TestPSKReporterIPFIX final + : public QObject +{ + Q_OBJECT + +private slots: + void splitsManySpotsIntoBoundedUdpPayloads () + { + QList<PSKReporterIPFIX::Spot> spots; + for (int i = 0; i != 200; ++i) + { + spots.append (spot (i)); + } + + auto const packets = buildUdpPackets (receiver (), spots, true, 17, 23, 29); + + QVERIFY (packets.size () > 1); + int spot_count = 0; + for (auto const& packet : packets) + { + QVERIFY2 (packet.payload.size () <= PSKReporterIPFIX::maxUdpIpfixPayloadBytes (), qPrintable (QString::number (packet.payload.size ()))); + spot_count += packet.spot_count; + } + QCOMPARE (spot_count, spots.size ()); + } + + void truncatesLongFieldsAndKeepsPacketsBounded () + { + auto long_text = QString (300, QChar {0x00f8}); + PSKReporterIPFIX::Receiver rx {long_text, long_text, long_text, long_text, long_text}; + QList<PSKReporterIPFIX::Spot> spots { + {long_text, long_text, -1, 50313000u, long_text, QDateTime {{2026, 5, 6}, {12, 0, 0}, Qt::UTC}} + }; + + auto const packets = buildUdpPackets (rx, spots, true, 1, 2, 3); + + QCOMPARE (packets.size (), 1); + QCOMPARE (packets.front ().spot_count, 1); + QVERIFY (packets.front ().payload.size () <= PSKReporterIPFIX::maxUdpIpfixPayloadBytes ()); + } + + void receiverOptionsTemplateUsesOneScopeField () + { + auto const packets = buildUdpPackets (receiver (), {}, true, 1, 2, 3); + auto const payload = packets.front ().payload; + + int offset = 16; + QCOMPARE (u16 (payload, offset), quint16 (2u)); + offset += u16 (payload, offset + 2); + QCOMPARE (u16 (payload, offset), quint16 (3u)); + QCOMPARE (u16 (payload, offset + 8), quint16 (1u)); + } + + void sequenceNumberAdvancesBySpotRecords () + { + QList<PSKReporterIPFIX::Spot> spots; + for (int i = 0; i != 200; ++i) + { + spots.append (spot (i)); + } + + auto const packets = buildUdpPackets (receiver (), spots, true, 100, 23, 29); + + quint32 expected = 100; + for (auto const& packet : packets) + { + QCOMPARE (u32 (packet.payload, 8), expected); + expected += packet.spot_count; + } + QCOMPARE (expected, quint32 (100 + spots.size ())); + } + + void descriptorOnlyPacketDoesNotAdvanceSequence () + { + auto const packets = buildUdpPackets (receiver (), {}, true, 44, 23, 29); + + QCOMPARE (packets.size (), 1); + QCOMPARE (packets.front ().spot_count, 0); + QCOMPARE (u32 (packets.front ().payload, 8), quint32 (44)); + } + + void splitPacketsOnlyCarryDescriptorsInFirstPacket () + { + QList<PSKReporterIPFIX::Spot> spots; + for (int i = 0; i != 200; ++i) + { + spots.append (spot (i)); + } + + auto const packets = buildUdpPackets (receiver (), spots, true, 1, 2, 3); + + QVERIFY (packets.size () > 1); + QVERIFY (setIds (packets.front ().payload).contains (quint16 (2u))); + QVERIFY (setIds (packets.front ().payload).contains (quint16 (3u))); + for (int i = 1; i != packets.size (); ++i) + { + QVERIFY (!setIds (packets[i].payload).contains (quint16 (2u))); + QVERIFY (!setIds (packets[i].payload).contains (quint16 (3u))); + } + } + + void everyPacketCarriesReceiverAndSenderSetsWhenSpotsSplit () + { + QList<PSKReporterIPFIX::Spot> spots; + for (int i = 0; i != 200; ++i) + { + spots.append (spot (i)); + } + + auto const packets = buildUdpPackets (receiver (), spots, true, 1, 2, 3); + + QVERIFY (packets.size () > 1); + for (auto const& packet : packets) + { + auto const ids = setIds (packet.payload); + QVERIFY (ids.contains (quint16 (0x50e2))); + QVERIFY (ids.contains (quint16 (0x50e3))); + } + } + + void tcpCanUseLargerIpfixPayloads () + { + QList<PSKReporterIPFIX::Spot> spots; + for (int i = 0; i != 200; ++i) + { + spots.append (spot (i)); + } + + auto const udp_packets = buildUdpPackets (receiver (), spots, true, 1, 2, 3); + auto const tcp_packets = buildTcpPackets (receiver (), spots, true, 1, 2, 3); + + QVERIFY (udp_packets.size () > 1); + QCOMPARE (tcp_packets.size (), 1); + QVERIFY (tcp_packets.front ().payload.size () > PSKReporterIPFIX::maxUdpIpfixPayloadBytes ()); + QVERIFY (tcp_packets.front ().payload.size () <= PSKReporterIPFIX::maxTcpIpfixPayloadBytes ()); + QCOMPARE (tcp_packets.front ().spot_count, spots.size ()); + } +}; + +QTEST_MAIN (TestPSKReporterIPFIX) + +#include "test_pskreporter_ipfix.moc" diff --git a/tests/unit/network/test_pskreporter_transport.cpp b/tests/unit/network/test_pskreporter_transport.cpp new file mode 100644 index 00000000..59b48aba --- /dev/null +++ b/tests/unit/network/test_pskreporter_transport.cpp @@ -0,0 +1,179 @@ +#include <QtTest> + +#include <QHostAddress> +#include <QSet> +#include <QTcpServer> +#include <QTcpSocket> +#include <QUdpSocket> + +#include "Network/PSKReporter.hpp" + +namespace +{ + quint16 u16(QByteArray const& bytes, int offset) + { + return (static_cast<quint8>(bytes[offset]) << 8) + | static_cast<quint8>(bytes[offset + 1]); + } + + QList<quint16> setIds(QByteArray const& payload) + { + QList<quint16> ids; + int offset = 16; + while (offset + 4 <= payload.size()) { + auto const length = u16(payload, offset + 2); + ids.append(u16(payload, offset)); + if (length < 4) { + break; + } + offset += length; + } + return ids; + } + + void verifyReport(QByteArray const& payload, bool includeDescriptors) + { + QVERIFY(payload.size() >= 16); + QCOMPARE(u16(payload, 0), quint16(10)); + QCOMPARE(u16(payload, 2), static_cast<quint16>(payload.size())); + + auto const ids = setIds(payload); + QVERIFY(ids.contains(quint16(0x50e2))); + QVERIFY(ids.contains(quint16(0x50e3))); + QCOMPARE(ids.contains(quint16(2)), includeDescriptors); + QCOMPARE(ids.contains(quint16(3)), includeDescriptors); + } + + PSKReporter::Options options(bool useTcpIp, quint16 port) + { + return {useTcpIp, QString {}, "MAP65 transport test", "127.0.0.1", port}; + } + + bool addSpots(PSKReporter& reporter, QString const& prefix, + QStringList& callsigns) + { + for (int i = 0; i < 2048; ++i) { + auto suffixIndex = i; + QString suffix; + for (int j = 0; j < 4; ++j) { + suffix.prepend(QChar { + static_cast<ushort>('A' + (suffixIndex % 26))}); + suffixIndex /= 26; + } + auto const callsign = prefix + QString::number((i / 26) % 10) + suffix; + if (!reporter.addRemoteStation( + callsign, "FN20", 50313000u, "Q65-60A", -12, + QDateTime {{2026, 8, 17}, {12, 0, 0}, Qt::UTC})) { + return false; + } + callsigns.append(callsign); + } + return true; + } + + void accountForPayload(QByteArray const& payload, QSet<QString>& remaining) + { + for (auto const& callsign : remaining.values()) { + if (payload.contains(callsign.toUtf8())) { + remaining.remove(callsign); + } + } + } + + QList<QByteArray> takeCompleteFrames(QByteArray& stream) + { + QList<QByteArray> frames; + while (stream.size() >= 4) { + auto const length = u16(stream, 2); + if (length < 16 || stream.size() < length) { + break; + } + frames.append(stream.left(length)); + stream.remove(0, length); + } + return frames; + } +} + +class TestPSKReporterTransport final : public QObject +{ + Q_OBJECT + +private slots: + void sendsAllIpfixReportsOverUdp() + { + QUdpSocket receiver; + QVERIFY(receiver.bind(QHostAddress {QHostAddress::LocalHost}, 0)); + // sendReport writes the maximum queue synchronously, before this test + // begins draining received datagrams. + receiver.setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption, + 256 * 1024); + + PSKReporter reporter {options(false, receiver.localPort())}; + reporter.setLocalStation("K1ABC", "FN21", "N/A", "N/A (MAP65)"); + QStringList callsigns; + QVERIFY(addSpots(reporter, "UA", callsigns)); + QSet<QString> remaining {callsigns.begin(), callsigns.end()}; + + reporter.sendReport(); + QList<QByteArray> reports; + QTRY_VERIFY_WITH_TIMEOUT(([&] { + while (receiver.hasPendingDatagrams()) { + QByteArray payload; + payload.resize(static_cast<int>(receiver.pendingDatagramSize())); + if (receiver.readDatagram(payload.data(), payload.size()) + != static_cast<qint64>(payload.size())) { + return false; + } + reports.append(payload); + accountForPayload(payload, remaining); + } + return reports.size() > 1 && remaining.isEmpty(); + }()), 5000); + + QVERIFY(reports.size() > 1); + for (int i = 0; i < reports.size(); ++i) { + verifyReport(reports.at(i), i == 0); + } + reporter.sendReport(true); + } + + void sendsAllIpfixReportsOverTcp() + { + QTcpServer server; + QVERIFY(server.listen(QHostAddress {QHostAddress::LocalHost}, 0)); + + PSKReporter reporter {options(true, server.serverPort())}; + reporter.setLocalStation("K1ABC", "FN21", "N/A", "N/A (MAP65)"); + QTRY_VERIFY_WITH_TIMEOUT(server.hasPendingConnections(), 3000); + auto *peer = server.nextPendingConnection(); + QVERIFY(peer); + + QStringList callsigns; + QVERIFY(addSpots(reporter, "TA", callsigns)); + QSet<QString> remaining {callsigns.begin(), callsigns.end()}; + QByteArray stream; + QList<QByteArray> reports; + reporter.sendReport(); + + QTRY_VERIFY_WITH_TIMEOUT(([&] { + stream.append(peer->readAll()); + auto const newFrames = takeCompleteFrames(stream); + for (auto const& frame : newFrames) { + reports.append(frame); + accountForPayload(frame, remaining); + } + return reports.size() > 1 && remaining.isEmpty(); + }()), 5000); + + QVERIFY(reports.size() > 1); + for (int i = 0; i < reports.size(); ++i) { + verifyReport(reports.at(i), i == 0); + } + reporter.sendReport(true); + } +}; + +QTEST_MAIN(TestPSKReporterTransport) + +#include "test_pskreporter_transport.moc" diff --git a/tests/unit/network/test_wsprnet_upload.cpp b/tests/unit/network/test_wsprnet_upload.cpp new file mode 100644 index 00000000..f2615722 --- /dev/null +++ b/tests/unit/network/test_wsprnet_upload.cpp @@ -0,0 +1,749 @@ +#include <QtTest> + +#include <QBuffer> +#include <QFile> +#include <QNetworkAccessManager> +#include <QNetworkReply> +#include <QPointer> +#include <QSignalSpy> +#include <QTemporaryDir> +#include <QTimer> +#include <QUrlQuery> + +#include "Network/wsprnet.h" + +namespace +{ + struct NetworkResponse + { + NetworkResponse () = default; + + NetworkResponse (QNetworkReply::NetworkError error, QString error_string, QByteArray body) + : error {error} + , error_string {error_string} + , body {body} + { + } + + QNetworkReply::NetworkError error = QNetworkReply::NoError; + QString error_string; + QByteArray body = "1 spot(s) added"; + }; + + class FakeReply final + : public QNetworkReply + { + public: + FakeReply (QNetworkRequest const& request, NetworkResponse response, QObject *parent = nullptr) + : QNetworkReply {parent} + , response_ {response} + , body_ {response.body} + , offset_ {0} + { + setRequest (request); + setUrl (request.url ()); + setOperation (QNetworkAccessManager::PostOperation); + open (QIODevice::ReadOnly | QIODevice::Unbuffered); + } + + void abort () override + { + response_.error = QNetworkReply::OperationCanceledError; + response_.error_string = "aborted"; + finish (); + } + + qint64 bytesAvailable () const override + { + return body_.size () - offset_ + QNetworkReply::bytesAvailable (); + } + + bool isSequential () const override + { + return true; + } + + void finish () + { + if (isFinished ()) + { + return; + } + setFinished (true); + if (QNetworkReply::NoError != response_.error) + { + setError (response_.error, response_.error_string); + } + if (!body_.isEmpty ()) + { + Q_EMIT readyRead (); + } + Q_EMIT finished (); + } + + protected: + qint64 readData (char *data, qint64 max_size) override + { + auto const bytes = qMin<qint64> (max_size, body_.size () - offset_); + if (bytes <= 0) + { + return -1; + } + memcpy (data, body_.constData () + offset_, static_cast<size_t> (bytes)); + offset_ += bytes; + return bytes; + } + + private: + NetworkResponse response_; + QByteArray body_; + qint64 offset_; + }; + + class FakeNetworkAccessManager final + : public QObject + , public WSPRNet::Transport + { + public: + struct Request + { + QUrl url; + QByteArray body; + }; + + explicit FakeNetworkAccessManager (QObject *parent = nullptr) + : QObject {parent} + , auto_finish {true} + , next_reply_to_finish_ {0} + { + } + + void enqueueResponse (NetworkResponse response) + { + responses_.append (response); + } + + void finishAll () + { + for (auto const& reply : replies_) + { + if (reply) + { + reply->finish (); + } + } + } + + void finishNext () + { + while (next_reply_to_finish_ < replies_.size () + && (!replies_[next_reply_to_finish_] || replies_[next_reply_to_finish_]->isFinished ())) + { + ++next_reply_to_finish_; + } + QVERIFY (next_reply_to_finish_ < replies_.size ()); + replies_[next_reply_to_finish_++]->finish (); + } + + void finishHost (QString const& host) + { + for (auto const& reply : replies_) + { + if (reply && !reply->isFinished () && reply->url ().host () == host) + { + reply->finish (); + return; + } + } + QFAIL (qPrintable (QString {"no unfinished reply for %1"}.arg (host))); + } + + QList<Request> requests; + bool auto_finish; + + QNetworkReply *post (QNetworkRequest const& request, QByteArray const& body) override + { + Request recorded {request.url (), body}; + requests.append (recorded); + + NetworkResponse response; + if (!responses_.isEmpty ()) + { + response = responses_.takeFirst (); + } + auto *reply = new FakeReply {request, response, this}; + replies_.append (reply); + if (auto_finish) + { + QTimer::singleShot (0, reply, [reply] () { reply->finish (); }); + } + return reply; + } + + private: + QList<NetworkResponse> responses_; + QList<QPointer<FakeReply>> replies_; + int next_reply_to_finish_; + }; + + WSPRNet::RetryPolicy retryPolicy (int max_attempts = 2, int max_pending = 1024, int ttl_ms = 60000) + { + WSPRNet::RetryPolicy policy; + policy.max_attempts = max_attempts; + policy.max_pending = max_pending; + policy.ttl_ms = ttl_ms; + policy.jitter_fraction = 0.; + policy.retry_delays_ms = {0}; + return policy; + } + + QString fst4wDecode () + { + return "1234 -10 0.1 1500 ` K1ABC FN20 37"; + } + + QString spotFileLine () + { + return "130223 2256 7 -21 -0.3 14.097090 K1ABC FN20 37 0 40 0\n"; + } + + QString secondSpotFileLine () + { + return "130223 2258 7 -19 -0.2 14.097120 K2DEF FN31 33 0 35 0\n"; + } + + QString type2SpotFileLine () + { + return "130223 2258 7 -19 -0.2 14.097120 K1ABC/P 37 0 35 0\n"; + } + + QString unresolvedHashSpotFileLine () + { + return "130223 2258 7 -19 -0.2 14.097120 <...> IO81UT 37 0 35 0\n"; + } + + QString twoSpotFileLines () + { + return spotFileLine () + secondSpotFileLine (); + } + + void postFst4w (WSPRNet& wspr, QString const& decode_text = QString {}) + { + wspr.post ("N0CALL", "FN20", "14.097000", "14.097100", "FST4W", 120.F, + "10", "37", "test-version", decode_text); + } + + void uploadFile (WSPRNet& wspr, QString const& file_name) + { + wspr.upload ("N0CALL", "FN20", "14.097000", "14.097100", "WSPR", 120.F, + "10", "37", "test-version", file_name); + } + + QString writeSpotFile (QTemporaryDir& dir, QString const& contents = spotFileLine ()) + { + auto const path = dir.path () + "/wspr_spots.txt"; + QFile file {path}; + if (!file.open (QIODevice::WriteOnly | QIODevice::Text)) + { + qFatal ("could not create temporary spot file"); + } + file.write (contents.toUtf8 ()); + file.close (); + return path; + } + + bool sawStatus (QSignalSpy const& spy, QString const& status) + { + for (auto const& arguments : spy) + { + if (!arguments.isEmpty () && arguments.front ().toString () == status) + { + return true; + } + } + return false; + } + + bool sawStatusContaining (QSignalSpy const& spy, QString const& text) + { + for (auto const& arguments : spy) + { + if (!arguments.isEmpty () && arguments.front ().toString ().contains (text)) + { + return true; + } + } + return false; + } + + int requestCountForHost (QList<FakeNetworkAccessManager::Request> const& requests, + QString const& host) + { + auto count = 0; + for (auto const& request : requests) + { + if (request.url.host () == host) + { + ++count; + } + } + return count; + } +} + +class TestWSPRNetUpload final + : public QObject +{ + Q_OBJECT + +private slots: + void fst4wDecodeQueuesSpotButDoesNotSendUntilFlush () + { + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + QCoreApplication::processEvents (); + + QCOMPARE (manager.requests.size (), 0); + + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 2); + QVERIFY (manager.requests.front ().body.contains ("function=wspr")); + QVERIFY (manager.requests.front ().body.contains ("tcall=K1ABC")); + } + + void primaryUploadsContinueWhileAlternateUploadIsOutstanding () + { + FakeNetworkAccessManager manager; + manager.auto_finish = false; + WSPRNet wspr {&manager, retryPolicy (1), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr, "1235 -11 0.2 1505 ` K2DEF FN31 33"); + postFst4w (wspr); + wspr.work (); + + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 1); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 1); + + manager.finishHost ("wsprnet.org"); + QTRY_COMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 2); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 1); + + manager.finishHost ("wsprnet.eu"); + QTRY_COMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 2); + manager.finishHost ("wsprnet.org"); + manager.finishHost ("wsprnet.eu"); + QTRY_VERIFY (sawStatus (statuses, "done")); + } + + void alternateRetryDoesNotSuppressLaterPrimaryStatus () + { + FakeNetworkAccessManager manager; + manager.auto_finish = false; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "1 spot(s) added"}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + WSPRNet wspr {&manager, retryPolicy (2), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr); + wspr.work (); + manager.finishHost ("wsprnet.org"); + manager.finishHost ("wsprnet.eu"); + + postFst4w (wspr); + wspr.work (); + + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 2); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 2); + QVERIFY (manager.requests.at (2).body.contains ("function=wsprstat")); + + manager.finishHost ("wsprnet.org"); + manager.finishHost ("wsprnet.eu"); + QTRY_VERIFY (sawStatus (statuses, "done")); + } + + void fst4wRetrySurvivesLaterDecodeCycles () + { + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + WSPRNet wspr {&manager, retryPolicy (3), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr); + wspr.work (); + QVERIFY (manager.requests.front ().body.contains ("tcall=K1ABC")); + + postFst4w (wspr, "1235 -11 0.2 1505 ` K2DEF FN31 33"); + postFst4w (wspr); + + QTRY_VERIFY (sawStatus (statuses, "done")); + + int k1abc = 0, k2def = 0; + for (auto const& request : manager.requests) + { + if (request.body.contains ("tcall=K1ABC")) ++k1abc; + if (request.body.contains ("tcall=K2DEF")) ++k2def; + } + QVERIFY (k1abc >= 3); + QCOMPARE (k2def, 2); + } + + void emptyFst4wFlushUploadsStatusAndCompletes () + { + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 1); + QVERIFY (manager.requests.front ().body.contains ("function=wsprstat")); + } + + void spotWithoutTargetGridUploadsOnlyToPrimary () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir, type2SpotFileLine ()); + + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 1); + QCOMPARE (manager.requests.front ().url.host (), QString {"wsprnet.org"}); + QUrlQuery query {QString::fromUtf8 (manager.requests.front ().body)}; + QCOMPARE (query.queryItemValue ("tcall", QUrl::FullyDecoded), QString {"K1ABC/P"}); + QCOMPARE (query.queryItemValue ("tgrid", QUrl::FullyDecoded), QString {}); + QVERIFY (!QFile::exists (path)); + } + + void unresolvedHashCallsignIsNotUploadedAsSpot () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir, unresolvedHashSpotFileLine ()); + + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 1); + QUrlQuery query {QString::fromUtf8 (manager.requests.front ().body)}; + QCOMPARE (query.queryItemValue ("function", QUrl::FullyDecoded), QString {"wsprstat"}); + QCOMPARE (query.queryItemValue ("tcall", QUrl::FullyDecoded), QString {}); + } + + void directUploadSuccessDoesNotDeleteStaleFilePath () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QVERIFY (QFile::exists (path)); + } + + void directStatusCompletionDoesNotPoisonNextFileUpload () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "status accepted"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "1 spot(s) added"}); + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr); + wspr.work (); + QTRY_VERIFY (sawStatus (statuses, "done")); + + statuses.clear (); + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 3); + QVERIFY (!QFile::exists (path)); + } + + void fileBackedAllSuccessDeletesSpotFile () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 1); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 1); + QVERIFY (!QFile::exists (path)); + } + + void fileBackedSuccessDoesNotDeleteRewrittenSpotFile () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.auto_finish = false; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + QCOMPARE (manager.requests.size (), 2); + QVERIFY (manager.requests.front ().body.contains ("tcall=K1ABC")); + + writeSpotFile (dir, secondSpotFileLine ()); + manager.finishNext (); + QCoreApplication::processEvents (); + manager.finishNext (); + QCoreApplication::processEvents (); + + QVERIFY (sawStatus (statuses, "done")); + QVERIFY (QFile::exists (path)); + + QFile file {path}; + QVERIFY (file.open (QIODevice::ReadOnly | QIODevice::Text)); + auto const contents = file.readAll (); + QVERIFY (contents.contains ("K2DEF")); + QVERIFY (!contents.contains ("K1ABC")); + } + + void fileBackedAlternateFailureDoesNotRetainAcceptedSpotFile () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir, twoSpotFileLines ()); + + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "1 spot(s) added"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "rejected"}); + WSPRNet wspr {&manager, retryPolicy (1), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 4); + QVERIFY (!QFile::exists (path)); + } + + void fileBackedPrimaryRejectionCanBeDeliveredByAlternate () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "rejected"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "1 spot(s) added"}); + WSPRNet wspr {&manager, retryPolicy (1), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 2); + QVERIFY (!QFile::exists (path)); + } + + void fileBackedTransportFailureRetriesThenRetainsSpotFile () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + WSPRNet wspr {&manager, retryPolicy (2), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 4); + QVERIFY (QFile::exists (path)); + } + + void directUploadStopsAfterConfiguredAttempts () + { + FakeNetworkAccessManager manager; + for (int i = 0; i != 6; ++i) + { + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + } + WSPRNet wspr {&manager, retryPolicy (3), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 6); + } + + void fileBackedBadServerResponseRetriesThenRetainsSpotFile () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "rejected"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "rejected"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "still rejected"}); + manager.enqueueResponse ({QNetworkReply::NoError, {}, "still rejected"}); + WSPRNet wspr {&manager, retryPolicy (2), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 4); + QVERIFY (QFile::exists (path)); + } + + void alternateSiteFailureDoesNotResendAcceptedPrimary () + { + FakeNetworkAccessManager manager; + manager.enqueueResponse ({QNetworkReply::NoError, {}, "1 spot(s) added"}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + manager.enqueueResponse ({QNetworkReply::TimeoutError, "timeout", {}}); + WSPRNet wspr {&manager, retryPolicy (2), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 1); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 2); + QCOMPARE (manager.requests.size (), 3); + } + + void expiredPendingUploadsAreDroppedAndFinalize () + { + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (2, 1024, 50), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + QTest::qWait (100); + postFst4w (wspr); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 0); + QVERIFY (sawStatusContaining (statuses, "expired")); + } + + void queueCapDropsOldestPendingUploads () + { + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (2, 2), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + for (int i = 0; i != 5; ++i) + { + postFst4w (wspr, fst4wDecode ()); + } + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (manager.requests.size (), 4); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 2); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 2); + QVERIFY (sawStatusContaining (statuses, "oldest pending")); + } + + void queueCapDoesNotDropPrimaryForAlternateLegs () + { + FakeNetworkAccessManager manager; + WSPRNet wspr {&manager, retryPolicy (1, 1), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + postFst4w (wspr, fst4wDecode ()); + postFst4w (wspr, "1235 -11 0.2 1505 ` K2DEF FN31 33"); + postFst4w (wspr); + wspr.work (); + + QTRY_VERIFY (sawStatus (statuses, "done")); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.org"), 1); + QCOMPARE (requestCountForHost (manager.requests, "wsprnet.eu"), 1); + } + + void abortClearsQueuedRetriesAndIgnoresStaleReplies () + { + QTemporaryDir dir; + QVERIFY (dir.isValid ()); + auto const path = writeSpotFile (dir); + + FakeNetworkAccessManager manager; + manager.auto_finish = false; + WSPRNet wspr {&manager, retryPolicy (), false}; + QSignalSpy statuses {&wspr, &WSPRNet::uploadStatus}; + + uploadFile (wspr, path); + wspr.work (); + QCOMPARE (manager.requests.size (), 2); + + wspr.abortOutstandingRequests (); + manager.finishAll (); + QCoreApplication::processEvents (); + + QVERIFY (QFile::exists (path)); + QVERIFY (!sawStatus (statuses, "done")); + } +}; + +QTEST_MAIN (TestWSPRNetUpload) + +#include "test_wsprnet_upload.moc" diff --git a/tests/unit/packjt77/CMakeLists.txt b/tests/unit/packjt77/CMakeLists.txt new file mode 100644 index 00000000..2ce41135 --- /dev/null +++ b/tests/unit/packjt77/CMakeLists.txt @@ -0,0 +1,132 @@ +# Build the shared helper module once so parallel test targets do not race +# while writing the same Fortran .mod interface file. +add_library (packjt77_test_helpers STATIC packjt77_test_helpers.f90) +set_target_properties (packjt77_test_helpers PROPERTIES + Fortran_MODULE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/packjt77_test_helpers") +target_include_directories (packjt77_test_helpers PUBLIC + "${CMAKE_CURRENT_BINARY_DIR}/packjt77_test_helpers") +wsjt_link_common_fortran (packjt77_test_helpers) + +add_executable (test_packjt77_grammar_gate + test_packjt77_grammar_gate.f90) +target_include_directories (test_packjt77_grammar_gate PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_packjt77_grammar_gate) + +add_test (NAME test_packjt77_grammar_gate COMMAND test_packjt77_grammar_gate) + +add_executable (test_packjt77_invariants + test_packjt77_invariants.f90) +target_include_directories (test_packjt77_invariants PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_invariants PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_invariants) + +add_test (NAME test_packjt77_invariants COMMAND test_packjt77_invariants) + +add_executable (test_packjt77var_invariants + test_packjt77var_invariants.f90) +target_include_directories (test_packjt77var_invariants PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77var_invariants PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77var_invariants) + +add_test (NAME test_packjt77var_invariants COMMAND test_packjt77var_invariants) + +add_executable (test_packjt77sdvar_invariants + test_packjt77sdvar_invariants.f90) +target_include_directories (test_packjt77sdvar_invariants PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77sdvar_invariants PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77sdvar_invariants) + +add_test (NAME test_packjt77sdvar_invariants COMMAND test_packjt77sdvar_invariants) + +add_executable (test_packjt77_protocol_vectors + test_packjt77_protocol_vectors.f90) +target_include_directories (test_packjt77_protocol_vectors PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_protocol_vectors PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_protocol_vectors) + +add_test (NAME test_packjt77_protocol_vectors COMMAND test_packjt77_protocol_vectors) + +add_executable (test_packjt77_schema_encoder + test_packjt77_schema_encoder.f90) +target_include_directories (test_packjt77_schema_encoder PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_schema_encoder PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_schema_encoder) + +add_test (NAME test_packjt77_schema_encoder COMMAND test_packjt77_schema_encoder) + +add_executable (test_packjt77_schema_decoder + test_packjt77_schema_decoder.f90) +target_include_directories (test_packjt77_schema_decoder PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_schema_decoder PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_schema_decoder) + +add_test (NAME test_packjt77_schema_decoder COMMAND test_packjt77_schema_decoder) + +add_executable (test_packjt77_hash_state + test_packjt77_hash_state.f90) +target_include_directories (test_packjt77_hash_state PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_hash_state PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_hash_state) + +add_test (NAME test_packjt77_hash_state COMMAND test_packjt77_hash_state) + +if (WSJT_BUILD_FORTRAN_OPENMP) + add_executable (test_packjt77_concurrent_unpack + test_packjt77_concurrent_unpack.f90) + target_include_directories (test_packjt77_concurrent_unpack PRIVATE + ${WSJT_FORTRAN_OPENMP_MODULE_DIR}) + target_link_libraries (test_packjt77_concurrent_unpack PRIVATE + wsjt_fort_omp wsjt_fortran_openmp) + + add_test (NAME test_packjt77_concurrent_unpack + COMMAND test_packjt77_concurrent_unpack) + set_tests_properties (test_packjt77_concurrent_unpack PROPERTIES + ENVIRONMENT "OMP_DYNAMIC=FALSE;OMP_NUM_THREADS=4;OMP_THREAD_LIMIT=4" + PROCESSORS 4 + TIMEOUT 30) +endif () + +add_executable (test_packjt77_pack28_sweep + test_packjt77_pack28_sweep.f90) +target_include_directories (test_packjt77_pack28_sweep PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_packjt77_pack28_sweep) + +add_test (NAME test_packjt77_pack28_sweep COMMAND test_packjt77_pack28_sweep) + +add_executable (test_packjt77_domain_sweeps + test_packjt77_domain_sweeps.f90) +target_include_directories (test_packjt77_domain_sweeps PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_domain_sweeps PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_domain_sweeps) + +add_test (NAME test_packjt77_domain_sweeps COMMAND test_packjt77_domain_sweeps) + +add_executable (test_packjt77_mutation_sweep + test_packjt77_mutation_sweep.f90) +target_include_directories (test_packjt77_mutation_sweep PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_packjt77_mutation_sweep PRIVATE packjt77_test_helpers) +wsjt_link_common_fortran (test_packjt77_mutation_sweep) + +add_test (NAME test_packjt77_mutation_sweep COMMAND test_packjt77_mutation_sweep) + +find_program (WSJT_SH_EXECUTABLE NAMES sh) +if (NOT WSJT_SH_EXECUTABLE) + message (FATAL_ERROR "sh is required to run lint_packjt77_idioms") +endif () + +add_test (NAME lint_packjt77_idioms + COMMAND "${WSJT_SH_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/lint_packjt77_idioms.sh" + "${CMAKE_SOURCE_DIR}") + +add_executable (test_packjt77_silent_rewrite_corpus + test_packjt77_silent_rewrite_corpus.f90) +target_include_directories (test_packjt77_silent_rewrite_corpus PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_packjt77_silent_rewrite_corpus) + +add_test (NAME test_packjt77_silent_rewrite_corpus + COMMAND test_packjt77_silent_rewrite_corpus + ${CMAKE_CURRENT_SOURCE_DIR}/silent_rewrite_corpus.txt --assert-zero-silent) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_packjt77_silent_rewrite_corpus PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") +endif () diff --git a/tests/unit/packjt77/encode77_test_messages.txt b/tests/unit/packjt77/encode77_test_messages.txt new file mode 100644 index 00000000..50f45596 --- /dev/null +++ b/tests/unit/packjt77/encode77_test_messages.txt @@ -0,0 +1,3 @@ +CQ K1ABC FN42 +HELLO@WORLD +K1ABC W9XYZ EN37 diff --git a/tests/unit/packjt77/lint_packjt77_idioms.sh b/tests/unit/packjt77/lint_packjt77_idioms.sh new file mode 100755 index 00000000..b221f9f0 --- /dev/null +++ b/tests/unit/packjt77/lint_packjt77_idioms.sh @@ -0,0 +1,88 @@ +#!/bin/sh + +root=${1:-.} +fail=0 + +show_violation() { + label=$1 + lines=$2 + echo "$label" + echo "$lines" + fail=1 +} + +pack_reads=$(grep -En "read *\(.*,\*" "$root/lib/77bit/packjt77.f90" || true) +if [ -n "$pack_reads" ]; then + show_violation "list-directed read in packjt77.f90:" "$pack_reads" +fi + +grammar_reads=$(grep -En "read *\(.*,\*" "$root/lib/77bit/packjt77_grammar.f90" || true) +grammar_read_count=0 +grammar_read_extra= +while IFS= read -r line; do + [ -z "$line" ] && continue + case "$line" in + *": read(token,*,err=10) value") + grammar_read_count=$((grammar_read_count + 1)) + ;; + *) + grammar_read_extra="${grammar_read_extra} +$line" + ;; + esac +done <<EOF +$grammar_reads +EOF +if [ "$grammar_read_count" -ne 2 ]; then + show_violation "unexpected grammar list-directed read count:" "$grammar_reads" +fi +if [ -n "$grammar_read_extra" ]; then + show_violation "unexpected grammar list-directed read:" "$grammar_read_extra" +fi + +bracket_lines=$(grep -En "index *\(.*'[<>]'" "$root/lib/77bit/packjt77.f90" || true) +bracket_extra= +while IFS= read -r line; do + [ -z "$line" ] && continue + case "$line" in + *": i=index(cw,'>')"|\ + *": i=index(cw,'>')"|\ + *": i2=index(c13,'>')"|\ + *": if(index(call_1,'<').le.0) then"|\ + *": if(index(call_2,'<').le.0) then") + ;; + *) + bracket_extra="${bracket_extra} +$line" + ;; + esac +done <<EOF +$bracket_lines +EOF +if [ -n "$bracket_extra" ]; then + show_violation "unexpected bracket probing in packjt77.f90:" "$bracket_extra" +fi + +legacy_lines=$(grep -En "call +(chkcall|split77)|(^|[^A-Za-z0-9_])(chkcall|split77) *\(" \ + "$root/lib/77bit/packjt77.f90" || true) +legacy_extra= +while IFS= read -r line; do + [ -z "$line" ] && continue + case "$line" in + *":subroutine split77(msg,nwords,nw,w)"|\ + *": call chkcall(w(3),bcall_1,ok1)"|\ + *":end subroutine split77") + ;; + *) + legacy_extra="${legacy_extra} +$line" + ;; + esac +done <<EOF +$legacy_lines +EOF +if [ -n "$legacy_extra" ]; then + show_violation "unexpected chkcall or split77 encode-path use:" "$legacy_extra" +fi + +exit "$fail" diff --git a/tests/unit/packjt77/packjt77_test_helpers.f90 b/tests/unit/packjt77/packjt77_test_helpers.f90 new file mode 100644 index 00000000..0373a005 --- /dev/null +++ b/tests/unit/packjt77/packjt77_test_helpers.f90 @@ -0,0 +1,1576 @@ +module packjt77_test_helpers + + use packjt77 + use packjt77_schema + implicit none + private :: reset_packjt77_state, prime_hash_call, prime_hash_call_var, & + store_rx_hash_var, wipe_shared_hash_tables, set_standard_call_state, & + set_var_call_state + + type pack77_result + logical :: encoded=.false. + integer :: status=PACK77_STATUS_NOT_ENCODED + integer :: i3=-1 + integer :: n3=-1 + character(len=77) :: c77=' ' + end type pack77_result + +contains + + subroutine wipe_shared_hash_tables() + calls10='' + calls12='' + calls22='' + recent_calls='' + ihash22=-1 + nzhash=0 + end subroutine wipe_shared_hash_tables + + subroutine set_standard_call_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + mycall13=' ' + dxcall13=' ' + mycall13_configured=' ' + dxcall13_configured=' ' + mycall13=mycall + dxcall13=dxcall + mycall13_configured=mycall + dxcall13_configured=dxcall + end subroutine set_standard_call_state + + subroutine set_var_call_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + queued_calls_by_thread='' + queued_recent_calls_by_thread='' + nqueued_calls_by_thread=0 + nqueued_recent_calls_by_thread=0 + mycall13=' ' + dxcall13=' ' + mycall13_configured_prev=' ' + dxcall13_configured_prev=' ' + mycall13_configured_set=.false. + dxcall13_configured_set=.false. + hashmy10_configured=-1 + hashmy12_configured=-1 + hashmy22_configured=-1 + hashdx10_configured=-1 + mycall13=mycall + dxcall13=dxcall + if(len_trim(mycall).gt.2) then + mycall13_configured_set=.true. + mycall13_configured_prev=mycall13 + hashmy10_configured=ihashcall(mycall13,10) + hashmy12_configured=ihashcall(mycall13,12) + hashmy22_configured=ihashcall(mycall13,22) + endif + if(len_trim(dxcall).gt.2) then + dxcall13_configured_set=.true. + dxcall13_configured_prev=dxcall13 + hashdx10_configured=ihashcall(dxcall13,10) + endif + end subroutine set_var_call_state + + subroutine clear_standard_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + call wipe_shared_hash_tables() + call set_standard_call_state(mycall,dxcall) + end subroutine clear_standard_state + + subroutine clear_var_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + call wipe_shared_hash_tables() + call set_var_call_state(mycall,dxcall) + end subroutine clear_var_state + + subroutine clear_all_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + call wipe_shared_hash_tables() + call set_standard_call_state(mycall,dxcall) + call set_var_call_state(mycall,dxcall) + end subroutine clear_all_state + + subroutine normalize_call(callsign,c13) + character(len=*), intent(in) :: callsign + character(len=13), intent(out) :: c13 + integer :: i + + c13=' ' + c13=callsign + if(c13(1:1).eq.'<') c13=c13(2:) + i=index(c13,'>') + if(i.gt.0) c13(i:)=' ' + end subroutine normalize_call + + subroutine assert_message_type(label,input,want_i3,want_n3,got_i3,got_n3) + character(len=*), intent(in) :: label, input + integer, intent(in) :: want_i3, want_n3, got_i3, got_n3 + + if(got_i3.ne.want_i3 .or. got_n3.ne.want_n3) then + write(*,1000) trim(label), trim(input), want_i3, want_n3, got_i3, got_n3 +1000 format(a,' message type failure for "',a,'"; wanted ',i0,'.',i0, & + ' got ',i0,'.',i0) + error stop 1 + endif + end subroutine assert_message_type + + subroutine assert_binary_payload(label,input,c77) + character(len=*), intent(in) :: label, input + character(len=77), intent(in) :: c77 + + if(.not.is_binary_payload(c77)) then + write(*,1010) trim(label), trim(input), c77 +1010 format(a,' emitted non-binary payload for "',a,'": ',a) + error stop 1 + endif + end subroutine assert_binary_payload + + subroutine assert_pack77_result(label,input,encoded) + character(len=*), intent(in) :: label, input + type(pack77_result), intent(in) :: encoded + + if(.not.encoded%encoded) then + write(*,1015) trim(label), trim(input) +1015 format(a,' failed to encode "',a,'"') + error stop 1 + endif + if(encoded%i3.lt.0 .or. encoded%i3.gt.7 .or. encoded%n3.lt.0 .or. & + encoded%n3.gt.7) then + write(*,1016) trim(label), trim(input), encoded%i3, encoded%n3 +1016 format(a,' emitted invalid type for "',a,'": ',i0,'.',i0) + error stop 1 + endif + call assert_binary_payload(label,input,encoded%c77) + end subroutine assert_pack77_result + + type(pack77_result) function pack77_result_from_api(msg,options) result(encoded) + character(len=*), intent(in) :: msg + type(pack77_options), intent(in), optional :: options + + encoded=pack77_result() + call pack77(msg,encoded%i3,encoded%n3,encoded%c77,options, & + status=encoded%status) + encoded%encoded=encoded%i3.ge.0 + end function pack77_result_from_api + + type(pack77_result) function pack77_legacy_result_from_api(msg,options) & + result(encoded) + character(len=*), intent(in) :: msg + type(pack77_options), intent(in), optional :: options + + encoded=pack77_result() + call pack77_legacy_truncating_fallback(msg,encoded%i3,encoded%n3, & + encoded%c77,options,status=encoded%status) + encoded%encoded=encoded%i3.ge.0 + end function pack77_legacy_result_from_api + + type(pack77_result) function pack77_with_hint(msg,pack_i3,pack_n3) result(encoded) + character(len=*), intent(in) :: msg + integer, intent(in) :: pack_i3, pack_n3 + + encoded=pack77_result() + if(pack_i3.eq.0 .and. pack_n3.eq.5) then + encoded=strict_telemetry_result_from_schema(msg) + else if(pack_i3.eq.0 .and. pack_n3.eq.6) then + encoded=pack77_result_from_api(msg, & + pack77_options(prefer_wspr_50bit=.true.)) + else + encoded=pack77_result_from_api(msg) + endif + end function pack77_with_hint + + type(pack77_result) function strict_telemetry_result_from_schema(msg) & + result(encoded) + character(len=*), intent(in) :: msg + character(len=37) :: text + character(len=18) :: c18 + character(len=1) :: ch + integer :: i,n + integer :: ntel(3) + logical :: ok + + encoded=pack77_result() + text=adjustl(msg) + n=len_trim(text) + if(n.lt.1 .or. n.gt.18) return + do i=1,n + ch=text(i:i) + if(ch.ge.'a' .and. ch.le.'z') ch=char(ichar(ch)-32) + if(index('0123456789ABCDEF',ch).eq.0) return + text(i:i)=ch + enddo + + c18=text(1:n) + c18=adjustr(c18) + ntel=-99 + read(c18,1005,err=6) ntel +1005 format(3z6) +6 if(ntel(1).lt.0 .or. ntel(2).lt.0 .or. ntel(3).lt.0) return + + call encode_pack77_telemetry(ntel(1),ntel(2),ntel(3),encoded%c77,ok) + if(ok) then + encoded%encoded=.true. + encoded%status=PACK77_STATUS_ENCODED + encoded%i3=0 + encoded%n3=5 + endif + end function strict_telemetry_result_from_schema + + logical function is_binary_payload(c77) + character(len=77), intent(in) :: c77 + integer :: i + + is_binary_payload=.true. + do i=1,77 + if(c77(i:i).ne.'0' .and. c77(i:i).ne.'1') then + is_binary_payload=.false. + return + endif + enddo + end function is_binary_payload + + subroutine assert_decode(label,input,expected,decoded,ok) + character(len=*), intent(in) :: label, input, expected, decoded + logical, intent(in) :: ok + + if(.not.ok) then + write(*,1020) trim(label), trim(input) +1020 format(a,' unpack failure for "',a,'"') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1030) trim(label), trim(input), trim(expected), trim(decoded) +1030 format(a,' decode failure for "',a,'"; expected "',a,'"; got "',a,'"') + error stop 1 + endif + end subroutine assert_decode + + subroutine assert_text_equal(label,left,right) + character(len=*), intent(in) :: label, left, right + + if(trim(left).ne.trim(right)) then + write(*,1040) trim(label), trim(left), trim(right) +1040 format(a,' mismatch; left "',a,'" right "',a,'"') + error stop 1 + endif + end subroutine assert_text_equal + + subroutine assert_canonical_text(label,input,canonical,decoded) + character(len=*), intent(in) :: label, input, canonical, decoded + + if(canonical.ne.decoded) then + write(*,1045) trim(label), trim(input), trim(canonical), trim(decoded) +1045 format(a,' canonical mismatch for "',a,'"; canonical "',a, & + '"; decoded "',a,'"') + error stop 1 + endif + end subroutine assert_canonical_text + + logical function normalized_equal(left,right) result(equal) + character(len=*), intent(in) :: left, right + character(len=37) :: left_norm, right_norm + + call normalize_message(left,left_norm) + call normalize_message(right,right_norm) + equal=trim(left_norm).eq.trim(right_norm) + end function normalized_equal + + logical function canonical_match(left,right) result(matches) + character(len=*), intent(in) :: left, right + character(len=37) :: left_tokens(19), right_tokens(19), wrapped + integer :: left_n, right_n, i + + matches=.false. + call split_tokens(left,left_tokens,left_n) + call split_tokens(right,right_tokens,right_n) + if(left_n.ne.right_n) return + do i=1,left_n + if(trim(left_tokens(i)).eq.trim(right_tokens(i))) cycle + if(plausible_auto_hash_source(left_tokens(i))) then + wrapped=' ' + wrapped='<'//trim(left_tokens(i))//'>' + if(trim(right_tokens(i)).eq.trim(wrapped)) cycle + endif + if(trim(right_tokens(i)).eq.'<...>' .and. & + hash_placeholder_source(left_tokens(i))) cycle + return + enddo + matches=.true. + end function canonical_match + + logical function telemetry_match(left,right) result(matches) + character(len=*), intent(in) :: left, right + character(len=37) :: left_tokens(19), right_tokens(19) + integer :: left_n, right_n + + ! Telemetry messages allow a documented leading-zero canonical form. + matches=.false. + call split_tokens(left,left_tokens,left_n) + call split_tokens(right,right_tokens,right_n) + if(left_n.ne.1 .or. right_n.ne.1) return + matches=telemetry_token_match(left_tokens(1),right_tokens(1)) + end function telemetry_match + + subroutine assert_call(label,got,expected) + character(len=*), intent(in) :: label, got, expected + + if(trim(got).ne.expected) then + write(*,1050) trim(label), trim(expected), trim(got) +1050 format(a,' failure; expected "',a,'"; got "',a,'"') + error stop 1 + endif + end subroutine assert_call + + subroutine assert_int(label,expected,got) + character(len=*), intent(in) :: label + integer, intent(in) :: expected, got + + if(got.ne.expected) then + write(*,1060) trim(label), expected, got +1060 format(a,' failure; expected ',i0,' got ',i0) + error stop 1 + endif + end subroutine assert_int + + subroutine normalize_message(input_msg,normalized) + character(len=*), intent(in) :: input_msg + character(len=37), intent(out) :: normalized + character(len=37) :: tokens(19) + integer :: nwords, i + + normalized=' ' + call split_tokens(input_msg,tokens,nwords) + do i=1,nwords + if(len_trim(normalized).gt.0) normalized=trim(normalized)//' ' + normalized=trim(normalized)//trim(tokens(i)) + enddo + end subroutine normalize_message + + subroutine split_tokens(input_msg,tokens,nwords) + character(len=*), intent(in) :: input_msg + character(len=37), intent(out) :: tokens(19) + integer, intent(out) :: nwords + character(len=1) :: c, previous + integer :: i, n + + tokens=' ' + nwords=0 + n=0 + previous=' ' + do i=1,len_trim(input_msg) + c=input_msg(i:i) + if(ichar(c).eq.0) c=' ' + if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) + if(c.eq.' ' .and. previous.eq.' ') cycle + if(c.ne.' ' .and. previous.eq.' ') then + nwords=nwords+1 + n=0 + if(nwords.gt.size(tokens)) return + endif + if(c.ne.' ') then + n=n+1 + if(n.le.len(tokens(1))) tokens(nwords)(n:n)=c + endif + previous=c + enddo + end subroutine split_tokens + + logical function plausible_auto_hash_source(token) result(ok) + character(len=*), intent(in) :: token + integer :: i,n,slash + + n=len_trim(token) + ok=.false. + if(n.lt.3 .or. n.gt.11) return + slash=index(token(1:n),'/') + if(slash.lt.2 .or. slash.ge.n) return + if(index(token(slash+1:n),'/').gt.0) return + do i=1,n + if(i.eq.slash) cycle + if(.not.((token(i:i).ge.'A' .and. token(i:i).le.'Z') .or. & + (token(i:i).ge.'0' .and. token(i:i).le.'9'))) return + enddo + ok=.true. + end function plausible_auto_hash_source + + logical function hash_placeholder_source(token) result(ok) + character(len=*), intent(in) :: token + integer :: n + + n=len_trim(token) + ok=plausible_auto_hash_source(token) + if(ok) return + if(n.lt.3 .or. n.gt.13) return + ok=token(1:1).eq.'<' .and. token(n:n).eq.'>' .and. n-2.le.11 + end function hash_placeholder_source + + logical function telemetry_token_match(left,right) result(matches) + character(len=*), intent(in) :: left, right + character(len=18) :: left_hex, right_hex + integer :: left_n, right_n + + matches=.false. + left_hex=upper_token(left) + right_hex=upper_token(right) + left_n=len_trim(left_hex) + right_n=len_trim(right_hex) + if(left_n.lt.17 .or. left_n.gt.18) return + if(right_n.lt.17 .or. right_n.gt.18) return + if(.not.is_hex_token(left_hex,left_n)) return + if(.not.is_hex_token(right_hex,right_n)) return + if(left_n.eq.right_n .and. trim(left_hex).eq.trim(right_hex)) then + matches=.true. + else if(left_n.eq.right_n+1 .and. left_hex(1:1).eq.'0' .and. & + left_hex(2:left_n).eq.right_hex(1:right_n)) then + matches=.true. + else if(right_n.eq.left_n+1 .and. right_hex(1:1).eq.'0' .and. & + right_hex(2:right_n).eq.left_hex(1:left_n)) then + matches=.true. + endif + end function telemetry_token_match + + logical function is_hex_token(token,n) result(ok) + character(len=*), intent(in) :: token + integer, intent(in) :: n + integer :: i + + ok=.true. + do i=1,n + if(index('0123456789ABCDEF',token(i:i)).eq.0) then + ok=.false. + return + endif + enddo + end function is_hex_token + + character(len=18) function upper_token(token) result(upper) + character(len=*), intent(in) :: token + integer :: i, n + character :: c + + upper=' ' + n=min(len_trim(token),len(upper)) + do i=1,n + c=token(i:i) + if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) + upper(i:i)=c + enddo + end function upper_token + + subroutine assert_true(label,condition) + character(len=*), intent(in) :: label + logical, intent(in) :: condition + + if(.not.condition) then + write(*,1070) trim(label) +1070 format(a,' failure') + error stop 1 + endif + end subroutine assert_true + + subroutine assert_shared_hash_tables_empty(label) + character(len=*), intent(in) :: label + + call assert_int(trim(label)//' nzhash',0,nzhash) + call assert_true(trim(label)//' calls10',all(calls10.eq.'')) + call assert_true(trim(label)//' calls12',all(calls12.eq.'')) + call assert_true(trim(label)//' calls22',all(calls22.eq.'')) + call assert_true(trim(label)//' recent calls',all(recent_calls.eq.'')) + call assert_true(trim(label)//' ihash22',all(ihash22.eq.-1)) + call assert_true(trim(label)//' queued hash counts', & + all(nqueued_calls_by_thread.eq.0)) + call assert_true(trim(label)//' queued recent counts', & + all(nqueued_recent_calls_by_thread.eq.0)) + call assert_true(trim(label)//' queued calls', & + all(queued_calls_by_thread.eq.'')) + call assert_true(trim(label)//' queued recent calls', & + all(queued_recent_calls_by_thread.eq.'')) + end subroutine assert_shared_hash_tables_empty + + subroutine run_packjt77_common_invariants(configured_var,ntests) + logical, intent(in) :: configured_var + integer, intent(inout) :: ntests + + call expect_round_trip('K1ABC W9XYZ FN42', & + 'K1ABC W9XYZ FN42', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ R-11', & + 'K1ABC W9XYZ R-11', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ', & + 'K1ABC W9XYZ', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ RRR', & + 'K1ABC W9XYZ RRR', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ RR73', & + 'K1ABC W9XYZ RR73', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ 73', & + 'K1ABC W9XYZ 73', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ +00', & + 'K1ABC W9XYZ +00', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ -30', & + 'K1ABC W9XYZ -30', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ -31', & + 'K1ABC W9XYZ -31', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ -50', & + 'K1ABC W9XYZ -50', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ +50', & + 'K1ABC W9XYZ +50', 1, 0, 0) + call expect_pack77_failure('K1ABC W9XYZ -55') + call expect_pack77_failure('K1ABC W9XYZ +51') + call expect_round_trip('K1ABC W9XYZ R+00', & + 'K1ABC W9XYZ R+00', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ R-31', & + 'K1ABC W9XYZ R-31', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ R-50', & + 'K1ABC W9XYZ R-50', 1, 0, 0) + call expect_round_trip('K1ABC W9XYZ R+50', & + 'K1ABC W9XYZ R+50', 1, 0, 0) + call expect_pack77_failure('K1ABC W9XYZ R-55') + call expect_pack77_failure('K1ABC W9XYZ R+51') + call expect_round_trip('K1ABC W9XYZ R FN42', & + 'K1ABC W9XYZ R FN42', 1, 0, 0) + call expect_pack77_failure('K1ABC W9XYZ FN42X') + call expect_pack77_failure('K1ABC W9XYZ R FN42X') + call expect_round_trip('K1ABC/P W9XYZ/P R FN42', & + 'K1ABC/P W9XYZ/P R FN42', 2, 0, 0) + call expect_round_trip('K1ABC/P W9XYZ/P FN42', & + 'K1ABC/P W9XYZ/P FN42', 2, 0, 0) + call expect_not_message_type('K1ABC/R W9XYZ/P FN42', 2, 0) + call expect_not_message_type('K1ABC W9XYZ +3', 1, 0) + call expect_round_trip('HELLO WORLD', & + 'HELLO WORLD', 0, 0, 0) + call expect_round_trip('hello', & + 'HELLO', 0, 0, 0) + call expect_round_trip('FREE TEXT MSG', & + 'FREE TEXT MSG', 0, 0, 0) + call expect_round_trip('ABCDEFGHIJKLM', & + 'ABCDEFGHIJKLM', 0, 0, 0) + call expect_pack77_failure('ABCDEFGHIJKLMN') + call expect_pack77_failure('HELLO WORLD 73') + call expect_pack77_failure('HELLO@WORLD') + call expect_pack77_failure('K1ABC PJ4/K9XYZ') + call expect_free_text_rejection('HELLO@WORLD', & + PACK77_STATUS_FREE_TEXT_INVALID) + call expect_free_text_rejection('THIS MESSAGE IS TOO LONG', & + PACK77_STATUS_FREE_TEXT_TOO_LONG) + call expect_pack77_structured('K1ABC W9XYZ FN42', 1, 0) + call expect_free_text_rejection('K1ABC W9XYZ@', & + PACK77_STATUS_FREE_TEXT_INVALID) + call expect_free_text_rejection('ABCDEFGHIJKLMN', & + PACK77_STATUS_FREE_TEXT_TOO_LONG) + call expect_free_text_rejection('A:B', & + PACK77_STATUS_FREE_TEXT_INVALID) + call expect_free_text_fallback('K1ABC R BOGUS', 'K1ABC R BOGUS') + call expect_legacy_truncating_fallback('ABCDEFGHIJKLMN', & + 'ABCDEFGHIJKLM') + call expect_legacy_truncating_fallback('K1ABCW9XYZ FN42', & + 'K1ABCW9XYZ FN') + call expect_legacy_matches_strict('K1ABC W9XYZ FN42') + call expect_legacy_matches_strict('FREE TEXT MSG') + call expect_legacy_fallback_failure('HELLO@WORLD 73', & + PACK77_STATUS_FREE_TEXT_INVALID) + call expect_round_trip('WA9XYZ KA1ABC R 16A EMA', & + 'WA9XYZ KA1ABC R 16A EMA', 0, 3, 0) + call expect_round_trip('WA9XYZ KA1ABC R 32A EMA', & + 'WA9XYZ KA1ABC R 32A EMA', 0, 4, 0) + call expect_round_trip('WA9XYZ KA1ABC 1A EMA', & + 'WA9XYZ KA1ABC 1A EMA', 0, 3, 0) + call expect_round_trip('WA9XYZ KA1ABC R 1A EMA', & + 'WA9XYZ KA1ABC R 1A EMA', 0, 3, 0) + call expect_round_trip_with_hashes('W1AW/P K1ABC 5A CT', & + '<W1AW/P> K1ABC 5A CT', 0, 3, 0, 'W1AW/P', '', '') + call expect_round_trip_with_hashes('ABCDEFG/HIJ KLMNOPQ/RST R 32A EMA', & + '<ABCDEFG/HIJ> <KLMNOPQ/RST> R 32A EMA', 0, 4, 0, & + 'ABCDEFG/HIJ', 'KLMNOPQ/RST', '') + call expect_round_trip('WA9XYZ KA1ABC 15F DX', & + 'WA9XYZ KA1ABC 15F DX', 0, 3, 0) + call expect_round_trip('WA9XYZ KA1ABC 17A EMA', & + 'WA9XYZ KA1ABC 17A EMA', 0, 4, 0) + call expect_round_trip_with_hashes('Y8W MW8WA/A R 17A ONE', & + 'Y8W <MW8WA/A> R 17A ONE', 0, 4, 0, 'MW8WA/A', '', '') + call expect_round_trip('WA9XYZ KA1ABC R 32A NB', & + 'WA9XYZ KA1ABC R 32A NB', 0, 4, 0) + call expect_pack77_failure('WA9XYZ KA1ABC R 1H EMA') + call expect_round_trip('PJ2/W1AW KA1ABC R 1A EMA', & + '<...> KA1ABC R 1A EMA', 0, 3, 0) + call expect_pack77_failure('WA9XYZ KA1ABC R 0A EMA') + call expect_pack77_failure('WA9XYZ KA1ABC R 33A EMA') + call expect_pack77_failure('WA9XYZ KA1ABC R 1A XYZ') + call expect_not_message_type('WA9XYZ KA1ABC +1A EMA', 0, 3) + call expect_not_message_type('WA9XYZ KA1ABC 01A EMA', 0, 3) + call expect_not_message_type('WA9XYZ KA1ABC R 1A EM', 0, 3) + call expect_not_message_type('WA9XYZ KA1ABC X 1A EMA', 0, 3) + call expect_not_message_type('<WA9XYZ> KA1ABC R 1A EMA', 0, 3) + call expect_pack77_failure('K1ABC/ K1A 1A CT') + call expect_pack77_failure('/K1ABC K1A 1A CT') + call expect_pack77_failure('A//B K1A 1A CT') + call expect_pack77_failure('K1ABC//P K1A 1A CT') + call expect_pack77_failure('ABCDEFGHI/JKL MNOPQRSTU/VWX 1A EMA') + call expect_round_trip('123456789ABCDEF012', & + '123456789ABCDEF012', 0, 5, 0) + call expect_round_trip_with_hint('0de', & + '0000000000000000DE', 0, 5, 0, 5, 0, '', '', '') + call expect_round_trip('TU; W9XYZ K1ABC R 579 MA', & + 'TU; W9XYZ K1ABC R 579 MA', 3, 0, 0) + call expect_round_trip('W9XYZ K1ABC R 579 MA', & + 'W9XYZ K1ABC R 579 MA', 3, 0, 0) + call expect_round_trip('W9XYZ K1ABC 579 MA', & + 'W9XYZ K1ABC 579 MA', 3, 0, 0) + call expect_round_trip('TU; W9XYZ G8ABC R 559 0013', & + 'TU; W9XYZ G8ABC R 559 0013', 3, 0, 0) + call expect_round_trip('W9XYZ G8ABC 559 0013', & + 'W9XYZ G8ABC 559 0013', 3, 0, 0) + call expect_round_trip('W9XYZ K1ABC 529 MA', & + 'W9XYZ K1ABC 529 MA', 3, 0, 0) + call expect_round_trip_with_hashes('W9XYZ W1AW/P R 599 MA', & + 'W9XYZ <W1AW/P> R 599 MA', 3, 0, 0, 'W1AW/P', '', '') + call expect_round_trip('TU; W9XYZ K1ABC 599 MA', & + 'TU; W9XYZ K1ABC 599 MA', 3, 0, 0) + call expect_round_trip('TU; W9XYZ K1ABC R 589 DC', & + 'TU; W9XYZ K1ABC R 589 DC', 3, 0, 0) + call expect_round_trip('W9XYZ VE3ABC 559 ON', & + 'W9XYZ VE3ABC 559 ON', 3, 0, 0) + call expect_round_trip('W9XYZ G8ABC 529 0001', & + 'W9XYZ G8ABC 529 0001', 3, 0, 0) + call expect_round_trip('W9XYZ G8ABC R 599 7999', & + 'W9XYZ G8ABC R 599 7999', 3, 0, 0) + call expect_round_trip('TU; W9XYZ G8ABC 529 0001', & + 'TU; W9XYZ G8ABC 529 0001', 3, 0, 0) + call expect_pack77_failure('W9XYZ K1ABC 509 MA') + call expect_pack77_failure('W9XYZ K1ABC R 519 MA') + call expect_pack77_failure('W9XYZ K1ABC R 609 MA') + call expect_pack77_failure('W9XYZ K1ABC R 579 XYZ') + call expect_pack77_failure('W9XYZ K1ABC 579 MAX') + call expect_pack77_failure('W9XYZ G8ABC R 559 13') + call expect_pack77_failure('W9XYZ G8ABC R 559 0000') + call expect_pack77_failure('W9XYZ G8ABC R 559 8000') + call expect_not_message_type('W9XYZ K1ABC R 579 MA JUNK', 3, 0) + call expect_not_message_type('<W9XYZ> K1ABC R 579 MA', 3, 0) + call expect_not_message_type('TU; GF9/XJ4PIE GP5MZC/1 R 539 1843', 3, 0) + call expect_raw_type3_unpack_failure(0) + call expect_raw_type3_unpack_success(1, & + 'W9XYZ K1ABC R 579 0001') + call expect_raw_type3_unpack_success(7999, & + 'W9XYZ K1ABC R 579 7999') + call expect_raw_type3_unpack_failure(8000) + call expect_raw_type3_unpack_failure(8191) + call expect_nonbinary_unpack_failure() + call expect_not_message_type('<W9XYZ> <K1ABC> R 579 MA', 3, 0) + call expect_round_trip('CQ PJ4/K1ABC', & + 'CQ PJ4/K1ABC', 4, 0, 0) + call expect_pack77_failure('CQ PJ4/K1ABC RR73') + call expect_not_message_type('CQ PJ4/K1ABC FK52', 1, 0) + call expect_round_trip('CQ N0CALL', & + 'CQ N0CALL', 4, 0, 0) + call expect_round_trip('CQ N0CAL FN31', & + 'CQ N0CAL FN31', 1, 0, 0) + call expect_not_message_type('CQ N0CALL FN31', 1, 0) + call expect_not_message_type('CQ N0CALL FN31', 4, 0) + call expect_pack77_failure('CQ N0CALL FN31') + call expect_pack77_failure('K1ABC PJ4/K9XYZ') + call expect_not_message_type('CQ 3DA0RS/W1ABC', 4, 0) + call expect_round_trip('CQ K1ABC FN42', & + 'CQ K1ABC FN42', 1, 0, 0) + call expect_round_trip('CQ 146 K1ABC FN42', & + 'CQ 146 K1ABC FN42', 1, 0, 0) + call expect_round_trip('CQ DX K1ABC FN42', & + 'CQ DX K1ABC FN42', 1, 0, 0) + call expect_round_trip('DE K1ABC FN42', & + 'DE K1ABC FN42', 1, 0, 0) + + call expect_round_trip('K1ABC FN42 37', & + 'K1ABC FN42 37', 0, 6, 0) + call expect_round_trip('PJ2/K1ABC 37', & + 'PJ2/K1ABC 37', 0, 6, 0) + call expect_round_trip('DL/K1ABC 37', & + 'DL/K1ABC 37', 0, 6, 0) + call expect_round_trip('K1ABC/P 37', & + 'K1ABC/P 37', 0, 6, 0) + call expect_not_message_type('00/K1ABC 37', 0, 6) + call expect_not_message_type('K1ABC/00 37', 0, 6) + call expect_round_trip_with_hint('<PJ4/K1ABC> FK52AB', & + '<PJ4/K1ABC> FK52AB', 0, 6, 0, 6, 0, 'PJ4/K1ABC', '', '') + call expect_not_message_type('PJ2/K1ABC FN42 37', 0, 6) + call expect_not_message_type('K1ABC FN4 37', 0, 6) + call expect_not_message_type('Q5A FN20 37', 0, 6) + call expect_not_message_type('VK9X/W1ABC 37', 0, 6) + call expect_not_message_type('A$/K1ABC 37', 0, 6) + call expect_not_message_type('K1ABC/A$ 37', 0, 6) + call expect_not_message_type('K1ABC/ABCD 37', 0, 6) + call expect_not_message_type('PJ2/Q5A 37', 0, 6) + call expect_not_message_type('K1ABC FN42 55', 0, 6) + call expect_not_message_type('K1ABC FN42 03', 0, 6) + call expect_not_message_type('<PJ4/K1ABC> FK52AB', 0, 6) + call expect_strict_telemetry_rejects('K1ABC W9XYZ') + call expect_strict_telemetry_rejects('') + call expect_strict_telemetry_rejects(' ') + call expect_strict_telemetry_rejects('+1') + call expect_strict_telemetry_rejects('-1') + call expect_strict_telemetry_rejects('ABC DEF') + call expect_strict_telemetry_rejects('123G') + call expect_strict_telemetry_rejects('123456789ABCDEF0123') + call expect_not_message_type('6666AAAAAAAA66666661ZZ', 0, 5) + call expect_prefer_wspr_rejects_invalid_type3('<PJ4/K1ABC> FK52A!') + call expect_prefer_wspr_rejects_invalid_type3('<PJ4/K1ABC>X FK52AB') + call expect_legacy_prefer_wspr_rejects('PJ4/K1ABC FK52A!') + + call expect_round_trip_with_hashes('<PJ4/K1ABC> W9XYZ RR73', & + '<PJ4/K1ABC> W9XYZ RR73', 1, 0, 0, 'PJ4/K1ABC', '', '') + call expect_round_trip_with_hashes('<PJ4/K1ABC> W9XYZ RRR', & + '<PJ4/K1ABC> W9XYZ RRR', 1, 0, 0, 'PJ4/K1ABC', '', '') + call expect_round_trip_with_hashes('<PJ4/K1ABC> W9XYZ 73', & + '<PJ4/K1ABC> W9XYZ 73', 1, 0, 0, 'PJ4/K1ABC', '', '') + if(configured_var) then + call expect_type_unpack_failure_with_hashes('PJ2/W1AW <W7ABC>', & + 4, 0, 0, 'W7ABC', '', '') + else + call expect_round_trip_with_hashes('PJ2/W1AW <W7ABC>', & + 'PJ2/W1AW <W7ABC>', 4, 0, 0, 'W7ABC', '', '') + endif + call expect_round_trip_with_hashes('PJ2/W1AW <W7ABC> RRR', & + 'PJ2/W1AW <W7ABC> RRR', 4, 0, 0, 'W7ABC', '', '') + call expect_round_trip_with_hashes('PJ2/W1AW <W7ABC> RR73', & + 'PJ2/W1AW <W7ABC> RR73', 4, 0, 0, 'W7ABC', '', '') + call expect_round_trip_with_hashes('PJ2/W1AW <W7ABC> 73', & + 'PJ2/W1AW <W7ABC> 73', 4, 0, 0, 'W7ABC', '', '') + call expect_round_trip_with_hashes('<W7ABC> PJ2/W1AW RR73', & + '<W7ABC> PJ2/W1AW RR73', 4, 0, 0, 'W7ABC', '', '') + call expect_round_trip_with_context('PJ2/W1AW <W7ABC> 73', & + 'PJ2/W1AW <W7ABC> 73', 4, 0, 0, 'W7ABC', 'N0BBB', '', '', '') + call expect_round_trip_with_context('<PJ4/K1ABC> W9XYZ RR73', & + '<PJ4/K1ABC> W9XYZ RR73', 1, 0, 1, 'PJ4/K1ABC', 'W9XYZ', '', '', '') + call expect_round_trip_with_hashes('<PJ4/K1ABC> W9XYZ -12', & + '<PJ4/K1ABC> W9XYZ -12', 1, 0, 0, 'PJ4/K1ABC', '', '') + call expect_not_message_type('<PJ4/K1ABC> W9XYZ -12', 4, 0) + call expect_not_message_type('<PJ4/K1ABC>X W9XYZ RR73', 1, 0) + call expect_not_message_type('W9XYZ <PJ4/K1ABC>X RR73', 1, 0) + call expect_not_message_type('K1ABC <W7ABC> RR73', 4, 0) + call expect_not_message_type('<W7ABC> K1ABC RR73', 4, 0) + call expect_not_message_type('<W7ABC> <PJ4/K1ABC> RR73', 4, 0) + call expect_pack77_failure('CQ <PJ4/K1ABC>') + + call expect_round_trip_with_hashes('<W3CCX> <K1JT/P> 590001 FN20QI', & + '<W3CCX> <K1JT/P> 590001 FN20QI', 5, 0, 0, 'W3CCX', 'K1JT/P', '') + call expect_round_trip_with_hashes('<W3CCX> <K1JT/P> 520001 FN20QI', & + '<W3CCX> <K1JT/P> 520001 FN20QI', 5, 0, 0, 'W3CCX', 'K1JT/P', '') + call expect_round_trip_with_hashes('<W3CCX> <K1JT/P> R 520001 FN20QI', & + '<W3CCX> <K1JT/P> R 520001 FN20QI', 5, 0, 0, 'W3CCX', 'K1JT/P', '') + call expect_round_trip_with_hashes('<W3CCX> <K1JT/P> R 592047 FN20QI', & + '<W3CCX> <K1JT/P> R 592047 FN20QI', 5, 0, 0, 'W3CCX', 'K1JT/P', '') + call expect_round_trip('<W3CCX> <K1JT/P> 590001 FN20QI', & + '<...> <...> 590001 FN20QI', 5, 0, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 520000 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 530000 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 592048 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 582048 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 594095 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 590001 FN20QY', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 590001 FN20Q', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> X 590001 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> RR 590001 FN20QI', 5, 0) + call expect_not_message_type('W3CCX <K1JT/P> 590001 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX <K1JT/P> 590001 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P 590001 FN20QI', 5, 0) + call expect_not_message_type('<ABCDEFGHIJK>X <K1JT/P> 590001 FN20QI', 5, 0) + call expect_not_message_type('<W3CCX> <K1JT/P> 0590001 FN20QI', 5, 0) + + call expect_round_trip_with_context('K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_round_trip_with_context('K1ABC RR73; W9XYZ <KH1/KH7Z> -30', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -30', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_round_trip_with_context('K1ABC RR73; W9XYZ <KH1/KH7Z> +00', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> +00', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_round_trip_with_context('K1ABC RR73; W9XYZ <KH1/KH7Z> +32', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> +32', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_pack77_failure('K1ABC RR73; W9XYZ <KH1/KH7Z> -11') + call expect_pack77_failure('K1ABC RR73; W9XYZ <KH1/KH7Z> -31') + call expect_pack77_failure('K1ABC RR73; W9XYZ <KH1/KH7Z> +33') + call expect_pack77_failure('K1ABC RR73; W9XYZ <KH1/KH7Z> +34') + call expect_round_trip_with_context('K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, 0, & + 'KH1/KH7Z', 'N0BBB', '', '', '') + call expect_not_message_type('K1ABC RR73: W9XYZ <KH1/KH7Z> -12', 0, 1) + call expect_not_message_type('K1ABC RRR; W9XYZ <KH1/KH7Z> -12', 0, 1) + call expect_round_trip_with_context('PJ2/W1AW RR73; W9XYZ <KH1/KH7Z> -12', & + '<...> RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_round_trip_with_context('K1ABC RR73; PJ2/W1AW <KH1/KH7Z> -12', & + 'K1ABC RR73; <...> <KH1/KH7Z> -12', 0, 1, 1, & + 'N0AAA', 'KH1/KH7Z', '', '', '') + call expect_round_trip_with_hashes('PJ2/W1AW RR73; W9XYZ <KH1/KH7Z> -12', & + '<PJ2/W1AW> RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, 0, & + 'PJ2/W1AW', 'KH1/KH7Z', '') + call expect_pack77_failure('PJ2/W1AW RR73; W9/YZ <KH1/KH7Z> -12') + call expect_not_message_type('<K1ABC> RR73; W9XYZ <KH1/KH7Z> -12', 0, 1) + call expect_not_message_type('K1ABC RR73; W9XYZ KH1/KH7Z -12', 0, 1) + call expect_not_message_type('K1ABC RR73; W9XYZ <KH1/KH7Z>X -12', 0, 1) + call expect_not_message_type('K1ABC RR73; W9XYZ <KH1/KH7Z> 3', 0, 1) + call expect_not_message_type('K1ABC RR73; W9XYZ <KH1/KH7Z> -12 JUNK', 0, 1) + + call expect_round_trip(' k1abc w9xyz fn42', & + 'K1ABC W9XYZ FN42', 1, 0, 0) + call expect_round_trip('K1ABC/R W9XYZ/R R FN42', & + 'K1ABC/R W9XYZ/R R FN42', 1, 0, 0) + call expect_round_trip('CQ PJ2/W1AW', & + 'CQ PJ2/W1AW', 4, 0, 0) + call expect_round_trip('CQ TEST/W1AW', & + 'CQ TEST/W1AW', 4, 0, 0) + call expect_round_trip('QRZ PJ4/K1ABC', & + 'QRZ PJ4/K1ABC', 0, 0, 0) + call expect_pack77_failure('CQ K1ABC R FN42') + call expect_not_message_type('CQ K1A W1AW FN20', 1, 0) + call expect_not_message_type('CQ TJ. K1ABC FN20', 1, 0) + call expect_not_message_type('<PJ4/K1ABC> <W7ABC> TEST', 5, 0) + call expect_not_message_type('<A/B> <C/D>', 1, 0) + call expect_not_message_type('<A/B> <C/D>', 5, 0) + + call expect_dual_angle_type1_placeholders('<W1AW> <K1JT>', '<...> <...>') + call expect_dual_angle_type1_placeholders('<W1AW> <K1JT> RR73', & + '<...> <...> RR73') + + contains + + subroutine expect_round_trip(input,expected,want_i3,want_n3,nrx) + character(len=*), intent(in) :: input, expected + integer, intent(in) :: want_i3, want_n3, nrx + + call expect_round_trip_with_context(input,expected,want_i3,want_n3,nrx, & + 'N0AAA', 'N0BBB', '', '', '') + end subroutine expect_round_trip + + subroutine expect_round_trip_with_hashes(input,expected,want_i3,want_n3, & + nrx,hash_call_1,hash_call_2,hash_call_3) + character(len=*), intent(in) :: input, expected + integer, intent(in) :: want_i3, want_n3, nrx + character(len=*), intent(in) :: hash_call_1, hash_call_2, hash_call_3 + + call expect_round_trip_with_context(input,expected,want_i3,want_n3,nrx, & + 'N0AAA', 'N0BBB', hash_call_1, hash_call_2, hash_call_3) + end subroutine expect_round_trip_with_hashes + + subroutine expect_round_trip_with_context(input,expected,want_i3,want_n3, & + nrx,mycall,dxcall,hash_call_1,hash_call_2,hash_call_3) + character(len=*), intent(in) :: input, expected + integer, intent(in) :: want_i3, want_n3, nrx + character(len=*), intent(in) :: mycall, dxcall + character(len=*), intent(in) :: hash_call_1, hash_call_2, hash_call_3 + + call expect_round_trip_with_pack_state(input,expected,want_i3,want_n3, & + -1,-1,nrx,mycall,dxcall,hash_call_1,hash_call_2,hash_call_3) + end subroutine expect_round_trip_with_context + + subroutine expect_round_trip_with_hint(input,expected,want_i3,want_n3, & + pack_i3,pack_n3,nrx,hash_call_1,hash_call_2,hash_call_3) + character(len=*), intent(in) :: input, expected + integer, intent(in) :: want_i3, want_n3, pack_i3, pack_n3, nrx + character(len=*), intent(in) :: hash_call_1, hash_call_2, hash_call_3 + + call expect_round_trip_with_pack_state(input,expected,want_i3,want_n3, & + pack_i3,pack_n3,nrx,'N0AAA','N0BBB',hash_call_1,hash_call_2, & + hash_call_3) + end subroutine expect_round_trip_with_hint + + subroutine expect_round_trip_with_pack_state(input,expected,want_i3,want_n3, & + pack_i3,pack_n3,nrx,mycall,dxcall,hash_call_1,hash_call_2,hash_call_3) + character(len=*), intent(in) :: input, expected + integer, intent(in) :: want_i3, want_n3, pack_i3, pack_n3, nrx + character(len=*), intent(in) :: mycall, dxcall + character(len=*), intent(in) :: hash_call_1, hash_call_2, hash_call_3 + character(len=77) :: c77 + character(len=37) :: canonical, canonical_decoded, decoded, packed_input + integer :: got_i3, got_n3 + logical :: canonical_ok, ok + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + got_i3=pack_i3 + got_n3=pack_n3 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_with_hint(packed_input,pack_i3,pack_n3) + call assert_pack77_result('pack77',input,encoded) + call assert_true('pack77 gate not rejected',encoded%status.ne.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + + call assert_message_type('pack77',input,want_i3,want_n3,got_i3,got_n3) + canonical_decoded=' ' + canonical_ok=.false. + call unpack77(c77,0,canonical_decoded,canonical_ok) + call assert_decode('pack77 canonical',input,canonical_decoded, & + canonical_decoded,canonical_ok) + canonical=canonical_decoded + call assert_canonical_text('pack77',input,canonical,canonical_decoded) + + call reset_packjt77_mode_state(mycall, dxcall) + call prime_hash_call_mode(hash_call_1) + call prime_hash_call_mode(hash_call_2) + call prime_hash_call_mode(hash_call_3) + + decoded=' ' + ok=.false. + call unpack77_mode(c77,nrx,decoded,ok) + if(.not.ok) then + write(*,1010) trim(input) +1010 format('Unpack failure for "',a,'"') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1020) trim(input), trim(expected), trim(decoded) +1020 format('Round-trip failure for "',a,'"; expected "',a,'"; got "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_round_trip_with_pack_state + + subroutine expect_not_message_type(input,blocked_i3,blocked_n3) + character(len=*), intent(in) :: input + integer, intent(in) :: blocked_i3, blocked_n3 + character(len=37) :: packed_input + integer :: got_i3, got_n3 + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + got_i3=-1 + got_n3=-1 + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + if(.not.encoded%encoded) then + ntests=ntests+1 + return + endif + got_i3=encoded%i3 + got_n3=encoded%n3 + end block + if(got_i3.eq.blocked_i3 .and. got_n3.eq.blocked_n3) then + write(*,1060) trim(input), blocked_i3, blocked_n3 +1060 format('Message "',a,'" packed as blocked type ',i0,'.',i0) + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_not_message_type + + subroutine expect_raw_type3_unpack_failure(nexch) + integer, intent(in) :: nexch + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok, unpack_ok + + call encode_pack77_type3(0,12751800,10214965,1,5,nexch,c77,ok) + call assert_true('raw Type 3 payload encoded',ok) + + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + decoded=' ' + unpack_ok=.true. + call unpack77_mode(c77,0,decoded,unpack_ok) + if(unpack_ok) then + write(*,1080) nexch, trim(decoded) +1080 format('Raw Type 3 exchange ',i0,' decoded successfully as "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_raw_type3_unpack_failure + + subroutine expect_raw_type3_unpack_success(nexch,expected) + integer, intent(in) :: nexch + character(len=*), intent(in) :: expected + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok, unpack_ok + + call encode_pack77_type3(0,12751800,10214965,1,5,nexch,c77,ok) + call assert_true('raw Type 3 payload encoded',ok) + + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + decoded=' ' + unpack_ok=.false. + call unpack77_mode(c77,0,decoded,unpack_ok) + call assert_decode('raw Type 3 exchange boundary',expected,expected, & + decoded,unpack_ok) + + ntests=ntests+1 + end subroutine expect_raw_type3_unpack_success + + subroutine expect_nonbinary_unpack_failure() + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok + + c77=repeat('0',77) + c77(10:10)='x' + c77(75:77)='001' + + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + decoded=' ' + ok=.true. + call unpack77_mode(c77,0,decoded,ok) + if(ok) then + write(*,1082) trim(decoded) +1082 format('Non-binary payload decoded successfully as "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_nonbinary_unpack_failure + + subroutine expect_pack77_failure(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + if(encoded%encoded) then + write(*,1095) trim(input), encoded%i3, encoded%n3 +1095 format('Message "',a,'" unexpectedly packed as ',i0,'.',i0) + error stop 1 + endif + end block + + ntests=ntests+1 + end subroutine expect_pack77_failure + + subroutine expect_free_text_rejection(input,want_status) + character(len=*), intent(in) :: input + integer, intent(in) :: want_status + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + if(encoded%encoded) then + write(*,1098) trim(input), encoded%i3, encoded%n3 +1098 format('Free text "',a,'" unexpectedly packed as ',i0, & + '.',i0) + error stop 1 + endif + call assert_int('free text reject status '//trim(input), & + want_status,encoded%status) + end block + + ntests=ntests+1 + end subroutine expect_free_text_rejection + + subroutine expect_strict_telemetry_rejects(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=strict_telemetry_result_from_schema(packed_input) + if(encoded%encoded) then + write(*,1097) trim(input), encoded%i3, encoded%n3 +1097 format('Strict telemetry message "',a,'" unexpectedly packed as ', & + i0,'.',i0) + error stop 1 + endif + end block + + ntests=ntests+1 + end subroutine expect_strict_telemetry_rejects + + subroutine expect_prefer_wspr_rejects_invalid_type3(input) + character(len=*), intent(in) :: input + + call expect_prefer_wspr_rejects_invalid_type3_impl(input) + end subroutine expect_prefer_wspr_rejects_invalid_type3 + + subroutine expect_prefer_wspr_rejects_invalid_type3_impl(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + character(len=24) :: prefix + + prefix='Preferred WSPR' + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input, & + pack77_options(prefer_wspr_50bit=.true.)) + if(encoded%encoded) then + write(*,1096) trim(prefix), trim(input), encoded%i3, encoded%n3 +1096 format(a,' message "',a,'" unexpectedly packed as ',i0,'.',i0) + error stop 1 + endif + call assert_true('failed preferred WSPR status', & + encoded%status.eq.PACK77_STATUS_PREFERRED_FAMILY_REJECTED) + end block + + ntests=ntests+1 + end subroutine expect_prefer_wspr_rejects_invalid_type3_impl + + subroutine expect_type_unpack_failure_with_hashes(input,want_i3,want_n3, & + nrx,hash_call_1,hash_call_2,hash_call_3) + character(len=*), intent(in) :: input + integer, intent(in) :: want_i3, want_n3, nrx + character(len=*), intent(in) :: hash_call_1, hash_call_2, hash_call_3 + character(len=77) :: c77 + character(len=37) :: decoded, packed_input + integer :: got_i3, got_n3 + logical :: ok + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('pack77',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('pack77',input,want_i3,want_n3,got_i3,got_n3) + + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + call prime_hash_call_mode(hash_call_1) + call prime_hash_call_mode(hash_call_2) + call prime_hash_call_mode(hash_call_3) + + decoded=' ' + ok=.true. + call unpack77_mode(c77,nrx,decoded,ok) + if(ok) then + write(*,1100) trim(input), trim(decoded) +1100 format('Message "',a,'" decoded successfully as "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_type_unpack_failure_with_hashes + + subroutine expect_free_text_fallback(input,expected) + character(len=*), intent(in) :: input, expected + + call expect_free_text_fallback_impl(input,expected) + end subroutine expect_free_text_fallback + + subroutine expect_free_text_fallback_impl(input,expected) + character(len=*), intent(in) :: input, expected + character(len=77) :: c77 + character(len=37) :: canonical, decoded, packed_input + character(len=40) :: pack_label + character(len=16) :: prefix + integer :: got_i3, got_n3 + logical :: ok + + pack_label='pack77' + prefix='Free-text' + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + got_i3=-1 + got_n3=-1 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result(trim(pack_label),packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type(trim(pack_label),input,0,0,got_i3,got_n3) + + decoded=' ' + ok=.false. + call unpack77_mode(c77,0,decoded,ok) + if(.not.ok) then + write(*,1070) trim(prefix), trim(input) +1070 format(a,' unpack failure for "',a,'"') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1085) trim(prefix), trim(input), trim(expected), trim(decoded) +1085 format(a,' failure for "',a,'"; expected "',a,'"; got "',a,'"') + error stop 1 + endif + canonical=decoded + call assert_canonical_text('pack77 free text',input,canonical,decoded) + + ntests=ntests+1 + end subroutine expect_free_text_fallback_impl + + subroutine expect_legacy_truncating_fallback(input,expected) + character(len=*), intent(in) :: input, expected + character(len=37) :: decoded, packed_input + logical :: ok + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: strict_encoded, legacy_encoded + strict_encoded=pack77_result_from_api(packed_input) + if(strict_encoded%encoded) then + write(*,1105) trim(input), strict_encoded%i3, strict_encoded%n3 +1105 format('Strict message "',a,'" unexpectedly packed as ',i0,'.',i0) + error stop 1 + endif + + legacy_encoded=pack77_legacy_result_from_api(packed_input) + call assert_pack77_result('legacy truncating fallback', & + packed_input,legacy_encoded) + call assert_message_type('legacy truncating fallback',input, & + 0,0,legacy_encoded%i3,legacy_encoded%n3) + + decoded=' ' + ok=.false. + call unpack77_mode(legacy_encoded%c77,0,decoded,ok) + call assert_decode('legacy truncating fallback',input,expected, & + decoded,ok) + end block + + ntests=ntests+1 + end subroutine expect_legacy_truncating_fallback + + subroutine expect_legacy_matches_strict(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: strict_encoded, legacy_encoded + strict_encoded=pack77_result_from_api(packed_input) + legacy_encoded=pack77_legacy_result_from_api(packed_input) + call assert_pack77_result('strict pack77',packed_input,strict_encoded) + call assert_pack77_result('legacy wrapper',packed_input,legacy_encoded) + call assert_int('legacy matches strict i3',strict_encoded%i3, & + legacy_encoded%i3) + call assert_int('legacy matches strict n3',strict_encoded%n3, & + legacy_encoded%n3) + call assert_text_equal('legacy matches strict c77', & + strict_encoded%c77,legacy_encoded%c77) + end block + + ntests=ntests+1 + end subroutine expect_legacy_matches_strict + + subroutine expect_legacy_fallback_failure(input,want_status) + character(len=*), intent(in) :: input + integer, intent(in) :: want_status + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_legacy_result_from_api(packed_input) + if(encoded%encoded) then + write(*,1110) trim(input), encoded%i3, encoded%n3 +1110 format('Legacy fallback message "',a,'" unexpectedly packed as ', & + i0,'.',i0) + error stop 1 + endif + call assert_int('legacy fallback reject status '//trim(input), & + want_status,encoded%status) + end block + + ntests=ntests+1 + end subroutine expect_legacy_fallback_failure + + subroutine expect_legacy_prefer_wspr_rejects(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_legacy_result_from_api(packed_input, & + pack77_options(prefer_wspr_50bit=.true.)) + if(encoded%encoded) then + write(*,1115) trim(input), encoded%i3, encoded%n3 +1115 format('Legacy WSPR message "',a,'" unexpectedly packed as ', & + i0,'.',i0) + error stop 1 + endif + call assert_int('legacy preferred WSPR status', & + PACK77_STATUS_PREFERRED_FAMILY_REJECTED,encoded%status) + end block + + ntests=ntests+1 + end subroutine expect_legacy_prefer_wspr_rejects + + subroutine expect_pack77_structured(input,want_i3,want_n3) + character(len=*), intent(in) :: input + integer, intent(in) :: want_i3, want_n3 + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('pack77 structured', & + packed_input,encoded) + call assert_message_type('pack77 structured',input, & + want_i3,want_n3,encoded%i3,encoded%n3) + end block + + ntests=ntests+1 + end subroutine expect_pack77_structured + + subroutine expect_dual_angle_type1_placeholders(input,expected) + character(len=*), intent(in) :: input, expected + character(len=77) :: c77 + character(len=37) :: canonical, canonical_decoded, decoded, packed_input + integer :: got_i3, got_n3 + logical :: canonical_ok, ok + + packed_input=' ' + packed_input=input + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('pack77',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('pack77',input,1,0,got_i3,got_n3) + canonical_decoded=' ' + canonical_ok=.false. + call unpack77(c77,0,canonical_decoded,canonical_ok) + call assert_decode('dual-angle Type 1 canonical',input,canonical_decoded, & + canonical_decoded,canonical_ok) + canonical=canonical_decoded + call assert_canonical_text('dual-angle Type 1',input,canonical, & + canonical_decoded) + + call reset_packjt77_mode_state('N0AAA', 'N0BBB') + decoded=' ' + ok=.false. + call unpack77_mode(c77,0,decoded,ok) + if(.not.ok) then + write(*,1040) trim(input) +1040 format('Dual-angle Type 1 unpack failure for "',a,'"') + error stop 1 + endif + if(trim(decoded).ne.expected) then + write(*,1050) trim(input), trim(expected), trim(decoded) +1050 format('Dual-angle Type 1 placeholder failure for "',a, & + '"; expected "',a,'"; got "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_dual_angle_type1_placeholders + + subroutine reset_packjt77_mode_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + if(configured_var) then + call reset_packjt77var_state(mycall,dxcall) + else + call reset_packjt77_state(mycall,dxcall) + endif + end subroutine reset_packjt77_mode_state + + subroutine prime_hash_call_mode(callsign) + character(len=*), intent(in) :: callsign + + if(configured_var) then + call prime_hash_call_var(callsign) + else + call prime_hash_call(callsign) + endif + end subroutine prime_hash_call_mode + + subroutine unpack77_mode(c77,nrx,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + if(configured_var) then + call unpack77_configured(c77,nrx,decoded,ok,unpack77_options(thread_index=1)) + else + call unpack77(c77,nrx,decoded,ok) + endif + end subroutine unpack77_mode + + end subroutine run_packjt77_common_invariants + + subroutine run_packjt77_standard_schema_invariants(ntests) + integer, intent(inout) :: ntests + + call expect_type12_qso_tail_mapping() + + contains + + subroutine expect_type12_qso_tail_mapping() + call expect_type12_qso_tail_irpt('Type 1 no tail', & + 1,32400+1,'K1ABC W9XYZ') + call expect_type12_qso_tail_irpt('Type 1 RRR', & + 1,32400+2,'K1ABC W9XYZ RRR') + call expect_type12_qso_tail_irpt('Type 1 RR73', & + 1,32400+3,'K1ABC W9XYZ RR73') + call expect_type12_qso_tail_irpt('Type 1 73', & + 1,32400+4,'K1ABC W9XYZ 73') + + call expect_type12_qso_tail_irpt('Type 2 no tail', & + 2,32400+1,'K1ABC/P W9XYZ/P') + call expect_type12_qso_tail_irpt('Type 2 RRR', & + 2,32400+2,'K1ABC/P W9XYZ/P RRR') + call expect_type12_qso_tail_irpt('Type 2 RR73', & + 2,32400+3,'K1ABC/P W9XYZ/P RR73') + call expect_type12_qso_tail_irpt('Type 2 73', & + 2,32400+4,'K1ABC/P W9XYZ/P 73') + + ntests=ntests+1 + end subroutine expect_type12_qso_tail_mapping + + subroutine expect_type12_qso_tail_irpt(label,want_i3,want_igrid4,expected) + character(len=*), intent(in) :: label, expected + integer, intent(in) :: want_i3, want_igrid4 + character(len=37) :: decoded + character(len=77) :: c77 + type(pack77_type12_fields) :: fields + logical :: ok, unpack_ok + + ok=.false. + if(want_i3.eq.1) then + call encode_pack77_type1(10214965,0,12751800,0,0,want_igrid4,c77,ok) + else + call encode_pack77_type2(10214965,1,12751800,1,0,want_igrid4,c77,ok) + endif + call assert_true(trim(label)//' Type 1/2 schema encode',ok) + + fields=pack77_type12_fields() + if(want_i3.eq.1) then + call decode_pack77_type1(c77,fields,ok) + else + call decode_pack77_type2(c77,fields,ok) + endif + call assert_true(trim(label)//' Type 1/2 schema decode',ok) + call assert_int(trim(label)//' igrid4',want_igrid4,fields%igrid4) + + call reset_packjt77_state('N0AAA', 'N0BBB') + decoded=' ' + unpack_ok=.false. + call unpack77(c77,0,decoded,unpack_ok) + call assert_true(trim(label)//' unpack',unpack_ok) + call assert_text_equal(trim(label)//' decoded tail',expected,decoded) + end subroutine expect_type12_qso_tail_irpt + + end subroutine run_packjt77_standard_schema_invariants + + subroutine reset_packjt77_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + + call clear_standard_state(mycall,dxcall) + end subroutine reset_packjt77_state + + subroutine reset_packjt77var_state(mycall,dxcall) + character(len=*), intent(in) :: mycall, dxcall + integer :: n10, n12, n22 + + call clear_all_state(mycall,dxcall) + if(len_trim(mycall).gt.2) then + call save_hash_call(mycall13,hashmy10_configured,hashmy12_configured, & + hashmy22_configured) + endif + if(len_trim(dxcall).gt.2) then + call prime_hash_call_var(dxcall) + call save_hash_call(dxcall13,n10,n12,n22) + endif + end subroutine reset_packjt77var_state + + subroutine prime_hash_call(callsign) + character(len=*), intent(in) :: callsign + integer :: n10, n12, n22 + character(len=13) :: c13 + + if(len_trim(callsign).le.0) return + c13=' ' + c13=callsign + call save_hash_call(c13,n10,n12,n22) + end subroutine prime_hash_call + + subroutine prime_hash_call_var(callsign) + character(len=*), intent(in) :: callsign + integer :: n10, n12, n22 + character(len=13) :: c13 + + if(len_trim(callsign).le.0) return + call normalize_call(callsign,c13) + if(len_trim(c13).le.0) return + call save_hash_call(c13,n10,n12,n22) + call store_rx_hash_var(c13) + end subroutine prime_hash_call_var + + subroutine store_rx_hash_var(c13) + character(len=*), intent(in) :: c13 + integer :: n10, n12, n22, i + + n10=ihashcall(c13,10) + if(n10.ge.0 .and. n10.le.1023) calls10(n10)=c13 + n12=ihashcall(c13,12) + if(n12.ge.0 .and. n12.le.4095) calls12(n12)=c13 + n22=ihashcall(c13,22) + do i=1,nzhash + if(ihash22(i).eq.n22) then + calls22(i)=c13 + return + endif + enddo + if(nzhash.lt.MAXHASH) then + if(nzhash.ge.1) then + ihash22(nzhash+1:2:-1)=ihash22(nzhash:1:-1) + calls22(nzhash+1:2:-1)=calls22(nzhash:1:-1) + endif + nzhash=nzhash+1 + ihash22(1)=n22 + calls22(1)=c13 + endif + end subroutine store_rx_hash_var + +end module packjt77_test_helpers diff --git a/tests/unit/packjt77/silent_rewrite_corpus.txt b/tests/unit/packjt77/silent_rewrite_corpus.txt new file mode 100644 index 00000000..ed668d6d --- /dev/null +++ b/tests/unit/packjt77/silent_rewrite_corpus.txt @@ -0,0 +1,54 @@ +W1AW/P K1ABC 5A CT | compound-call-regression +K1ABC/R W9XYZ/P FN42 | compound-call-regression +CQ PJ4/K1ABC FK52 | compound-call-regression +VK9X/W1ABC 37 | compound-call-regression +K1ABC FN42 55 | compound-call-regression +CQ 3DA0RS/W1ABC | compound-call-regression +CQ PJ4/K1ABC | compound-call-regression +CQ <PJ4/K1ABC> | compound-call-regression +PJ2/W1AW <W7ABC> RR73 | silent-rewrite-regression +<PJ4/K1ABC> W9XYZ RR73 | silent-rewrite-regression +K1ABC RR73; W9XYZ <KH1/KH7Z> -12 | silent-rewrite-regression +<W3CCX> <K1JT/P> 590001 FN20QI | silent-rewrite-regression +PJ2/W1AW KA1ABC R 1A EMA | silent-rewrite-regression +Y8W MW8WA/A R 17A ONE | silent-rewrite-regression +W9XYZ W1AW/P R 599 MA | silent-rewrite-regression +K1ABC FN42 37 | silent-rewrite-regression +PJ2/K1ABC 37 | silent-rewrite-regression +K1ABC/P 37 | silent-rewrite-regression +<PJ4/K1ABC>X W9XYZ RR73 | malformed-bracket +W9XYZ <PJ4/K1ABC>X RR73 | malformed-bracket +<PJ4/K1ABC> FK52A! | malformed-bracket +<PJ4/K1ABC>X FK52AB | malformed-bracket +<W3CCX <K1JT/P> 590001 FN20QI | malformed-bracket +<W3CCX> <K1JT/P 590001 FN20QI | malformed-bracket +<ABCDEFGHIJK>X <K1JT/P> 590001 FN20QI | malformed-bracket +K1ABC RR73; W9XYZ <KH1/KH7Z>X -12 | malformed-bracket +K1ABC/ K1A 1A CT | grammar-edge +/K1ABC K1A 1A CT | grammar-edge +A//B K1A 1A CT | grammar-edge +K1ABC//P K1A 1A CT | grammar-edge +K1ABC <W7ABC> RR73 | grammar-edge +<W7ABC> K1ABC RR73 | grammar-edge +<W7ABC> <PJ4/K1ABC> RR73 | grammar-edge +<A/B> <C/D> | grammar-edge +K1ABC RR73; PJ2/W1AW <KH1/KH7Z> -12 | grammar-edge +PJ2/W1AW RR73; W9XYZ <KH1/KH7Z> -12 | grammar-edge +K1ABC RR73: W9XYZ <KH1/KH7Z> -12 | grammar-edge +K1ABC RRR; W9XYZ <KH1/KH7Z> -12 | grammar-edge +WA9XYZ KA1ABC R 1H EMA | grammar-edge +WA9XYZ KA1ABC R 0A EMA | grammar-edge +WA9XYZ KA1ABC 01A EMA | grammar-edge +W9XYZ K1ABC 579 MAX | grammar-edge +W9XYZ G8ABC R 559 8000 | grammar-edge +K1ABC FN42 03 | grammar-edge +A$/K1ABC 37 | grammar-edge +K1ABC/ABCD 37 | grammar-edge +Q5A FN20 37 | grammar-edge +CQ K1ABC R FN42 | grammar-edge +CQ N0CALL FN31 | grammar-edge +K1ABC PJ4/K9XYZ | grammar-edge +QRZ PJ4/K1ABC | grammar-edge +K1ABC RR73; W9XYZ <KH1/KH7Z> -12 JUNK | overlong-field +<W3CCX> <K1JT/P> 590001 FN20QI EXTRA | overlong-field +PJ2/W1AW RR73; W9/YZ <KH1/KH7Z> -12 | overlong-field diff --git a/tests/unit/packjt77/test_encode77.cmake b/tests/unit/packjt77/test_encode77.cmake new file mode 100644 index 00000000..f614241a --- /dev/null +++ b/tests/unit/packjt77/test_encode77.cmake @@ -0,0 +1,39 @@ +execute_process( + COMMAND "${ENCODE77}" "CQ K1ABC FN42" + RESULT_VARIABLE valid_result + OUTPUT_VARIABLE valid_output + ERROR_VARIABLE valid_error +) +if (NOT valid_result EQUAL 0) + message(FATAL_ERROR "Valid message failed (${valid_result}):\n${valid_output}${valid_error}") +endif () +if (NOT valid_output MATCHES "1[ ]+OK[ ]+CQ K1ABC FN42[ ]+CQ K1ABC FN42") + message(FATAL_ERROR "Valid message output was unexpected:\n${valid_output}") +endif () + +execute_process( + COMMAND "${ENCODE77}" "THIS FREE TEXT IS TOO LONG" + RESULT_VARIABLE rejected_result + OUTPUT_VARIABLE rejected_output + ERROR_VARIABLE rejected_error +) +if (rejected_result EQUAL 0) + message(FATAL_ERROR "Rejected message returned success:\n${rejected_output}") +endif () +if (NOT rejected_output MATCHES "REJECTED[ ]+THIS FREE TEXT IS TOO LONG[ ]+free text too long") + message(FATAL_ERROR "Rejected message output was unexpected:\n${rejected_output}${rejected_error}") +endif () + +execute_process( + COMMAND "${ENCODE77}" -f "${INPUT_FILE}" + WORKING_DIRECTORY "${INPUT_DIR}" + RESULT_VARIABLE batch_result + OUTPUT_VARIABLE batch_output + ERROR_VARIABLE batch_error +) +if (batch_result EQUAL 0) + message(FATAL_ERROR "Batch with a rejection returned success:\n${batch_output}") +endif () +if (NOT batch_output MATCHES "Summary: 2 encoded, 1 rejected, 0 unpack failures, 0 differences") + message(FATAL_ERROR "Batch summary was unexpected:\n${batch_output}${batch_error}") +endif () diff --git a/tests/unit/packjt77/test_pack77_cli_fallbacks.cmake b/tests/unit/packjt77/test_pack77_cli_fallbacks.cmake new file mode 100644 index 00000000..ed3d3aa1 --- /dev/null +++ b/tests/unit/packjt77/test_pack77_cli_fallbacks.cmake @@ -0,0 +1,75 @@ +function(expect_fallback label executable expected_output) + execute_process( + COMMAND "${executable}" ${ARGN} + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + ) + if (NOT result EQUAL 0) + message(FATAL_ERROR "${label} fallback failed (${result}):\n${output}${error}") + endif () + if (NOT output MATCHES "${expected_output}") + message(FATAL_ERROR "${label} fallback output was unexpected:\n${output}") + endif () +endfunction() + +function(expect_rejected label executable) + execute_process( + COMMAND "${executable}" "HELLO@WORLD" ${ARGN} + RESULT_VARIABLE result + OUTPUT_VARIABLE output + ERROR_VARIABLE error + ) + if (result EQUAL 0) + message(FATAL_ERROR "${label} accepted an unrepresentable message:\n${output}${error}") + endif () + if (NOT output MATCHES "Cannot encode message:[ ]+HELLO@WORLD") + message(FATAL_ERROR "${label} rejection output was unexpected:\n${output}${error}") + endif () +endfunction() + +expect_fallback("ft4code" "${FT4CODE}" + "THIS FREE TEX.*0\\.0[ ]+Free text" "THIS FREE TEXT IS TOO LONG") +expect_rejected("ft4code" "${FT4CODE}") + +expect_fallback("ft4sim" "${FT4SIM}" + "THIS FREE TEX.*i3.n3:[ ]+0\\.0" "THIS FREE TEXT IS TOO LONG" + 1500 0.0 0.0 0.0 0 99) +expect_rejected("ft4sim" "${FT4SIM}" 1500 0.0 0.0 0.0 0 99) + +execute_process( + COMMAND "${FST4SIM}" "THIS FREE TEXT IS TOO LONG" 60 1500 0.0 0.0 0.0 0 99 F + RESULT_VARIABLE fst4_result + OUTPUT_VARIABLE fst4_output + ERROR_VARIABLE fst4_error +) +if (NOT fst4_result EQUAL 0) + message(FATAL_ERROR "fst4sim fallback failed (${fst4_result}):\n${fst4_output}${fst4_error}") +endif () +if (NOT fst4_output MATCHES "THIS FREE TEX") + message(FATAL_ERROR "fst4sim did not report the canonical fallback message:\n${fst4_output}") +endif () +if (NOT fst4_output MATCHES "iwspr:[ ]+0") + message(FATAL_ERROR "fst4sim did not select FST4 for the fallback message:\n${fst4_output}") +endif () +expect_rejected("fst4sim" "${FST4SIM}" 60 1500 0.0 0.0 0.0 0 99 F) + +expect_fallback("ldpcsim240_101" "${LDPCSIM240_101}" + "Message sent:[ ]+THIS FREE TEX" 1 -1 0 1.0 101 + "THIS FREE TEXT IS TOO LONG") +execute_process( + COMMAND "${LDPCSIM240_101}" 1 -1 0 1.0 101 "HELLO@WORLD" + RESULT_VARIABLE ldpc_rejected_result + OUTPUT_VARIABLE ldpc_rejected_output + ERROR_VARIABLE ldpc_rejected_error +) +if (ldpc_rejected_result EQUAL 0) + message(FATAL_ERROR "ldpcsim240_101 accepted an unrepresentable message:\n${ldpc_rejected_output}${ldpc_rejected_error}") +endif () +if (NOT ldpc_rejected_output MATCHES "Cannot encode message:[ ]+HELLO@WORLD") + message(FATAL_ERROR "ldpcsim240_101 rejection output was unexpected:\n${ldpc_rejected_output}${ldpc_rejected_error}") +endif () + +expect_fallback("msk144code" "${MSK144CODE}" + "THIS FREE TEX.*0\\.0[ ]+Free text" "THIS FREE TEXT IS TOO LONG") +expect_rejected("msk144code" "${MSK144CODE}") diff --git a/tests/unit/packjt77/test_packjt77_concurrent_unpack.f90 b/tests/unit/packjt77/test_packjt77_concurrent_unpack.f90 new file mode 100644 index 00000000..5f72a4b6 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_concurrent_unpack.f90 @@ -0,0 +1,101 @@ +program test_packjt77_concurrent_unpack + + use omp_lib + use packjt77 + implicit none + + integer, parameter :: worker_count=4 + integer, parameter :: phase_count=5 + integer, parameter :: iteration_count=1000 + character(len=37) :: source_messages(worker_count,phase_count) + character(len=77) :: payloads(worker_count,phase_count) + character(len=37) :: expected_messages(worker_count,phase_count) + character(len=37) :: decoded + integer :: failures,i3,iteration,n3,observed_threads,phase,status,worker + logical :: ok + + failures=0 + observed_threads=0 + source_messages(1,1)='A92EE F5PSR -14' + source_messages(2,1)='WM3PEN EA6VQ -09' + source_messages(3,1)='W1FC F5BZB -08' + source_messages(4,1)='N1JFU EA6EE R-07' + source_messages(1,2)='K1ABC/P W9XYZ/P R FN42' + source_messages(2,2)='N0AAA/P N0BBB/P -10' + source_messages(3,2)='W3ABC/P K4XYZ/P RR73' + source_messages(4,2)='F1ABC/P G2XYZ/P 73' + source_messages(1,3)='K1ABC RR73; W9XYZ <KH1/KH7Z> -12' + source_messages(2,3)='N0AAA RR73; N0BBB <KH1/KH7Z> -14' + source_messages(3,3)='W3ABC RR73; K4XYZ <KH1/KH7Z> -16' + source_messages(4,3)='F1ABC RR73; G2XYZ <KH1/KH7Z> -18' + source_messages(1,4)='WA9XYZ KA1ABC R 16A EMA' + source_messages(2,4)='N0AAA N0BBB 1B CT' + source_messages(3,4)='W3ABC K4XYZ R 2C WMA' + source_messages(4,4)='F1ABC G2XYZ 3D DX' + source_messages(1,5)='TU; K1ABC W9XYZ R 529 MA' + source_messages(2,5)='TU; W9XYZ K1ABC R 559 CT' + source_messages(3,5)='TU; W9XYZ G8ABC R 559 0013' + source_messages(4,5)='W9XYZ VE3ABC 559 ON' + + do phase=1,phase_count + do worker=1,worker_count + call pack77(source_messages(worker,phase),i3,n3, & + payloads(worker,phase), & + pack77_options(record_tx_hashes=.false.),status) + if(status.ne.PACK77_STATUS_ENCODED) then + write(*,1000) phase,worker,status,trim(source_messages(worker,phase)) +1000 format('failed to encode phase ',i0,' worker ',i0,' status ',i0,': ',a) + error stop 1 + endif + call unpack77_configured(payloads(worker,phase),0, & + expected_messages(worker,phase),ok, & + unpack77_options(thread_index=worker,record_hashes=.false., & + record_recent_calls=.false.)) + if(.not.ok) then + write(*,1010) phase,worker,trim(source_messages(worker,phase)) +1010 format('failed expected decode for phase ',i0,' worker ',i0,': ',a) + error stop 1 + endif + enddo + enddo + + call omp_set_dynamic(.false.) + call omp_set_num_threads(worker_count) + +!$omp parallel default(none) & +!$omp shared(expected_messages,failures,observed_threads,payloads) & +!$omp private(decoded,iteration,ok,phase,worker) + worker=omp_get_thread_num()+1 +!$omp single + observed_threads=omp_get_num_threads() +!$omp end single + do phase=1,phase_count + do iteration=1,iteration_count +!$omp barrier + call unpack77_configured(payloads(worker,phase),0,decoded,ok, & + unpack77_options(thread_index=worker,record_hashes=.false., & + record_recent_calls=.false.)) + if(.not.ok .or. decoded.ne.expected_messages(worker,phase)) then +!$omp atomic update + failures=failures+1 + endif +!$omp barrier + enddo + enddo +!$omp end parallel + + if(observed_threads.ne.worker_count) then + write(*,1020) worker_count,observed_threads +1020 format('expected ',i0,' OpenMP workers, got ',i0) + error stop 1 + endif + if(failures.ne.0) then + write(*,1030) failures,worker_count*phase_count*iteration_count +1030 format('concurrent unpack mismatches: ',i0,' of ',i0) + error stop 1 + endif + + write(*,1040) worker_count*phase_count*iteration_count,worker_count +1040 format('concurrent unpack decodes passed: ',i0,' across ',i0,' threads') + +end program test_packjt77_concurrent_unpack diff --git a/tests/unit/packjt77/test_packjt77_domain_sweeps.f90 b/tests/unit/packjt77/test_packjt77_domain_sweeps.f90 new file mode 100644 index 00000000..eee14cc9 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_domain_sweeps.f90 @@ -0,0 +1,333 @@ +program test_packjt77_domain_sweeps + use packjt77_grammar + use packjt77_test_helpers, only: assert_true + implicit none + + integer, parameter :: GRID4_TOTAL=18*18*10*10 + integer, parameter :: GRID6_TOTAL=18*18*10*10*24*24 + integer, parameter :: GRID6_WSPR_TOTAL=18*18*10*10*25*25 + integer :: nchecked + + nchecked=0 + call sweep_arrl_sections() + call sweep_rtty_multipliers() + call sweep_rtty_reports() + call sweep_snr_reports() + call sweep_qso_tails() + call sweep_dxpedition_reports() + call sweep_wspr_dbm() + call sweep_field_day_exchanges() + call sweep_wspr_affixes() + call sweep_grid4() + call sweep_grid6_samples() + + print '(a,i0,a)', 'test_packjt77_domain_sweeps: ', nchecked, & + ' values enumerated' + +contains + + subroutine sweep_arrl_sections() + character(len=3) :: section + integer :: i + + call assert_true('ARRL invalid text', & + pack77_arrl_section_index('ZZZ').eq.-1) + do i=1,PACK77_NSEC + section=pack77_arrl_section_name(i) + call assert_true('ARRL inverse', pack77_arrl_section_index(section).eq.i) + if(section(1:1).ge.'A' .and. section(1:1).le.'Z') then + section(1:1)=achar(iachar(section(1:1))+32) + call assert_true('ARRL lowercase reject', & + pack77_arrl_section_index(section).eq.-1) + endif + nchecked=nchecked+1 + enddo + call assert_true('ARRL low index', pack77_arrl_section_name(0).eq.' ') + call assert_true('ARRL high index', & + pack77_arrl_section_name(PACK77_NSEC+1).eq.' ') + end subroutine sweep_arrl_sections + + subroutine sweep_rtty_multipliers() + character(len=3) :: multiplier + integer :: i + + call assert_true('RTTY multiplier invalid text', & + pack77_rtty_multiplier_index('ZZZ').eq.-1) + do i=1,PACK77_NUSCAN + multiplier=pack77_rtty_multiplier_name(i) + call assert_true('RTTY multiplier inverse', & + pack77_rtty_multiplier_index(multiplier).eq.i) + if(multiplier(1:1).ge.'A' .and. multiplier(1:1).le.'Z') then + multiplier(1:1)=achar(iachar(multiplier(1:1))+32) + call assert_true('RTTY multiplier lowercase reject', & + pack77_rtty_multiplier_index(multiplier).eq.-1) + endif + nchecked=nchecked+1 + enddo + call assert_true('RTTY multiplier low index', & + pack77_rtty_multiplier_name(0).eq.' ') + call assert_true('RTTY multiplier high index', & + pack77_rtty_multiplier_name(PACK77_NUSCAN+1).eq.' ') + end subroutine sweep_rtty_multipliers + + subroutine sweep_rtty_reports() + character(len=3) :: report + integer :: i + + do i=0,7 + report=pack77_format_rtty_report(i) + call assert_true('RTTY report inverse', & + pack77_rtty_report_index(report).eq.i) + nchecked=nchecked+1 + enddo + call assert_true('RTTY report low reject', & + pack77_rtty_report_index('519').eq.-1) + call assert_true('RTTY report high reject', & + pack77_rtty_report_index('609').eq.-1) + call assert_true('RTTY report wrong length reject', & + pack77_rtty_report_index('5799').eq.-1) + end subroutine sweep_rtty_reports + + subroutine sweep_snr_reports() + character(len=3) :: report + integer :: isnr,irpt + + do isnr=-50,50 + irpt=pack77_report_index_from_snr(isnr) + call assert_true('SNR report accepts legal value', irpt.ge.0) + call assert_true('SNR report inverse', & + pack77_snr_from_report_index(irpt).eq.isnr) + report=pack77_format_snr_report(isnr) + call assert_true('SNR report format width', len_trim(report).eq.3) + nchecked=nchecked+1 + enddo + do isnr=-75,-51 + call assert_true('SNR report low reject', & + pack77_report_index_from_snr(isnr).eq.-1) + enddo + do isnr=51,75 + call assert_true('SNR report high reject', & + pack77_report_index_from_snr(isnr).eq.-1) + enddo + end subroutine sweep_snr_reports + + subroutine sweep_qso_tails() + character(len=4), parameter :: tails(3)=(/'RRR ','RR73','73 '/) + integer :: i,irpt,nrpt + + do i=1,3 + call assert_true('QSO tail index', pack77_qso_tail_index(tails(i)).eq.i) + irpt=pack77_type12_irpt_from_tail(i) + call assert_true('Type 1/2 tail inverse', & + pack77_tail_from_type12_irpt(irpt).eq.i) + nrpt=pack77_type4_nrpt_from_tail(i) + call assert_true('Type 4 tail inverse', & + pack77_tail_from_type4_nrpt(nrpt).eq.i) + nchecked=nchecked+1 + enddo + call assert_true('QSO tail near miss', pack77_qso_tail_index('RR').eq.0) + call assert_true('Type 1/2 tail low', pack77_tail_from_type12_irpt(1).eq.0) + call assert_true('Type 4 tail high', pack77_tail_from_type4_nrpt(4).eq.0) + end subroutine sweep_qso_tails + + subroutine sweep_dxpedition_reports() + character(len=3) :: report + integer :: isnr,n5 + logical :: ok + + do isnr=-31,33 + call format_signed_report(isnr,report) + call pack77_parse_dxpedition_report(report,n5,ok) + if(isnr.ge.-30 .and. isnr.le.32 .and. mod(isnr,2).eq.0) then + call assert_true('DXpedition report accepts legal value', ok) + call assert_true('DXpedition report inverse', 2*n5-30.eq.isnr) + nchecked=nchecked+1 + else + call assert_true('DXpedition report rejects illegal value', .not.ok) + endif + enddo + end subroutine sweep_dxpedition_reports + + subroutine sweep_wspr_dbm() + character(len=3) :: token + integer :: dbm,idbm,decoded + logical :: ok + + do dbm=-5,65 + write(token,'(i0)') dbm + call pack77_parse_wspr_dbm(token,idbm,ok) + if(ok) then + decoded=nint(idbm*10.0/3.0) + call assert_true('WSPR dBm inverse', decoded.eq.dbm) + nchecked=nchecked+1 + else if(dbm.ge.0 .and. dbm.le.60) then + call assert_true('WSPR dBm legal codebook only', & + nint(nint(0.3*dbm)*10.0/3.0).ne.dbm) + endif + enddo + call pack77_parse_wspr_dbm('03',idbm,ok) + call assert_true('WSPR dBm leading zero reject', .not.ok) + end subroutine sweep_wspr_dbm + + subroutine sweep_field_day_exchanges() + character(len=4) :: token + integer :: ntx,nclass,parsed_ntx,parsed_class + logical :: ok + + do ntx=1,32 + do nclass=0,5 + write(token,'(i0,a1)') ntx, achar(iachar('A')+nclass) + call pack77_parse_field_day_exchange(token,parsed_ntx,parsed_class,ok) + call assert_true('Field Day exchange accepts legal value', ok) + call assert_true('Field Day exchange inverse', & + parsed_ntx.eq.ntx .and. parsed_class.eq.nclass) + nchecked=nchecked+1 + enddo + enddo + call pack77_parse_field_day_exchange('0A',parsed_ntx,parsed_class,ok) + call assert_true('Field Day ntx low reject', .not.ok) + call pack77_parse_field_day_exchange('33A',parsed_ntx,parsed_class,ok) + call assert_true('Field Day ntx high reject', .not.ok) + call pack77_parse_field_day_exchange('1G',parsed_ntx,parsed_class,ok) + call assert_true('Field Day class reject', .not.ok) + call pack77_parse_field_day_exchange('01A',parsed_ntx,parsed_class,ok) + call assert_true('Field Day leading zero reject', .not.ok) + end subroutine sweep_field_day_exchanges + + subroutine sweep_wspr_affixes() + character(len=13) :: token + character(len=3) :: affix,affix_text + integer :: i,npfx,slash_index + logical :: is_prefix,ok + + do i=0,PACK77_WSPR_NZZZ+12959 + call pack77_wspr_affix_text(i,affix,is_prefix,ok) + call assert_true('WSPR affix index renders', ok) + affix_text=adjustl(affix) + if(is_prefix) then + token=trim(affix_text)//'/K1ABC' + slash_index=len_trim(affix_text)+1 + else + token='K1ABC/'//trim(affix_text) + slash_index=6 + endif + npfx=pack77_wspr_affix_index(token,slash_index,len_trim(token),ok) + call assert_true('WSPR affix index inverse', ok .and. npfx.eq.i) + call require_wspr_source(token//' 37', i) + nchecked=nchecked+1 + enddo + + token='ABCD/K1ABC' + npfx=pack77_wspr_affix_index(token,5,len_trim(token),ok) + call assert_true('WSPR four-character prefix reject', .not.ok) + token='K1ABC/ABA' + npfx=pack77_wspr_affix_index(token,6,len_trim(token),ok) + call assert_true('WSPR suffix non-digit third reject', .not.ok) + call require_wspr_source_reject('00/K1ABC 37') + call require_wspr_source_reject('K1ABC/00 37') + end subroutine sweep_wspr_affixes + + subroutine require_wspr_source(msg,want_npfx) + character(len=*), intent(in) :: msg + integer, intent(in) :: want_npfx + type(pack77_wspr_source) :: source + logical :: ok,matched_shape + + call pack77_parse_wspr_source(msg,source,ok,matched_shape) + call assert_true('WSPR source affix parse', & + ok .and. source%npfx.eq.want_npfx) + end subroutine require_wspr_source + + subroutine require_wspr_source_reject(msg) + character(len=*), intent(in) :: msg + type(pack77_wspr_source) :: source + logical :: ok,matched_shape + + call pack77_parse_wspr_source(msg,source,ok,matched_shape) + call assert_true('WSPR source alias reject '//trim(msg), .not.ok) + end subroutine require_wspr_source_reject + + subroutine sweep_grid4() + character(len=4) :: grid4 + integer :: i,narg + logical :: ok + + do i=0,GRID4_TOTAL-1 + narg=i + call to_grid4(narg,grid4,ok) + call assert_true('Grid4 renders', ok) + call assert_true('Grid4 validates', pack77_is_grid4(grid4)) + call assert_true('Grid4 inverse', pack77_grid4_index(grid4).eq.i) + nchecked=nchecked+1 + enddo + narg=-1 + call to_grid4(narg,grid4,ok) + call assert_true('Grid4 low index reject', .not.ok) + narg=GRID4_TOTAL + call to_grid4(narg,grid4,ok) + call assert_true('Grid4 high index reject', .not.ok) + call assert_true('Grid4 short reject', .not.pack77_is_grid4('AA0')) + call assert_true('Grid4 lowercase reject', .not.pack77_is_grid4('aa00')) + end subroutine sweep_grid4 + + subroutine sweep_grid6_samples() + integer, parameter :: NSAMPLE=10000 + integer(kind=8) :: state + integer :: i,n + + call check_grid6_index(0) + call check_grid6_index(GRID6_TOTAL-1) + call check_grid6_index(18*10*10*24*24-1) + call check_grid6_index(18*10*10*24*24) + call check_wspr_grid_index(0) + call check_wspr_grid_index(GRID6_WSPR_TOTAL-1) + call check_wspr_grid_index(18*10*10*25*25-1) + call check_wspr_grid_index(18*10*10*25*25) + + state=123456789_8 + do i=1,NSAMPLE + state=mod(1103515245_8*state+12345_8,2147483648_8) + n=int(mod(state,int(GRID6_TOTAL,kind=8))) + call check_grid6_index(n) + state=mod(1103515245_8*state+12345_8,2147483648_8) + n=int(mod(state,int(GRID6_WSPR_TOTAL,kind=8))) + call check_wspr_grid_index(n) + enddo + end subroutine sweep_grid6_samples + + subroutine check_grid6_index(n) + integer, intent(in) :: n + character(len=6) :: grid6 + integer :: narg + logical :: ok + + narg=n + call to_grid6(narg,grid6,ok) + call assert_true('Grid6 renders', ok) + call assert_true('Grid6 validates', pack77_is_grid6(grid6,.false.)) + call assert_true('Grid6 inverse', pack77_grid6_index(grid6).eq.n) + nchecked=nchecked+1 + end subroutine check_grid6_index + + subroutine check_wspr_grid_index(n) + integer, intent(in) :: n + character(len=6) :: grid6 + integer :: narg + logical :: ok + + narg=n + call to_grid(narg,grid6,ok) + call assert_true('WSPR Grid6 renders', ok) + call assert_true('WSPR Grid6 inverse', pack77_grid6_wspr_index(grid6).eq.n) + nchecked=nchecked+1 + end subroutine check_wspr_grid_index + + subroutine format_signed_report(value,token) + integer, intent(in) :: value + character(len=3), intent(out) :: token + + write(token,'(sp,i3.2)') value + if(value.ge.0 .and. token(1:1).eq.' ') token(1:1)='+' + end subroutine format_signed_report + +end program test_packjt77_domain_sweeps diff --git a/tests/unit/packjt77/test_packjt77_grammar_gate.f90 b/tests/unit/packjt77/test_packjt77_grammar_gate.f90 new file mode 100644 index 00000000..2698baa1 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_grammar_gate.f90 @@ -0,0 +1,73 @@ +program test_packjt77_grammar_gate + + use packjt77_grammar, only: pack77_gate_messages_match + implicit none + + integer :: ntests + character(len=13) :: no_calls(1), staged_calls(2) + + ntests=0 + no_calls='' + staged_calls='' + staged_calls(1)='PJ4/K1ABC' + staged_calls(2)='W3CCX' + + call expect_match('equal messages', & + ' k1abc w9xyz fn42', 'K1ABC W9XYZ FN42', no_calls, 0) + call expect_match('auto-hash canonicalization', & + 'W1AW/P K1ABC 5A CT', '<W1AW/P> K1ABC 5A CT', no_calls, 0) + call expect_match('staged placeholder', & + '<PJ4/K1ABC> W9XYZ RR73', '<...> W9XYZ RR73', staged_calls, 2) + + call expect_no_match('unstaged placeholder', & + '<PJ4/K1ABC> W9XYZ RR73', '<...> W9XYZ RR73', no_calls, 0) + call expect_no_match('CQ bracketed C11 mismatch', & + 'CQ <PJ4/K1ABC>', 'CQ PJ4/K1ABC', no_calls, 0) + call expect_no_match('wrong bracket body', & + '<K1ABC> W9XYZ RR73', '<W9XYZ> W9XYZ RR73', no_calls, 0) + call expect_no_match('different token count', & + 'K1ABC W9XYZ FN42', 'K1ABC W9XYZ', no_calls, 0) + call expect_no_match('changed first call', & + 'K1ABC W9XYZ FN42', 'N1ABC W9XYZ FN42', no_calls, 0) + call expect_no_match('changed second call', & + 'K1ABC W9XYZ FN42', 'K1ABC W9XYA FN42', no_calls, 0) + call expect_no_match('changed report', & + 'K1ABC W9XYZ -12', 'K1ABC W9XYZ -13', no_calls, 0) + call expect_no_match('changed grid', & + 'K1ABC W9XYZ FN42', 'K1ABC W9XYZ FN43', no_calls, 0) + call expect_no_match('changed serial', & + 'K1ABC FN42 37', 'K1ABC FN42 38', no_calls, 0) + + write(*,1000) ntests +1000 format('packjt77 grammar gate tests passed: ',i0) + +contains + + subroutine expect_match(label,input_msg,decoded_msg,staged_calls,nstaged) + character(len=*), intent(in) :: label,input_msg,decoded_msg + character(len=13), intent(in) :: staged_calls(:) + integer, intent(in) :: nstaged + + if(.not.pack77_gate_messages_match(input_msg,decoded_msg,staged_calls, & + nstaged)) then + write(*,1010) trim(label), trim(input_msg), trim(decoded_msg) +1010 format(a,' expected match for input "',a,'" decoded "',a,'"') + error stop 1 + endif + ntests=ntests+1 + end subroutine expect_match + + subroutine expect_no_match(label,input_msg,decoded_msg,staged_calls,nstaged) + character(len=*), intent(in) :: label,input_msg,decoded_msg + character(len=13), intent(in) :: staged_calls(:) + integer, intent(in) :: nstaged + + if(pack77_gate_messages_match(input_msg,decoded_msg,staged_calls,nstaged)) then + write(*,1020) trim(label), trim(input_msg), trim(decoded_msg) +1020 format(a,' expected mismatch for input "',a,'" decoded "',a,'"') + error stop 1 + endif + ntests=ntests+1 + end subroutine expect_no_match + +end program test_packjt77_grammar_gate diff --git a/tests/unit/packjt77/test_packjt77_hash_state.f90 b/tests/unit/packjt77/test_packjt77_hash_state.f90 new file mode 100644 index 00000000..b122ba46 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_hash_state.f90 @@ -0,0 +1,1293 @@ +program test_packjt77_hash_state + + use packjt77 + use packjt77_test_helpers + use ft8_mod1, only : mycall, hiscall, lhound, mybcall, hisbcall, hisgrid4 + implicit none + + integer :: ntests + external :: fillhashvar + external :: ft8apsetvar + external :: genft8 + + ntests=0 + + call expect_standard_hash_save_contract() + call expect_var_hash_save_contract() + call expect_var_hash_save_thread_bounds() + call expect_var_thread_queue_capacity() + call expect_var_thread_rx_accumulation() + call expect_type4_literal_call_staged_until_fill() + call expect_configured_type12_addressee_staged_until_fill() + call expect_legacy_type12_addressee_not_hashed() + call expect_service_unpack_does_not_consume_dx_edge() + call expect_configured_call_clear_blanks_stale_state() + call expect_dxpedition_dxcall_reentry_substitution() + call expect_shared_hash_tables_survive_mode_sync() + call expect_default_pack77_tx_hash_recording() + call expect_pack77_record_tx_hashes_option_suppresses_commit() + call expect_pack77_encode_rejects_dx_macro_by_default() + call expect_pack77_free_text_fallback_rejects_unexpanded_dx_macro() + call expect_pack_unpack_hash_state_matches_pack_only() + call expect_genft8_failure_state() + call expect_dx_macro_option_uses_explicit_base() + call expect_failed_pack77_candidates_do_not_record_hashes() + call expect_ft8apsetvar_does_not_record_template_hashes() + call expect_var_tx_rx_separation() + call expect_mycall_dxcall_substitutions() + call expect_invalid_standard_call_decode_failure() + + call expect_hash_resolution_case( & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, & + 'K1ABC RR73; W9XYZ <...> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 10, 'KH1/KH7Z', 0, '', 0, '') + call expect_hash_resolution_case( & + '<PJ4/K1ABC> W9XYZ RR73', 1, 0, & + '<...> W9XYZ RR73', & + '<PJ4/K1ABC> W9XYZ RR73', & + 22, 'PJ4/K1ABC', 0, '', 0, '') + call expect_hash_resolution_case( & + 'PJ2/W1AW <W7ABC> RR73', 4, 0, & + 'PJ2/W1AW <...> RR73', & + 'PJ2/W1AW <W7ABC> RR73', & + 12, 'W7ABC', 0, '', 0, '') + call expect_hash_resolution_case( & + '<W3CCX> <K1JT/P> 590001 FN20QI', 5, 0, & + '<...> <...> 590001 FN20QI', & + '<W3CCX> <K1JT/P> 590001 FN20QI', & + 12, 'W3CCX', 22, 'K1JT/P', 0, '') + + write(*,1000) ntests +1000 format('packjt77 hash-state tests passed: ',i0) + +contains + + subroutine expect_standard_hash_save_contract() + character(len=13) :: c13 + integer :: n10, n12, n22 + + call clear_all_state('N0AAA','N0BBB') + + c13=' ' + c13='<PJ4/K1ABC>' + call save_hash_call(c13,n10,n12,n22) + call assert_int('standard n10',346,n10) + call assert_int('standard n12',1387,n12) + call assert_int('standard n22',1420834,n22) + call assert_call('standard calls10',calls10(n10),'PJ4/K1ABC') + call assert_call('standard calls12',calls12(n12),'PJ4/K1ABC') + call assert_int('standard nzhash',1,nzhash) + call assert_int('standard ihash22(1)',n22,ihash22(1)) + call assert_call('standard calls22(1)',calls22(1),'PJ4/K1ABC') + + call save_hash_call(c13,n10,n12,n22) + call assert_int('standard duplicate nzhash',1,nzhash) + call assert_call('standard duplicate calls22(1)',calls22(1),'PJ4/K1ABC') + + call clear_all_state('K1ABC','N0BBB') + c13=' ' + c13='K1ABC' + call save_hash_call(c13,n10,n12,n22) + call assert_call('standard mycall calls10 excluded',calls10(n10),'') + call assert_call('standard mycall calls12 excluded',calls12(n12),'') + call assert_call('standard mycall calls22 retained',calls22(1),'K1ABC') + + call clear_all_state('N0AAA','N0BBB') + n10=-99 + n12=-99 + n22=-99 + c13=' ' + c13='<...>' + call save_hash_call(c13,n10,n12,n22) + call assert_int('standard placeholder ignored nzhash',0,nzhash) + call assert_int('standard placeholder ignored n10',-99,n10) + + c13=' ' + c13='K1' + call save_hash_call(c13,n10,n12,n22) + call assert_int('standard short call ignored nzhash',0,nzhash) + + ntests=ntests+1 + end subroutine expect_standard_hash_save_contract + + subroutine expect_var_hash_save_contract() + character(len=13) :: c13 + integer :: n10, n12, n22 + integer :: slot + + call clear_all_state('N0AAA','N0BBB') + + c13=' ' + c13='<PJ4/K1ABC>' + call save_hash_call(c13,n10,n12,n22) + call assert_int('var rx n10',346,n10) + call assert_int('var rx n12',1387,n12) + call assert_int('var rx n22',1420834,n22) + call assert_call('var rx calls10',calls10(n10),'PJ4/K1ABC') + call assert_call('var rx calls12',calls12(n12),'PJ4/K1ABC') + call assert_int('var rx nzhash',1,nzhash) + call assert_int('var rx ihash22(1)',n22,ihash22(1)) + call assert_call('var rx calls22(1)',calls22(1),'PJ4/K1ABC') + + call clear_all_state('N0AAA','N0BBB') + c13=' ' + c13='<PJ4/K1ABC>' + n10=ihashcall('PJ4/K1ABC ',10) + n12=ihashcall('PJ4/K1ABC ',12) + n22=ihashcall('PJ4/K1ABC ',22) + call assert_int('var tx disabled count',0,nzhash) + call assert_call('var tx disabled calls12',calls12(1387),'') + + call save_hash_call(c13,n10,n12,n22) + call assert_int('var tx n10',346,n10) + call assert_int('var tx n12',1387,n12) + call assert_int('var tx n22',1420834,n22) + call assert_call('var tx calls10',calls10(n10),'PJ4/K1ABC') + call assert_call('var tx calls12',calls12(n12),'PJ4/K1ABC') + call assert_int('var tx nzhash',1,nzhash) + call assert_int('var tx ihash22(1)',n22,ihash22(1)) + call assert_call('var tx calls22(1)',calls22(1),'PJ4/K1ABC') + + call clear_all_state('N0AAA','N0BBB') + c13=' ' + c13='<W7ABC>' + call queue_hash_call_for_thread(c13,3) + slot=thread_call_index(3)+1 + call assert_int('var thread 3 count',1,nqueued_calls_by_thread(3)) + call assert_int('var thread 2 count',0,nqueued_calls_by_thread(2)) + call assert_int('var thread 4 count',0,nqueued_calls_by_thread(4)) + call assert_call('var thread 3 call',queued_calls_by_thread(slot),'W7ABC') + call assert_call('var thread call not folded',calls12(ihashcall('W7ABC ',12)),'') + + ntests=ntests+1 + end subroutine expect_var_hash_save_contract + + subroutine expect_var_hash_save_thread_bounds() + character(len=13) :: c13 + + call clear_all_state('N0AAA','N0BBB') + call normalize_call('W7ABC',c13) + + call queue_hash_call_for_thread(c13,0) + call queue_hash_call_for_thread(c13,-1) + call queue_hash_call_for_thread(c13,25) + + call assert_true('var invalid thread indices ignored', & + all(nqueued_calls_by_thread(1:24).eq.0)) + call assert_call('var first queued call untouched',queued_calls_by_thread(1),'') + + ntests=ntests+1 + end subroutine expect_var_hash_save_thread_bounds + + subroutine expect_var_thread_queue_capacity() + character(len=13) :: c13, last_call, overflow_call + integer :: capacity, i, nthr + + call clear_all_state('N0AAA','N0BBB') + + nthr=24 + capacity=thread_call_index(nthr+1)-thread_call_index(nthr) + do i=1,capacity + c13=' ' + write(c13,'("K0",i2.2)') i + call queue_hash_call_for_thread(c13,nthr) + enddo + + overflow_call=' ' + write(overflow_call,'("K0",i2.2)') 99 + call queue_hash_call_for_thread(overflow_call,nthr) + + last_call=' ' + write(last_call,'("K0",i2.2)') capacity + call assert_int('var thread capacity count',capacity, & + nqueued_calls_by_thread(nthr)) + call assert_call('var thread capacity last call', & + queued_calls_by_thread(thread_call_index(nthr)+capacity),last_call) + call assert_true('var thread capacity overflow dropped', & + .not.any(queued_calls_by_thread.eq.overflow_call)) + call assert_int('var thread capacity nzhash before fold',0,nzhash) + + call fillhashvar(nthr,.true.) + + call assert_int('var thread capacity nzhash after fold',capacity,nzhash) + call assert_true('var thread capacity last hash after fold', & + shared_hash22_contains(last_call)) + call assert_true('var thread capacity overflow absent after fold', & + .not.shared_hash22_contains(overflow_call)) + + ntests=ntests+1 + end subroutine expect_var_thread_queue_capacity + + subroutine expect_var_thread_rx_accumulation() + character(len=13) :: rx_call, later_thread_call + integer :: n10, n12, n22 + integer :: later_n10, later_n12 + + call clear_all_state('N0AAA','N0BBB') + + call normalize_call('W7ABC',rx_call) + call normalize_call('K9XYZ',later_thread_call) + + ! queue_hash_call_for_thread queues RX hashes per thread until fillhashvar folds them. + call queue_hash_call_for_thread(rx_call,3) + call queue_hash_call_for_thread(later_thread_call,7) + + n10=ihashcall(rx_call,10) + n12=ihashcall(rx_call,12) + n22=ihashcall(rx_call,22) + later_n10=ihashcall(later_thread_call,10) + later_n12=ihashcall(later_thread_call,12) + + call assert_int('var thread 3 count before fold',1,nqueued_calls_by_thread(3)) + call assert_int('var thread 7 count before fold',1,nqueued_calls_by_thread(7)) + call assert_int('var thread 2 count before fold',0,nqueued_calls_by_thread(2)) + call assert_int('var thread 4 count before fold',0,nqueued_calls_by_thread(4)) + call assert_call('var thread 3 first call',queued_calls_by_thread(thread_call_index(3)+1), & + 'W7ABC') + call assert_call('var thread 7 first call',queued_calls_by_thread(thread_call_index(7)+1), & + 'K9XYZ') + call assert_call('var thread 2 first slot untouched', & + queued_calls_by_thread(thread_call_index(2)+1),'') + call assert_call('var thread 4 first slot untouched', & + queued_calls_by_thread(thread_call_index(4)+1),'') + call assert_call('var rx calls10 before fold',calls10(n10),'') + call assert_call('var rx calls12 before fold',calls12(n12),'') + call assert_int('var rx nzhash before fold',0,nzhash) + + call fillhashvar(3,.true.) + + call assert_call('var rx calls10 after fold',calls10(n10),'W7ABC') + call assert_call('var rx calls12 after fold',calls12(n12),'W7ABC') + call assert_int('var rx nzhash after fold',1,nzhash) + call assert_int('var rx ihash22 after fold',n22,ihash22(1)) + call assert_call('var rx calls22 after fold',calls22(1),'W7ABC') + call assert_call('var later thread not folded calls10',calls10(later_n10),'') + call assert_call('var later thread not folded calls12',calls12(later_n12),'') + call assert_int('var thread 3 count after fold',1,nqueued_calls_by_thread(3)) + call assert_int('var thread 7 count after fold',1,nqueued_calls_by_thread(7)) + call assert_call('var thread 7 call retained after fold', & + queued_calls_by_thread(thread_call_index(7)+1),'K9XYZ') + + ntests=ntests+1 + end subroutine expect_var_thread_rx_accumulation + + subroutine expect_type4_literal_call_staged_until_fill() + character(len=77) :: c77 + character(len=37) :: decoded + character(len=13) :: literal_call + integer :: n10, n12 + logical :: ok + + call pack_and_assert_type('PJ2/W1AW <W7ABC> RR73',4,0,c77) + call clear_all_state('N0AAA','N0BBB') + call normalize_call('PJ2/W1AW',literal_call) + n10=ihashcall(literal_call,10) + n12=ihashcall(literal_call,12) + + call unpack_var_current_state_thread(c77,1,3,decoded,ok) + + call assert_decode('type 4 staged literal decode', & + 'PJ2/W1AW <W7ABC> RR73','PJ2/W1AW <...> RR73',decoded,ok) + call assert_int('type 4 thread 3 queued count',1,nqueued_calls_by_thread(3)) + call assert_call('type 4 thread 3 queued call', & + queued_calls_by_thread(thread_call_index(3)+1),'PJ2/W1AW') + call assert_int('type 4 thread 3 queued recent count',1, & + nqueued_recent_calls_by_thread(3)) + call assert_call('type 4 thread 3 queued recent call', & + queued_recent_calls_by_thread(thread_call_index(3)+1),'PJ2/W1AW') + call assert_call('type 4 calls10 before fill',calls10(n10),'') + call assert_call('type 4 calls12 before fill',calls12(n12),'') + call assert_call('type 4 recent before fill',recent_calls(1),'') + + call fillhashvar(3,.true.) + + call assert_call('type 4 calls10 after fill',calls10(n10),'PJ2/W1AW') + call assert_call('type 4 calls12 after fill',calls12(n12),'PJ2/W1AW') + call assert_true('type 4 calls22 after fill',shared_hash22_contains(literal_call)) + call assert_call('type 4 recent after fill',recent_calls(1),'PJ2/W1AW') + + ntests=ntests+1 + end subroutine expect_type4_literal_call_staged_until_fill + + subroutine expect_configured_type12_addressee_staged_until_fill() + character(len=77) :: c77 + character(len=37) :: decoded + character(len=13) :: call1, call2 + logical :: ok + + call pack_and_assert_type('W9XYZ K1ABC FN42',1,0,c77) + call clear_all_state('N0AAA','N0BBB') + call normalize_call('W9XYZ',call1) + call normalize_call('K1ABC',call2) + + call unpack_var_current_state_thread(c77,1,3,decoded,ok) + + call assert_decode('type 1 staged addressee decode', & + 'W9XYZ K1ABC FN42','W9XYZ K1ABC FN42',decoded,ok) + call assert_int('type 1 thread 3 queued hash count',2, & + nqueued_calls_by_thread(3)) + call assert_call('type 1 thread 3 queued first call', & + queued_calls_by_thread(thread_call_index(3)+1),'W9XYZ') + call assert_call('type 1 thread 3 queued second call', & + queued_calls_by_thread(thread_call_index(3)+2),'K1ABC') + call assert_true('type 1 addressee hash absent before fill', & + .not.shared_hash22_contains(call1)) + + call fillhashvar(3,.true.) + + call assert_true('type 1 addressee hash after fill', & + shared_hash22_contains(call1)) + call assert_true('type 1 second call hash after fill', & + shared_hash22_contains(call2)) + + ntests=ntests+1 + end subroutine expect_configured_type12_addressee_staged_until_fill + + subroutine expect_legacy_type12_addressee_not_hashed() + character(len=77) :: c77 + character(len=37) :: decoded + character(len=13) :: call1, call2 + integer :: n10a, n12a, n10b, n12b + logical :: ok + + call pack_and_assert_type('W9XYZ K1ABC FN42',1,0,c77) + call clear_all_state('N0AAA','N0BBB') + call normalize_call('W9XYZ',call1) + call normalize_call('K1ABC',call2) + n10a=ihashcall(call1,10) + n12a=ihashcall(call1,12) + n10b=ihashcall(call2,10) + n12b=ihashcall(call2,12) + + call unpack_standard_current_state(c77,1,decoded,ok) + + call assert_decode('legacy type 1 addressee decode', & + 'W9XYZ K1ABC FN42','W9XYZ K1ABC FN42',decoded,ok) + call assert_call('legacy type 1 recent sender',recent_calls(1),'K1ABC') + call assert_call('legacy type 1 recent addressee',recent_calls(2),'W9XYZ') + call assert_call('legacy type 1 addressee calls10',calls10(n10a),'') + call assert_call('legacy type 1 addressee calls12',calls12(n12a),'') + call assert_true('legacy type 1 addressee hash22 absent', & + .not.shared_hash22_contains(call1)) + call assert_call('legacy type 1 sender calls10',calls10(n10b),'K1ABC') + call assert_call('legacy type 1 sender calls12',calls12(n12b),'K1ABC') + call assert_true('legacy type 1 sender hash22 present', & + shared_hash22_contains(call2)) + + ntests=ntests+1 + end subroutine expect_legacy_type12_addressee_not_hashed + + subroutine expect_service_unpack_does_not_consume_dx_edge() + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok + + call pack_and_assert_type('K1ABC W9XYZ RR73',1,0,c77) + call clear_all_state('N0AAA','') + + mycall='N0AAA' + hiscall='KH1/KH7Z' + dxcall13='KH1/KH7Z ' + dxcall13_configured_prev=' ' + dxcall13_configured=' ' + dxcall13_configured_set=.false. + hashdx10_configured=-1 + + decoded=' ' + ok=.false. + call unpack77_configured(c77,1,decoded,ok, & + unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) + + call assert_true('service unpack leaves recent queue empty', & + all(nqueued_recent_calls_by_thread(1:24).eq.0)) + call assert_call('service unpack leaves recent calls empty',recent_calls(1),'') + + call fillhashvar(1,.false.) + + call assert_int('service unpack leaves dx edge queued count',1, & + nqueued_calls_by_thread(1)) + call assert_call('service unpack leaves dx edge queued call', & + queued_calls_by_thread(thread_call_index(1)+1),'KH1/KH7Z') + call assert_true('service unpack dx configured set',dxcall13_configured_set) + call assert_call('service unpack dx configured',dxcall13_configured,'KH1/KH7Z') + call assert_call('service unpack dx configured prev',dxcall13_configured_prev, & + 'KH1/KH7Z') + call assert_int('service unpack dx configured hash', & + ihashcall(dxcall13_configured,10),hashdx10_configured) + + ntests=ntests+1 + end subroutine expect_service_unpack_does_not_consume_dx_edge + + subroutine expect_configured_call_clear_blanks_stale_state() + integer :: old_hash + + call clear_all_state('N0AAA','KH1/KH7Z') + mycall='N0AAA' + hiscall='KH1/KH7Z' + call fillhashvar(1,.false.) + + call assert_true('configured clear seeded dx',dxcall13_configured_set) + call assert_call('configured clear seeded dx call',dxcall13_configured, & + 'KH1/KH7Z') + old_hash=hashdx10_configured + + hiscall='' + call fillhashvar(1,.false.) + + call assert_true('configured clear dx flag',.not.dxcall13_configured_set) + call assert_call('configured clear dx configured blank',dxcall13_configured,'') + call assert_call('configured clear dx previous blank',dxcall13_configured_prev,'') + call assert_int('configured clear dx hash reset',-1,hashdx10_configured) + call assert_int('configured clear dx queue count',0,nqueued_calls_by_thread(1)) + call assert_true('configured clear changed dx hash',hashdx10_configured.ne.old_hash) + + call clear_all_state('KH1/KH7Z','N0BBB') + mycall='KH1/KH7Z' + hiscall='N0BBB' + call fillhashvar(1,.false.) + + call assert_true('configured clear seeded mycall',mycall13_configured_set) + call assert_call('configured clear seeded mycall value',mycall13_configured, & + 'KH1/KH7Z') + + mycall='' + call fillhashvar(1,.false.) + + call assert_true('configured clear mycall flag',.not.mycall13_configured_set) + call assert_call('configured clear mycall configured blank', & + mycall13_configured,'') + call assert_call('configured clear mycall previous blank', & + mycall13_configured_prev,'') + call assert_int('configured clear mycall hash10 reset',-1,hashmy10_configured) + call assert_int('configured clear mycall hash12 reset',-1,hashmy12_configured) + call assert_int('configured clear mycall hash22 reset',-1,hashmy22_configured) + + ntests=ntests+1 + end subroutine expect_configured_call_clear_blanks_stale_state + + subroutine expect_dxpedition_dxcall_reentry_substitution() + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok + + call pack_and_assert_type('K1ABC RR73; W9XYZ <KH1/KH7Z> -12',0,1,c77) + call clear_all_state('N0AAA','') + + mycall='N0AAA' + hiscall='KH1/KH7Z' + call fillhashvar(1,.false.) + call unpack_var_current_state(c77,1,decoded,ok) + call assert_decode('DXpedition dx configured first entry', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded,ok) + + hiscall='' + call fillhashvar(1,.false.) + call assert_true('DXpedition dx cleared',.not.dxcall13_configured_set) + + hiscall='KH1/KH7Z' + call fillhashvar(1,.false.) + call unpack_var_current_state(c77,1,decoded,ok) + call assert_decode('DXpedition dx configured re-entry', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded,ok) + + ntests=ntests+1 + end subroutine expect_dxpedition_dxcall_reentry_substitution + + subroutine expect_shared_hash_tables_survive_mode_sync() + character(len=13) :: c13 + integer :: n10, n12, n22 + + call clear_all_state('N0AAA','KH1/KH7Z') + + call normalize_call('PJ4/K1ABC',c13) + call save_hash_call(c13,n10,n12,n22) + call assert_call('persistent hash calls10 seeded',calls10(n10),'PJ4/K1ABC') + call assert_true('persistent hash calls22 seeded',shared_hash22_contains(c13)) + + mycall='W1AW' + hiscall='W9XYZ' + call fillhashvar(1,.false.) + + call assert_call('persistent hash calls10 after mode sync', & + calls10(n10),'PJ4/K1ABC') + call assert_call('persistent hash calls12 after mode sync', & + calls12(n12),'PJ4/K1ABC') + call assert_true('persistent hash calls22 after mode sync', & + shared_hash22_contains(c13)) + + ntests=ntests+1 + end subroutine expect_shared_hash_tables_survive_mode_sync + + subroutine expect_default_pack77_tx_hash_recording() + character(len=37) :: input, packed_input, decoded + character(len=77) :: c77 + character(len=13) :: call1, call2, call12, call22, forced_call + integer :: n10a, n12a, n10b, n12b, got_i3, got_n3 + integer :: forced_n10, forced_n12, forced_n22 + logical :: ok + + input='K1ABC W9XYZ RR73' + packed_input=' ' + packed_input=input + call normalize_call('K1ABC',call1) + call normalize_call('W9XYZ',call2) + n10a=ihashcall(call1,10) + n12a=ihashcall(call1,12) + n10b=ihashcall(call2,10) + n12b=ihashcall(call2,12) + + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('default Type 1 tx hashes',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + end block + call assert_message_type('default Type 1 tx hashes',input,1,0,got_i3,got_n3) + call assert_call('default Type 1 calls10 first call',calls10(n10a),'K1ABC') + call assert_call('default Type 1 calls12 first call',calls12(n12a),'K1ABC') + call assert_call('default Type 1 calls10 second call',calls10(n10b),'W9XYZ') + call assert_call('default Type 1 calls12 second call',calls12(n12b),'W9XYZ') + call assert_int('default Type 1 nzhash after pack',2,nzhash) + call assert_true('default Type 1 hash22 first call',shared_hash22_contains(call1)) + call assert_true('default Type 1 hash22 second call',shared_hash22_contains(call2)) + + input='PJ2/W1AW <W7ABC> RR73' + packed_input=' ' + packed_input=input + call normalize_call('W7ABC',call12) + n10a=ihashcall(call12,10) + n12a=ihashcall(call12,12) + + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('default Type 4 tx hashes',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + end block + call assert_message_type('default Type 4 tx hashes',input,4,0,got_i3,got_n3) + call assert_call('default Type 4 calls10 hashed call',calls10(n10a),'W7ABC') + call assert_call('default Type 4 calls12 hashed call',calls12(n12a),'W7ABC') + call assert_int('default Type 4 nzhash after pack',1,nzhash) + call assert_true('default Type 4 hash22 hashed call',shared_hash22_contains(call12)) + + input='<W3CCX> <K1JT/P> 590001 FN20QI' + packed_input=' ' + packed_input=input + call normalize_call('W3CCX',call12) + call normalize_call('K1JT/P',call22) + n10a=ihashcall(call12,10) + n12a=ihashcall(call12,12) + n10b=ihashcall(call22,10) + n12b=ihashcall(call22,12) + + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('default pack77 tx hashes',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('default pack77 tx hashes',input,5,0,got_i3,got_n3) + call assert_call('default tx calls10 first hashed call',calls10(n10a), & + 'W3CCX') + call assert_call('default tx calls12 first hashed call',calls12(n12a), & + 'W3CCX') + call assert_call('default tx calls10 second hashed call',calls10(n10b), & + 'K1JT/P') + call assert_call('default tx calls12 second hashed call',calls12(n12b), & + 'K1JT/P') + call assert_int('default tx nzhash after pack',2,nzhash) + call assert_true('default tx hash22 second hashed call', & + shared_hash22_contains(call22)) + + decoded=' ' + ok=.false. + call unpack77(c77,0,decoded,ok) + call assert_decode('default tx decode uses recorded hashes',input,input,decoded,ok) + + input='<PJ4/K1ABC> FK52AB' + packed_input=' ' + packed_input=input + call normalize_call('PJ4/K1ABC',forced_call) + forced_n10=ihashcall(forced_call,10) + forced_n12=ihashcall(forced_call,12) + forced_n22=ihashcall(forced_call,22) + + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input,pack77_options(prefer_wspr_50bit=.true.)) + call assert_pack77_result('prefer WSPR tx hashes',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('prefer WSPR tx hashes',input,0,6,got_i3,got_n3) + call assert_call('prefer WSPR calls10',calls10(forced_n10),'PJ4/K1ABC') + call assert_call('prefer WSPR calls12',calls12(forced_n12),'PJ4/K1ABC') + call assert_int('prefer WSPR hash22',forced_n22,ihash22(1)) + call assert_call('prefer WSPR calls22',calls22(1),'PJ4/K1ABC') + + decoded=' ' + ok=.false. + call unpack77(c77,0,decoded,ok) + call assert_decode('prefer WSPR decode uses recorded hashes',input,input,decoded,ok) + + ntests=ntests+1 + end subroutine expect_default_pack77_tx_hash_recording + + subroutine expect_pack77_record_tx_hashes_option_suppresses_commit() + character(len=37) :: input, packed_input + + input='K1ABC W9XYZ RR73' + call assert_record_tx_disabled_same_payload(input,1,0) + + input='PJ2/W1AW <W7ABC> RR73' + call assert_record_tx_disabled_same_payload(input,4,0) + + input='<W3CCX> <K1JT/P> 590001 FN20QI' + call assert_record_tx_disabled_same_payload(input,5,0) + + input='<PJ4/K1ABC> FK52AB' + packed_input=' ' + packed_input=input + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: default_encoded, disabled_encoded + default_encoded=pack77_result_from_api(packed_input,pack77_options(prefer_wspr_50bit=.true.)) + call assert_pack77_result('default preferred WSPR payload',packed_input, & + default_encoded) + call clear_all_state('N0AAA','N0BBB') + disabled_encoded=pack77_result_from_api(packed_input, & + pack77_options(prefer_wspr_50bit=.true.,record_tx_hashes=.false.)) + call assert_pack77_result('disabled preferred WSPR payload',packed_input, & + disabled_encoded) + call assert_text_equal('disabled preferred WSPR c77',default_encoded%c77, & + disabled_encoded%c77) + call assert_message_type('disabled preferred WSPR type',input,0,6, & + disabled_encoded%i3,disabled_encoded%n3) + end block + call assert_shared_hash_tables_empty('disabled preferred WSPR hashes') + + ntests=ntests+1 + end subroutine expect_pack77_record_tx_hashes_option_suppresses_commit + + subroutine expect_pack77_encode_rejects_dx_macro_by_default() + character(len=37) :: shorthand + + shorthand='$DX K1ABC FN42' + call clear_all_state('N0AAA','N0BBB') + + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(shorthand) + call assert_true('pure Pack77 encode rejects DX macro', & + .not.encoded%encoded) + end block + + ntests=ntests+1 + end subroutine expect_pack77_encode_rejects_dx_macro_by_default + + subroutine expect_pack77_free_text_fallback_rejects_unexpanded_dx_macro() + character(len=37) :: input, direct + + direct='W9XYZ K1ABC FN42' + call clear_all_state('N0AAA','N0BBB') + + input='$DX K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects DX macro', & + .not.encoded%encoded) + end block + + input='$dx K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects lowercase DX macro', & + .not.encoded%encoded) + end block + + input=' $DX K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects leading-space DX macro', & + .not.encoded%encoded) + end block + + input='$DXCALL K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects DXCALL macro', & + .not.encoded%encoded) + end block + + input='$dxcall K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects lowercase DXCALL macro', & + .not.encoded%encoded) + end block + + input='$DXFOO K1ABC FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_true('Pack77 free-text fallback rejects invalid DX prefix', & + .not.encoded%encoded) + call assert_true('Pack77 free-text fallback invalid DX prefix status', & + encoded%status.eq.PACK77_STATUS_FREE_TEXT_INVALID) + end block + + input='$DX K1ABC FN42' + block + type(pack77_result) :: shorthand_encoded, direct_encoded + shorthand_encoded=pack77_result_from_api(input, & + pack77_options(expand_dx_macro=.true.,dx_macro_base='W9XYZ')) + direct_encoded=pack77_result_from_api(direct) + call assert_pack77_result('Pack77 free-text fallback explicit DX expansion',input, & + shorthand_encoded) + call assert_text_equal('Pack77 free-text fallback explicit DX expansion c77', & + direct_encoded%c77,shorthand_encoded%c77) + end block + + ntests=ntests+1 + end subroutine expect_pack77_free_text_fallback_rejects_unexpanded_dx_macro + + subroutine expect_pack_unpack_hash_state_matches_pack_only() + call assert_pack_unpack_hash_state_matches_pack_only( & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12') + call assert_pack_unpack_hash_state_matches_pack_only('W1AW/P K1A 1A CT') + call assert_pack_unpack_hash_state_matches_pack_only('PJ2/W1AW <W7ABC> RR73') + call assert_pack_unpack_hash_state_matches_pack_only( & + '<W3CCX> <K1JT/P> 590001 FN20QI') + + ntests=ntests+1 + end subroutine expect_pack_unpack_hash_state_matches_pack_only + + subroutine expect_genft8_failure_state() + character(len=37) :: input, msgsent + integer*1 :: msgbits(77) + integer :: itone(79) + integer :: i3,n3 + + input='$DX K1ABC FN42' + call genft8(input,i3,n3,msgsent,msgbits,itone) + + call assert_int('genft8 failure i3',-1,i3) + call assert_int('genft8 failure n3',-1,n3) + call assert_text_equal('genft8 failure msgsent', & + '*** bad message *** ',msgsent) + call assert_true('genft8 failure msgbits',all(msgbits.eq.0)) + call assert_true('genft8 failure itone',all(itone.eq.0)) + + ntests=ntests+1 + end subroutine expect_genft8_failure_state + + subroutine expect_dx_macro_option_uses_explicit_base() + character(len=37) :: shorthand, direct, decoded + logical :: ok + + shorthand='$DX K1ABC FN42' + direct='W9XYZ K1ABC FN42' + call clear_all_state('N0AAA','N0BBB') + + block + type(pack77_result) :: shorthand_encoded, direct_encoded + shorthand_encoded=pack77_result_from_api(shorthand, & + pack77_options(expand_dx_macro=.true.,dx_macro_base='W9XYZ')) + direct_encoded=pack77_result_from_api(direct) + call assert_pack77_result('DX rewrite shorthand',shorthand, & + shorthand_encoded) + call assert_pack77_result('DX rewrite direct',direct,direct_encoded) + call assert_message_type('DX rewrite type',shorthand,1,0, & + shorthand_encoded%i3,shorthand_encoded%n3) + call assert_text_equal('DX rewrite c77',direct_encoded%c77, & + shorthand_encoded%c77) + + decoded=' ' + ok=.false. + call unpack77(shorthand_encoded%c77,0,decoded,ok) + call assert_decode('DX rewrite decode',shorthand,direct,decoded,ok) + end block + + shorthand='$DXCALL K1ABC FN42' + block + type(pack77_result) :: shorthand_encoded, direct_encoded + shorthand_encoded=pack77_result_from_api(shorthand, & + pack77_options(expand_dx_macro=.true.,dx_macro_base='W9XYZ')) + direct_encoded=pack77_result_from_api(direct) + call assert_pack77_result('DXCALL rewrite shorthand',shorthand, & + shorthand_encoded) + call assert_text_equal('DXCALL rewrite c77',direct_encoded%c77, & + shorthand_encoded%c77) + end block + + shorthand='$dx K1ABC FN42' + block + type(pack77_result) :: shorthand_encoded, direct_encoded + shorthand_encoded=pack77_result_from_api(shorthand, & + pack77_options(expand_dx_macro=.true.,dx_macro_base='W9XYZ')) + direct_encoded=pack77_result_from_api(direct) + call assert_pack77_result('lowercase DX rewrite shorthand',shorthand, & + shorthand_encoded) + call assert_text_equal('lowercase DX rewrite c77',direct_encoded%c77, & + shorthand_encoded%c77) + end block + + shorthand=' $DX K1ABC FN42' + block + type(pack77_result) :: shorthand_encoded, direct_encoded + shorthand_encoded=pack77_result_from_api(shorthand, & + pack77_options(expand_dx_macro=.true.,dx_macro_base='W9XYZ')) + direct_encoded=pack77_result_from_api(direct) + call assert_pack77_result('DX rewrite leading whitespace',shorthand, & + shorthand_encoded) + call assert_text_equal('DX rewrite leading whitespace c77', & + direct_encoded%c77,shorthand_encoded%c77) + end block + + ntests=ntests+1 + end subroutine expect_dx_macro_option_uses_explicit_base + + subroutine expect_failed_pack77_candidates_do_not_record_hashes() + call assert_rejected_candidate_does_not_record('W9XYZ K1ABC R BAD MA') + call assert_rejected_candidate_does_not_record('<PJ2/W1AW> K1ABC BOGUS') + call assert_rejected_candidate_does_not_record('CQ PJ2/W1AW BOGUS') + call assert_rejected_candidate_does_not_record('<PJ4/K1ABC>X W9XYZ RR73') + call assert_rejected_candidate_does_not_record( & + 'K1ABC RR73; W9XYZ <KH1/KH7Z>X -12') + call assert_rejected_candidate_does_not_record( & + '<W3CCX <K1JT/P> 590001 FN20QI') + call assert_rejected_candidate_does_not_record( & + '<W3CCX> <K1JT/P 590001 FN20QI') + + ntests=ntests+1 + end subroutine expect_failed_pack77_candidates_do_not_record_hashes + + subroutine expect_ft8apsetvar_does_not_record_template_hashes() + logical(1) :: lmycallstd, lhiscallstd + + call clear_all_state('N0AAA','PJ2/W1AW') + mycall='N0AAA ' + hiscall='PJ2/W1AW ' + mybcall='N0AAA ' + hisbcall='PJ2/W1AW ' + hisgrid4=' ' + lhound=.false. + lmycallstd=.true. + lhiscallstd=.false. + + call ft8apsetvar(lmycallstd,lhiscallstd,1) + call assert_shared_hash_tables_empty('ft8apsetvar template hashes') + + ntests=ntests+1 + end subroutine expect_ft8apsetvar_does_not_record_template_hashes + + subroutine expect_var_tx_rx_separation() + character(len=37) :: input + character(len=77) :: c77 + character(len=37) :: decoded + character(len=13) :: call12, call22 + integer :: n10a, n12a, n10b, n12b + logical :: ok + + input='<W3CCX> <K1JT/P> 590001 FN20QI' + call normalize_call('W3CCX',call12) + call normalize_call('K1JT/P',call22) + n10a=ihashcall(call12,10) + n12a=ihashcall(call12,12) + n10b=ihashcall(call22,10) + n12b=ihashcall(call22,12) + + call clear_all_state('N0AAA','N0BBB') + ! record_tx_hashes writes accepted pack hashes into the shared lookup table. + call pack_var_current_state(input,5,0,1,c77) + + call assert_call('var tx calls10 first hashed call',calls10(n10a), & + 'W3CCX') + call assert_call('var tx calls12 first hashed call',calls12(n12a), & + 'W3CCX') + call assert_call('var tx calls10 second hashed call',calls10(n10b), & + 'K1JT/P') + call assert_call('var tx calls12 second hashed call',calls12(n12b), & + 'K1JT/P') + call assert_int('var tx nzhash after pack',2,nzhash) + call assert_true('var tx hash22 second hashed call', & + shared_hash22_contains(call22)) + + call unpack_var_current_state_thread(c77,1,26,decoded,ok) + call assert_decode('var tx-state decode',input,input,decoded,ok) + call unpack_var_current_state_thread(c77,1,1,decoded,ok) + call assert_decode('var shared-state decodes tx hashes',input,input,decoded,ok) + + call clear_all_state('N0AAA','N0BBB') + call pack_var_current_state(input,5,0,0,c77) + + call assert_int('var tx nzhash disabled',0,nzhash) + call assert_call('var tx disabled calls10 first',calls10(n10a),'') + call assert_call('var tx disabled calls12 first',calls12(n12a),'') + call assert_call('var tx disabled calls10 second',calls10(n10b),'') + call assert_call('var tx disabled calls12 second',calls12(n12b),'') + call assert_true('var tx disabled hash22 empty', & + .not.shared_hash22_contains(call22)) + + call unpack_var_current_state_thread(c77,1,26,decoded,ok) + call assert_decode('var tx-state disabled decode',input, & + '<...> <...> 590001 FN20QI',decoded,ok) + + ntests=ntests+1 + end subroutine expect_var_tx_rx_separation + + subroutine expect_mycall_dxcall_substitutions() + character(len=77) :: c77 + character(len=37) :: decoded_standard, decoded_var + logical :: ok_standard, ok_var + + ! These decode paths substitute local my/dx calls without hash-table priming. + call pack_and_assert_type('<PJ4/K1ABC> W9XYZ RR73',1,0,c77) + call clear_all_state('PJ4/K1ABC','N0BBB') + call unpack_standard_current_state(c77,1,decoded_standard,ok_standard) + call clear_all_state('PJ4/K1ABC','N0BBB') + call unpack_var_current_state(c77,1,decoded_var,ok_var) + call assert_decode('standard Type 1 mycall hash22','<PJ4/K1ABC> W9XYZ RR73', & + '<PJ4/K1ABC> W9XYZ RR73',decoded_standard,ok_standard) + call assert_decode('var Type 1 mycall hash22','<PJ4/K1ABC> W9XYZ RR73', & + '<PJ4/K1ABC> W9XYZ RR73',decoded_var,ok_var) + + call pack_and_assert_type('K1ABC RR73; W9XYZ <KH1/KH7Z> -12',0,1,c77) + call clear_all_state('N0AAA','KH1/KH7Z') + call unpack_standard_current_state(c77,1,decoded_standard,ok_standard) + call clear_all_state('N0AAA','KH1/KH7Z') + call unpack_var_current_state(c77,1,decoded_var,ok_var) + call assert_decode('standard DXpedition dxcall hash10', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded_standard,ok_standard) + call assert_decode('var DXpedition dxcall hash10', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded_var,ok_var) + + call clear_all_state('KH1/KH7Z','N0BBB') + call unpack_standard_current_state(c77,0,decoded_standard,ok_standard) + call clear_all_state('KH1/KH7Z','N0BBB') + call unpack_var_current_state(c77,0,decoded_var,ok_var) + call assert_decode('standard DXpedition mycall hash10', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded_standard,ok_standard) + call assert_decode('var DXpedition mycall hash10', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12', & + 'K1ABC RR73; W9XYZ <KH1/KH7Z> -12',decoded_var,ok_var) + + call pack_and_assert_type('<W3CCX> <K1JT/P> 590001 FN20QI',5,0,c77) + call clear_all_state('W3CCX','N0BBB') + call unpack_standard_current_state(c77,1,decoded_standard,ok_standard) + call clear_all_state('W3CCX','N0BBB') + call unpack_var_current_state(c77,1,decoded_var,ok_var) + call assert_decode('standard Type 5 mycall hash12', & + '<W3CCX> <K1JT/P> 590001 FN20QI', & + '<W3CCX> <...> 590001 FN20QI',decoded_standard,ok_standard) + call assert_decode('var Type 5 mycall hash12', & + '<W3CCX> <K1JT/P> 590001 FN20QI', & + '<W3CCX> <...> 590001 FN20QI',decoded_var,ok_var) + + ntests=ntests+1 + end subroutine expect_mycall_dxcall_substitutions + + subroutine expect_invalid_standard_call_decode_failure() + character(len=13) :: decoded_standard, decoded_var + integer, parameter :: n28_q1abc = 11395945 + logical :: ok_standard, ok_var + + call unpack28(n28_q1abc,decoded_standard,ok_standard) + call unpack28(n28_q1abc,decoded_var,ok_var) + + call assert_true('standard invalid raw call fails',.not.ok_standard) + call assert_true('var invalid raw call fails',.not.ok_var) + + ntests=ntests+1 + end subroutine expect_invalid_standard_call_decode_failure + + subroutine expect_hash_resolution_case(input,want_i3,want_n3,blank_expected, & + primed_expected,width1,call1,width2,call2,width3,call3) + character(len=*), intent(in) :: input, blank_expected, primed_expected + character(len=*), intent(in) :: call1, call2, call3 + integer, intent(in) :: want_i3, want_n3, width1, width2, width3 + character(len=77) :: c77 + character(len=37) :: decoded_standard, decoded_var + logical :: ok_standard, ok_var + + call pack_and_assert_type(input,want_i3,want_n3,c77) + + call decode_standard(c77,1,decoded_standard,ok_standard) + call decode_var(c77,1,decoded_var,ok_var) + call assert_decode('standard blank',input,blank_expected,decoded_standard,ok_standard) + call assert_decode('var blank',input,blank_expected,decoded_var,ok_var) + call assert_text_equal('blank standard/var',decoded_standard,decoded_var) + + call prime_hash_width(width1,call1,'standard') + call prime_hash_width(width2,call2,'standard') + call prime_hash_width(width3,call3,'standard') + call unpack_standard_current_state(c77,1,decoded_standard,ok_standard) + + call prime_hash_width(width1,call1,'var') + call prime_hash_width(width2,call2,'var') + call prime_hash_width(width3,call3,'var') + call unpack_var_current_state(c77,1,decoded_var,ok_var) + + call assert_decode('standard primed',input,primed_expected,decoded_standard,ok_standard) + call assert_decode('var primed',input,primed_expected,decoded_var,ok_var) + call assert_text_equal('primed standard/var',decoded_standard,decoded_var) + + ntests=ntests+1 + end subroutine expect_hash_resolution_case + + subroutine pack_and_assert_type(input,want_i3,want_n3,c77) + character(len=*), intent(in) :: input + integer, intent(in) :: want_i3, want_n3 + character(len=77), intent(out) :: c77 + character(len=37) :: packed_input + integer :: got_i3, got_n3 + + call clear_all_state('N0AAA','N0BBB') + packed_input=' ' + packed_input=input + got_i3=-1 + got_n3=-1 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('pack77',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('pack77',input,want_i3,want_n3,got_i3,got_n3) + end subroutine pack_and_assert_type + + subroutine decode_standard(c77,nrx,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + call clear_all_state('N0AAA','N0BBB') + call unpack_standard_current_state(c77,nrx,decoded,ok) + end subroutine decode_standard + + subroutine decode_var(c77,nrx,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + call clear_all_state('N0AAA','N0BBB') + call unpack_var_current_state(c77,nrx,decoded,ok) + end subroutine decode_var + + subroutine unpack_standard_current_state(c77,nrx,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + decoded=' ' + ok=.false. + call unpack77(c77,nrx,decoded,ok) + end subroutine unpack_standard_current_state + + subroutine unpack_var_current_state(c77,nrx,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + call unpack_var_current_state_thread(c77,nrx,1,decoded,ok) + end subroutine unpack_var_current_state + + subroutine unpack_var_current_state_thread(c77,nrx,nthr,decoded,ok) + character(len=77), intent(in) :: c77 + integer, intent(in) :: nrx, nthr + character(len=37), intent(out) :: decoded + logical, intent(out) :: ok + + decoded=' ' + ok=.false. + call unpack77_configured(c77,nrx,decoded,ok,unpack77_options(thread_index=nthr)) + end subroutine unpack_var_current_state_thread + + subroutine pack_var_current_state(input,want_i3,want_n3,ntxhash,c77) + character(len=*), intent(in) :: input + integer, intent(in) :: want_i3, want_n3, ntxhash + character(len=77), intent(out) :: c77 + character(len=37) :: packed_input + integer :: got_i3, got_n3 + + packed_input=' ' + packed_input=input + got_i3=-1 + got_n3=-1 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input,pack77_options(record_tx_hashes=ntxhash.eq.1)) + call assert_pack77_result('pack77',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('pack77',input,want_i3,want_n3,got_i3,got_n3) + end subroutine pack_var_current_state + + subroutine assert_record_tx_disabled_same_payload(input,want_i3,want_n3) + character(len=*), intent(in) :: input + integer, intent(in) :: want_i3, want_n3 + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: default_encoded, disabled_encoded + default_encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('default record_tx payload',packed_input, & + default_encoded) + call clear_all_state('N0AAA','N0BBB') + disabled_encoded=pack77_result_from_api(packed_input,pack77_options(record_tx_hashes=.false.)) + call assert_pack77_result('disabled record_tx payload',packed_input, & + disabled_encoded) + call assert_text_equal('disabled record_tx c77',default_encoded%c77, & + disabled_encoded%c77) + call assert_message_type('disabled record_tx type',input,want_i3,want_n3, & + disabled_encoded%i3,disabled_encoded%n3) + end block + call assert_shared_hash_tables_empty('disabled record_tx hashes') + end subroutine assert_record_tx_disabled_same_payload + + subroutine assert_rejected_candidate_does_not_record(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call clear_all_state('N0AAA','N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + if(encoded%encoded) then + call assert_message_type('rejected candidate fallback type',input,0,0, & + encoded%i3,encoded%n3) + endif + end block + call assert_shared_hash_tables_empty('rejected candidate hashes') + end subroutine assert_rejected_candidate_does_not_record + + subroutine assert_pack_unpack_hash_state_matches_pack_only(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input, decoded + character(len=77) :: c77 + character(len=13) :: calls10_after_unpack(0:1023) + character(len=13) :: calls12_after_unpack(0:4095) + character(len=13) :: calls22_after_unpack(1:MAXHASH) + integer :: ihash22_after_unpack(1:MAXHASH) + integer :: nzhash_after_unpack + integer :: i3,n3 + logical :: ok + + packed_input=' ' + packed_input=input + + call clear_all_state('N0AAA','N0BBB') + i3=-1 + n3=-1 + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + i3=encoded%i3 + n3=encoded%n3 + c77=encoded%c77 + end block + call assert_true('pack/unpack hash-state packed '//trim(input),i3.ge.0) + decoded=' ' + ok=.false. + call unpack77(c77,0,decoded,ok) + call assert_true('pack/unpack hash-state unpacked '//trim(input),ok) + nzhash_after_unpack=nzhash + calls10_after_unpack=calls10 + calls12_after_unpack=calls12 + calls22_after_unpack=calls22 + ihash22_after_unpack=ihash22 + + call clear_all_state('N0AAA','N0BBB') + i3=-1 + n3=-1 + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + i3=encoded%i3 + n3=encoded%n3 + c77=encoded%c77 + end block + call assert_true('pack-only hash-state packed '//trim(input),i3.ge.0) + + call assert_int('pack/unpack nzhash '//trim(input),nzhash_after_unpack,nzhash) + call assert_true('pack/unpack calls10 '//trim(input), & + all(calls10_after_unpack.eq.calls10)) + call assert_true('pack/unpack calls12 '//trim(input), & + all(calls12_after_unpack.eq.calls12)) + call assert_true('pack/unpack calls22 '//trim(input), & + all(calls22_after_unpack.eq.calls22)) + call assert_true('pack/unpack ihash22 '//trim(input), & + all(ihash22_after_unpack.eq.ihash22)) + end subroutine assert_pack_unpack_hash_state_matches_pack_only + + subroutine prime_hash_width(width,callsign,label) + integer, intent(in) :: width + character(len=*), intent(in) :: callsign, label + character(len=13) :: c13 + integer :: n + + if(width.le.0 .or. len_trim(callsign).le.0) return + call normalize_call(callsign,c13) + if(len_trim(c13).le.0) return + n=ihashcall(c13,width) + if(width.eq.10) then + calls10(n)=c13 + else if(width.eq.12) then + calls12(n)=c13 + else if(width.eq.22) then + if(nzhash.lt.MAXHASH) nzhash=nzhash+1 + ihash22(nzhash)=n + calls22(nzhash)=c13 + else + write(*,1010) trim(label), width +1010 format('Unsupported ',a,' hash width ',i0) + error stop 1 + endif + end subroutine prime_hash_width + + logical function shared_hash22_contains(callsign) + character(len=*), intent(in) :: callsign + character(len=13) :: c13 + integer :: n22 + + call normalize_call(callsign,c13) + n22=ihashcall(c13,22) + shared_hash22_contains=any(ihash22(1:nzhash).eq.n22) + end function shared_hash22_contains + +end program test_packjt77_hash_state diff --git a/tests/unit/packjt77/test_packjt77_invariants.f90 b/tests/unit/packjt77/test_packjt77_invariants.f90 new file mode 100644 index 00000000..3fd14493 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_invariants.f90 @@ -0,0 +1,150 @@ +program test_packjt77_invariants + + use packjt77_test_helpers + implicit none + + integer :: ntests + external :: genft8 + external :: genft4 + external :: genfst4 + external :: genmsk_128_90 + external :: genq65 + + ntests=0 + + call run_packjt77_common_invariants(.false.,ntests) + call run_packjt77_standard_schema_invariants(ntests) + call expect_callok_suffix_bounds(ntests) + call expect_tx_generators_use_legacy_fallback(ntests) + call expect_tx_generators_reject_invalid_fallback(ntests) + call expect_fst4w_keeps_preferred_wspr_strict(ntests) + + write(*,1000) ntests +1000 format('packjt77 invariant tests passed: ',i0) + +contains + + subroutine expect_callok_suffix_bounds(ntests) + integer, intent(inout) :: ntests + logical :: callok + + call assert_true('callok accepts normal suffix length',callok('K1ABC')) + call assert_true('callok rejects overlength suffix',.not.callok('N0CALL')) + + ntests=ntests+1 + end subroutine expect_callok_suffix_bounds + + subroutine expect_tx_generators_use_legacy_fallback(ntests) + integer, intent(inout) :: ntests + character(len=37) :: input, msgsent + integer :: i3, n3, iwspr, itype + integer :: itone79(79), itone85(85), itone105(105), itone144(144) + integer :: itone160(160) + integer*1 :: msgbits77(77), msgbits101(101) + + input='ABCDEFGHIJKLMN' + + call genft8(input,i3,n3,msgsent,msgbits77,itone79) + call assert_int('FT8 legacy fallback i3',0,i3) + call assert_int('FT8 legacy fallback n3',0,n3) + call assert_text_equal('FT8 legacy fallback message', & + 'ABCDEFGHIJKLM',msgsent) + call assert_true('FT8 legacy fallback tones',any(itone79.ne.0)) + + call genft4(input,0,msgsent,msgbits77,itone105) + call assert_text_equal('FT4 legacy fallback message', & + 'ABCDEFGHIJKLM',msgsent) + call assert_true('FT4 legacy fallback bits',any(msgbits77.ne.0)) + call assert_true('FT4 legacy fallback tones',any(itone105.ne.0)) + + iwspr=0 + call genfst4(input,0,msgsent,msgbits101,itone160,iwspr) + call assert_text_equal('FST4 legacy fallback message', & + 'ABCDEFGHIJKLM',msgsent) + call assert_int('FST4 legacy fallback iwspr',0,iwspr) + call assert_true('FST4 legacy fallback bits',any(msgbits101.ne.0)) + call assert_true('FST4 legacy fallback tones',any(itone160.ne.0)) + + itype=1 + call genmsk_128_90(input,0,msgsent,itone144,itype) + call assert_int('MSK144 legacy fallback type',1,itype) + call assert_text_equal('MSK144 legacy fallback message', & + 'ABCDEFGHIJKLM',msgsent) + call assert_true('MSK144 legacy fallback tones',any(itone144.ne.0)) + + call genq65(input,0,msgsent,itone85,i3,n3,0) + call assert_int('Q65 legacy fallback i3',0,i3) + call assert_int('Q65 legacy fallback n3',0,n3) + call assert_text_equal('Q65 legacy fallback message', & + 'ABCDEFGHIJKLM',msgsent) + call assert_true('Q65 legacy fallback tones',any(itone85.ne.0)) + + ntests=ntests+1 + end subroutine expect_tx_generators_use_legacy_fallback + + subroutine expect_fst4w_keeps_preferred_wspr_strict(ntests) + integer, intent(inout) :: ntests + character(len=37) :: input, msgsent + integer :: iwspr + integer :: itone160(160) + integer*1 :: msgbits101(101) + + input='PJ4/K1ABC FK52A!' + iwspr=1 + msgsent=' ' + msgbits101=1 + itone160=1 + + call genfst4(input,0,msgsent,msgbits101,itone160,iwspr) + + call assert_int('FST4W strict iwspr',1,iwspr) + call assert_text_equal('FST4W strict message','*** bad message ***', & + msgsent) + call assert_true('FST4W strict bits',all(msgbits101.eq.0)) + call assert_true('FST4W strict tones',all(itone160.eq.0)) + + ntests=ntests+1 + end subroutine expect_fst4w_keeps_preferred_wspr_strict + + subroutine expect_tx_generators_reject_invalid_fallback(ntests) + integer, intent(inout) :: ntests + character(len=37) :: input, msgsent + integer :: i3, n3, itype + integer :: itone85(85), itone105(105), itone144(144) + integer*1 :: msgbits77(77) + + input='$DX K1ABC FN42' + + msgsent=' ' + msgbits77=1 + itone105=1 + call genft4(input,1,msgsent,msgbits77,itone105) + call assert_text_equal('FT4 invalid fallback message', & + '*** bad message ***',msgsent) + call assert_true('FT4 invalid fallback bits',all(msgbits77.eq.0)) + call assert_true('FT4 invalid fallback tones',all(itone105(1:103).eq.0)) + + itype=1 + msgsent=' ' + itone144=1 + call genmsk_128_90(input,0,msgsent,itone144,itype) + call assert_int('MSK144 invalid fallback type',-1,itype) + call assert_text_equal('MSK144 invalid fallback message', & + '*** bad message ***',msgsent) + call assert_true('MSK144 invalid fallback tones',all(itone144.eq.0)) + + i3=0 + n3=0 + msgsent=' ' + itone85=1 + call genq65(input,0,msgsent,itone85,i3,n3,0) + call assert_int('Q65 invalid fallback i3',-1,i3) + call assert_int('Q65 invalid fallback n3',-1,n3) + call assert_text_equal('Q65 invalid fallback message', & + '*** bad message ***',msgsent) + call assert_true('Q65 invalid fallback tones',all(itone85.eq.0)) + + ntests=ntests+1 + end subroutine expect_tx_generators_reject_invalid_fallback + +end program test_packjt77_invariants diff --git a/tests/unit/packjt77/test_packjt77_mutation_sweep.f90 b/tests/unit/packjt77/test_packjt77_mutation_sweep.f90 new file mode 100644 index 00000000..58abdb60 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_mutation_sweep.f90 @@ -0,0 +1,280 @@ + program test_packjt77_mutation_sweep + use packjt77 + use packjt77_test_helpers + implicit none + + integer, parameter :: MAX_SEEDS=400,MAX_MUTANTS=50000 + character(len=37) :: seeds(MAX_SEEDS) + integer :: nseeds,nmutants,nexact,ncanon,nreject + + nseeds=0 + nmutants=0 + nexact=0 + ncanon=0 + nreject=0 + + call check_canonical_matcher() + call generate_seeds() + call assert_true('seed generator coverage', nseeds.ge.200) + call sweep_mutations() + + print '(a,i0,a,i0,a,i0,a,i0)', & + 'test_packjt77_mutation_sweep: mutants=', nmutants, & + ' encoded-exact=', nexact, ' encoded-canonical=', ncanon, & + ' rejected=', nreject + +contains + + subroutine check_canonical_matcher() + call assert_true('canonical compound bracket', & + canonical_match('W1AW/P','<W1AW/P>')) + call assert_true('canonical compound placeholder', & + canonical_match('PJ2/W1AW','<...>')) + call assert_true('canonical bracket placeholder', & + canonical_match('<PJ4/K1ABC>','<...>')) + call assert_true('canonical grid bracket reject', & + .not.canonical_match('FN42','<FN42>')) + call assert_true('canonical trailing slash reject', & + .not.canonical_match('K1ABC/','<K1ABC/>')) + call assert_true('canonical leading slash reject', & + .not.canonical_match('/K1ABC','</K1ABC>')) + call assert_true('canonical double slash reject', & + .not.canonical_match('A//B','<A//B>')) + end subroutine check_canonical_matcher + + subroutine generate_seeds() + character(len=13), parameter :: calls(6)=(/'K1ABC ', & + 'W9XYZ ','KA1ABC ','WA9XYZ ','PJ2/W1AW ', & + 'W1AW/P '/) + character(len=4), parameter :: grids(4)=(/'FN42','EM10','DM79','IO91'/) + character(len=3), parameter :: snrs(4)=(/'-12','+00','+20','R-7'/) + character(len=3), parameter :: rtty_reports(4)=(/'529','559','579','599'/) + character(len=3), parameter :: mults(4)=(/'MA ','CT ','DX ','EMA'/) + character(len=6), parameter :: vhf_exch(4)=(/'520001','590001', & + '592047','582047'/) + integer :: i,j + character(len=13) :: free_seed + + do i=1,4 + do j=1,4 + call add_seed(trim(calls(i))//' '//trim(calls(j))//' '//grids(j)) + call add_seed(trim(calls(i))//' '//trim(calls(j))//' '//snrs(i)) + call add_seed(trim(calls(i))//' '//trim(calls(j))//' R '//grids(j)) + call add_seed(trim(calls(i))//' '//trim(calls(j))//' RRR') + enddo + enddo + + do i=1,4 + call add_seed(trim(calls(i))//' RR73; W9XYZ <KH1/KH7Z> -12') + call add_seed(trim(calls(5))//' RR73; W9XYZ <KH1/KH7Z> -12') + call add_seed(trim(calls(i))//' '//trim(calls(j_index(i)))//' R 1A EMA') + call add_seed(trim(calls(6))//' '//trim(calls(i))//' 5A CT') + call add_seed('TU; '//trim(calls(i))//' W9XYZ R '//rtty_reports(i)// & + ' '//trim(mults(i))) + call add_seed(trim(calls(i))//' W9XYZ '//rtty_reports(i)// & + ' '//trim(mults(i))) + call add_seed('<PJ4/K1ABC> '//trim(calls(i))//' RR73') + call add_seed(trim(calls(5))//' <W7ABC> RR73') + call add_seed('<W3CCX> <K1JT/P> '//vhf_exch(i)//' FN20QI') + call add_seed('<W3CCX> <K1JT/P> R '//vhf_exch(i)//' FN20QI') + call add_seed(trim(calls(i))//' '//grids(i)//' 37') + call add_seed('0/'//trim(calls(i))//' 37') + call add_seed(trim(calls(i))//'/1 37') + enddo + + call add_seed('CQ PJ2/W1AW') + call add_seed('CQ K1ABC FN42') + call add_seed('123456789ABCDEF012') + call add_seed('0000000000000000DE') + call add_seed('HELLO WORLD 73') + call add_seed('FREE TEXT MSG') + + do i=1,80 + call add_seed('K1ABC W9XYZ +'//digit2(mod(i,50))) + call add_seed('K1ABC W9XYZ R+'//digit2(mod(i,50))) + call add_seed('WA9XYZ KA1ABC '//field_day_exchange(i)) + enddo + + do i=1,160 + write(free_seed,'("TXT",i3.3," MSG")') i + call add_seed(free_seed) + enddo + end subroutine generate_seeds + + integer function j_index(i) result(j) + integer, intent(in) :: i + + j=mod(i,4)+1 + end function j_index + + character(len=2) function digit2(n) result(text) + integer, intent(in) :: n + + write(text,'(i2.2)') n + end function digit2 + + character(len=3) function field_day_exchange(i) result(text) + integer, intent(in) :: i + + write(text,'(i0,a1)') mod(i-1,32)+1, achar(iachar('A')+mod(i,6)) + end function field_day_exchange + + subroutine add_seed(text) + character(len=*), intent(in) :: text + character(len=37) :: msg,decoded + logical :: ok + type(pack77_result) :: encoded + + if(nseeds.ge.MAX_SEEDS) return + msg=' ' + msg=text + call clear_all_state('N0AAA','N0BBB') + encoded=pack77_result_from_api(msg) + if(.not.encoded%encoded) return + decoded=' ' + ok=.false. + call unpack77(encoded%c77,0,decoded,ok) + call assert_true('seed decodes', ok) + nseeds=nseeds+1 + seeds(nseeds)=msg + end subroutine add_seed + + subroutine sweep_mutations() + integer :: i + + do i=1,nseeds + call mutate_seed(seeds(i)) + if(nmutants.ge.MAX_MUTANTS) exit + enddo + end subroutine sweep_mutations + + subroutine mutate_seed(seed) + character(len=*), intent(in) :: seed + character(len=8), parameter :: probes='A0/<>+. ' + character(len=37) :: mutant + integer :: i,j,n + + n=len_trim(seed) + do i=1,n + do j=1,len(probes) + mutant=seed + mutant(i:i)=probes(j:j) + call check_mutant(mutant) + if(nmutants.ge.MAX_MUTANTS) return + enddo + enddo + + do i=1,n + mutant=' ' + if(i.gt.1) mutant(1:i-1)=seed(1:i-1) + if(i.lt.n) mutant(i:n-1)=seed(i+1:n) + call check_mutant(mutant) + if(nmutants.ge.MAX_MUTANTS) return + enddo + + call mutate_tokens(seed) + end subroutine mutate_seed + + subroutine mutate_tokens(seed) + character(len=*), intent(in) :: seed + character(len=37) :: tokens(19),mutant + integer :: ntokens,i,j + + call split_tokens(seed,tokens,ntokens) + do i=1,ntokens + mutant=join_tokens(tokens,ntokens,i,i) + call check_mutant(mutant) + if(nmutants.ge.MAX_MUTANTS) return + enddo + do i=1,ntokens-1 + do j=i+1,ntokens + mutant=join_tokens(tokens,ntokens,i,j) + call check_mutant(mutant) + if(nmutants.ge.MAX_MUTANTS) return + enddo + enddo + end subroutine mutate_tokens + + character(len=37) function join_tokens(tokens,ntokens,a,b) result(msg) + character(len=37), intent(in) :: tokens(:) + integer, intent(in) :: ntokens,a,b + integer :: i + character(len=37) :: work(19) + + work=tokens + if(a.eq.b) then + msg=' ' + do i=1,ntokens + call append_token(msg,tokens(i)) + if(i.eq.a) call append_token(msg,tokens(i)) + enddo + else + work(a)=tokens(b) + work(b)=tokens(a) + msg=' ' + do i=1,ntokens + call append_token(msg,work(i)) + enddo + endif + end function join_tokens + + subroutine append_token(msg,token) + character(len=37), intent(inout) :: msg + character(len=*), intent(in) :: token + integer :: n,m + + n=len_trim(msg) + m=len_trim(token) + if(m.eq.0) return + if(n.eq.0) then + if(m.le.37) msg(1:m)=token(1:m) + else if(n+m+1.le.37) then + msg(n+1:n+1)=' ' + msg(n+2:n+m+1)=token(1:m) + endif + end subroutine append_token + + subroutine check_mutant(mutant) + character(len=*), intent(in) :: mutant + character(len=37) :: msg,decoded + logical :: ok,is_exact,is_canonical,is_telemetry + type(pack77_result) :: encoded + + if(nmutants.ge.MAX_MUTANTS) return + nmutants=nmutants+1 + msg=' ' + msg=mutant + call clear_all_state('N0AAA','N0BBB') + encoded=pack77_result_from_api(msg) + if(.not.encoded%encoded) then + nreject=nreject+1 + return + endif + call assert_true('encoded gate rejected', encoded%status.ne.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED) + decoded=' ' + ok=.false. + call unpack77(encoded%c77,0,decoded,ok) + if(.not.ok) then + write(*,'(a,a,a,a,a)') 'silent rewrite: input="', trim(msg), & + '" c77="', trim(encoded%c77), '"' + error stop 1 + endif + is_exact=normalized_equal(msg,decoded) + is_canonical=canonical_match(msg,decoded) + is_telemetry=telemetry_match(msg,decoded) + if(.not.is_exact .and. .not.is_canonical .and. .not.is_telemetry) then + write(*,'(a,a,a,a,a,a,a)') 'silent rewrite: input="', trim(msg), & + '" decoded="', trim(decoded), '" c77="', trim(encoded%c77), '"' + error stop 1 + endif + if(is_exact) then + nexact=nexact+1 + else if(is_telemetry) then + ncanon=ncanon+1 + else + call assert_true('canonical mutation decode', is_canonical) + ncanon=ncanon+1 + endif + end subroutine check_mutant + +end program test_packjt77_mutation_sweep diff --git a/tests/unit/packjt77/test_packjt77_pack28_sweep.f90 b/tests/unit/packjt77/test_packjt77_pack28_sweep.f90 new file mode 100644 index 00000000..66433692 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_pack28_sweep.f90 @@ -0,0 +1,231 @@ +program test_packjt77_pack28_sweep + + use packjt77 + use packjt77_grammar, only: PACK77_NTOKENS,PACK77_MAX22 + implicit none + + integer, parameter :: ncat=20 + integer, parameter :: nsweep=260 + integer, parameter :: expected_n28(nsweep) = (/ & + 5950126, 5950126, 5121162, 5121162, 3532835, 5950126, 5950126, & + 5950126, 2063592, 5950126, 4386540, 3225066, 3225066, 3959688, & + 5121162, 5002078, 5002078, 3532835, 5950126, 4907736, 4396757, & + 4636842, 3214849, 5375614, 6173770, 4396757, 4396757, 4396757, & + 2063592, 4396757, 4993936, 2, 2, 0, 3454934, & + 4168964, 4776360, 4253090, 4636842, 5755217, 8246608, 86387389, & + 11395888, 204642853, 22417639, 84419089, 8246608, 8246608, 2063592, & + 8246608, 194269912, 2195446, 2195446, 2111640, 1, 2913946, & + 3521341, 4940621, 86387389, 10214908, 8246635, 86388118, 11395915, & + 204661807, 22418368, 84419818, 4873537, 5750231, 2063592, 5750231, & + 6256420, 5239844, 1023, 4175765, 3318227, 2338993, 5010514, & + 2065856, 86388118, 10214962, 8246636, 86388145, 11395916, 204662509, & + 22418395, 84419872, 5574985, 2257374, 2063592, 2257374, 3991096, & + 5415206, 1548, 6216860, 5359321, 4380087, 4372313, 2416579, & + 86388172, 10214965, 6022918, 86388146, 5193953, 204662535, 22418396, & + 84419875, 3165162, 4041856, 2363507, 4041856, 5686611, 126, & + 15737, 2959280, 2101742, 6164569, 3835940, 4156578, 86388175, & + 4447486, 2074017, 3976499, 5439357, 4585084, 5513427, 2444633, & + 3432875, 4309569, 2063592, 4309569, 5932014, 4857335, 398841, & + 3204683, 2347145, 2260287, 4594460, 4335053, 4845483, 5206005, & + 2080475, 3982957, 5445815, 4591542, 5519885, 2464594, 3439920, & + 4316614, 2063592, 4316614, 5951388, 4863793, 2695765, 3211141, & + 2353603, 2280248, 4614421, 4340337, 4865444, 5225967, 2080645, & + 3983127, 5445985, 4591712, 5520055, 2465120, 3440106, 4316799, & + 2063592, 4316799, 5951558, 4863963, 2695935, 3211311, 2353773, & + 2280774, 4614946, 4340491, 4865970, 5226492, 2080650, 3983132, & + 5445989, 4591716, 5520059, 2465134, 3440111, 4316804, 2063592, & + 4316804, 5951563, 4863968, 2695939, 3211316, 2353778, 2280788, & + 4614960, 4340492, 4865984, 5226506, 2080650, 3983132, 5445989, & + 4591716, 5520059, 2465134, 3440111, 4316804, 2063592, 4316804, & + 5951563, 4863968, 2695940, 3211316, 2353778, 2280788, 4614960, & + 4340492, 4865984, 5226506, 2080650, 3983132, 5445989, 4591716, & + 5520059, 2465134, 3440111, 4316804, 2063592, 4316804, 5951563, & + 4863968, 2695940, 3211316, 2353778, 2280788, 4614960, 4340492, & + 4865984, 5226506, 2080650, 3983132, 5445989, 4591716, 5520059, & + 2465134, 3440111, 4316804, 2063592, 4316804, 5951563, 4863968, & + 2695940, 3211316, 2353778, 2280788, 4614960, 4340492, 4865984, & + 5226506 /) + integer :: i,n28 + character(len=13) :: decoded, token + logical :: ok + + call check_cq_modifier_edges() + + do i=1,nsweep + token=sweep_token(i) + call pack28(token,n28) + if(n28.ne.expected_n28(i)) then + write(*,1000) i, trim(token), expected_n28(i), n28 +1000 format('pack28 sweep case ',i0,' "',a,'" expected ',i0,' got ',i0) + error stop 1 + endif + decoded=' ' + ok=.false. + call unpack28(n28,decoded,ok) + enddo + + print '(a,i0,a)', 'test_packjt77_pack28_sweep: ', nsweep, ' checks passed' + +contains + + character(len=13) function sweep_token(i) result(token) + integer, intent(in) :: i + integer :: category,n + + category=mod(i-1,ncat)+1 + n=(i-1)/ncat+1 + token=' ' + select case(category) + case(1) + if(n.lt.3) then + token=take_prefix('AAAAAAAAAAAAA',n) + else + token=take_prefix('A1AAAAAAAAAAA',n) + endif + case(2) + token=take_prefix('AB1AAAAAAAAAA',n) + case(3) + if(n.lt.3) then + token=take_prefix('QQQQQQQQQQQQQ',n) + else + token=take_prefix('Q1AAAAAAAAAAA',n) + endif + case(4) + token=take_prefix('QZ9ZZZAAAAAAA',n) + case(5) + token=take_prefix('1A1AAAAAAAAAA',n) + case(6) + if(n.lt.3) then + token=take_prefix('AAAAAAAAAAAAA',n) + else + token=take_prefix('A11ABCXXXXXXX',n) + endif + case(7) + if(n.lt.3) then + token=take_prefix('AAAAAAAAAAAAA',n) + else + token=take_prefix('A1A/BBBBBBBBB',n) + endif + case(8) + if(n.lt.3) then + token=take_prefix('AAAAAAAAAAAAA',n) + else + token=take_prefix('A1A$BBBBBBBBB',n) + endif + case(9) + token=take_prefix('<W1AW>AAAAAAA',n) + case(10) + if(n.lt.3) then + token=take_prefix('AAAAAAAAAAAAA',n) + else + token=take_prefix('A1A>BBBBBBBBB',n) + endif + case(11) + token=take_prefix('PJ2/W1AWAAAAA',n) + case(12) + token=take_prefix('CQ_123AAAAAAA',n) + case(13) + token=take_prefix('CQ_TESTAAAAAA',n) + case(14) + token=take_prefix('DEAAAAAAAAAAA',n) + case(15) + token=take_prefix('QRZAAAAAAAAAA',n) + case(16) + token=take_prefix('3DA0ABCXXXXXX',n) + case(17) + token=take_prefix('3XABCXXXXXXXX',n) + case(18) + token=take_prefix('1234567890123',n) + case(19) + token=take_prefix('AB1ABCXXXXXXX',n) + case(20) + if(n.lt.3) then + token=take_prefix('KKKKKKKKKKKKK',n) + else + token=take_prefix('K1ABCXXXXXXXX',n) + endif + end select + end function sweep_token + + character(len=13) function take_prefix(seed,n) result(token) + character(len=*), intent(in) :: seed + integer, intent(in) :: n + + token=' ' + token(1:n)=seed(1:n) + end function take_prefix + + subroutine check_cq_modifier_edges() + call assert_cq_modifier_special('CQ_A') + call assert_cq_modifier_special('CQ_AB') + call assert_cq_modifier_special('CQ_ABC') + call assert_cq_modifier_special('CQ_ABCD') + call assert_cq_modifier_special('CQ_000') + call assert_cq_modifier_special('CQ_123') + call assert_cq_modifier_special('CQ_999') + + call assert_cq_modifier_hash('CQ_') + call assert_cq_modifier_hash('CQ_1') + call assert_cq_modifier_hash('CQ_12') + call assert_cq_modifier_hash('CQ_1234') + call assert_cq_modifier_hash('CQ_ABCDE') + call assert_cq_modifier_hash('CQ_A1') + call assert_cq_modifier_hash('CQ_1A') + call assert_cq_modifier_hash('CQ_AB12') + call assert_cq_modifier_hash('CQ_A/B') + call assert_cq_modifier_hash('CQ_A-B') + end subroutine check_cq_modifier_edges + + subroutine assert_cq_modifier_special(input) + character(len=*), intent(in) :: input + character(len=13) :: c13 + integer :: got + + call clear_hash_state() + c13=' ' + c13=input + call pack28(c13,got) + if(got.lt.3 .or. got.ge.PACK77_NTOKENS) then + write(*,1010) trim(input), got +1010 format('CQ modifier "',a,'" expected special token, got ',i0) + error stop 1 + endif + if(nzhash.ne.0) then + write(*,1011) trim(input), nzhash +1011 format('CQ modifier "',a,'" unexpectedly staged ',i0,' hashes') + error stop 1 + endif + end subroutine assert_cq_modifier_special + + subroutine assert_cq_modifier_hash(input) + character(len=*), intent(in) :: input + character(len=13) :: c13 + integer :: got + + call clear_hash_state() + c13=' ' + c13=input + call pack28(c13,got) + if(got.lt.PACK77_NTOKENS .or. got.ge.PACK77_NTOKENS+PACK77_MAX22) then + write(*,1020) trim(input), got +1020 format('CQ modifier "',a,'" expected hash token, got ',i0) + error stop 1 + endif + if(nzhash.ne.1 .or. calls22(1).ne.c13) then + write(*,1021) trim(input), nzhash, trim(calls22(1)) +1021 format('CQ modifier "',a,'" expected one committed hash, got nzhash=', & + i0,' calls22(1)="',a,'"') + error stop 1 + endif + end subroutine assert_cq_modifier_hash + + subroutine clear_hash_state() + calls10='' + calls12='' + calls22='' + recent_calls='' + ihash22=-1 + nzhash=0 + end subroutine clear_hash_state + +end program test_packjt77_pack28_sweep diff --git a/tests/unit/packjt77/test_packjt77_protocol_vectors.f90 b/tests/unit/packjt77/test_packjt77_protocol_vectors.f90 new file mode 100644 index 00000000..70930127 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_protocol_vectors.f90 @@ -0,0 +1,228 @@ +program test_packjt77_protocol_vectors + + use packjt77 + use packjt77_test_helpers + implicit none + + integer :: ntests + + ntests=0 + + call expect_hash_vector('K1ABC', 712, 2851, 2920267) + call expect_hash_vector('W9XYZ', 972, 3889, 3982604) + call expect_hash_vector('PJ4/K1ABC', 346, 1387, 1420834) + call expect_hash_vector('KH1/KH7Z', 201, 806, 825805) + call expect_hash_vector('K1JT/P', 959, 3839, 3931158) + call expect_hash_vector('W3CCX', 665, 2662, 2726483) + call expect_hash_vector('3DA0ABC', 48, 192, 196695) + call expect_hash_vector('3XABC', 563, 2254, 2308721) + call expect_hash_vector('///////////', 671, 2685, 2749801) + call expect_hash_vector('ZZZZZZZZZZZ', 902, 3609, 3695718) + call expect_hash_vector('99999999999', 762, 3050, 3123740) + call expect_hash_vector('A23456789Z/', 122, 488, 499902) + call expect_hash_vector(' ', 0, 0, 0) + + call expect_pack_bits('K1ABC W9XYZ FN42', 1, 0, -1, -1, & + '00001001101111011110001101010000011000010100100111011100000010100001100110001') + call expect_pack_bits('<PJ4/K1ABC> W9XYZ RR73', 1, 0, -1, -1, & + '00000011010100101011000010100000011000010100100111011100000111111001110101001') + call expect_pack_bits('K1ABC RR73; W9XYZ <KH1/KH7Z> -12', 0, 1, -1, -1, & + '00001001101111011110001101010000110000101001001110111000001100100101001001000') + call expect_pack_bits('PJ2/W1AW <W7ABC> RR73', 4, 0, -1, -1, & + '00100100001100000000000000001011000010101110000110010100011010110100111100100') + call expect_pack_bits('<W3CCX> <K1JT/P> 592047 RR99XX', 5, 0, -1, -1, & + '10100110011011101111111100000101100111111111111111000111001100001111111111101') + call expect_pack_bits('K1ABC FN42 37', 0, 6, -1, -1, & + '00001001101111011110001101010101000011001100101100000000000000000000000110000') + ! WSPR Type 2 prefix/suffix vectors need both exact bits and decoded text. + call expect_pack_bits('PJ2/K1ABC 37', 0, 6, -1, -1, & + '00001001101111011110001101011000000100111110010111000000000000000000000110000', & + 'PJ2/K1ABC 37') + call expect_pack_bits('<PJ4/K1ABC> FK52AB', 0, 6, 0, 6, & + '01010110101110001000100010111111101110100000101010000000000000000000000110000') + + call expect_unified_codec_bits('K1ABC W9XYZ FN42', -1, -1) + call expect_unified_codec_bits('FREE TEXT MSG', -1, -1) + call expect_unified_codec_bits('WA9XYZ KA1ABC R 16A EMA', -1, -1) + call expect_unified_codec_bits('WA9XYZ KA1ABC R 32A EMA', -1, -1) + call expect_unified_codec_bits('TU; W9XYZ G8ABC R 559 0013', -1, -1) + call expect_unified_codec_bits('K1ABC RR73; W9XYZ <KH1/KH7Z> -12', -1, -1) + call expect_unified_codec_bits('<PJ4/K1ABC> W9XYZ RR73', -1, -1) + call expect_unified_codec_bits('PJ2/W1AW <W7ABC> RR73', -1, -1) + call expect_unified_codec_bits('<W3CCX> <K1JT/P> 592047 RR99XX', -1, -1) + call expect_unified_codec_bits('K1ABC FN42 37', -1, -1) + call expect_unified_codec_bits('<PJ4/K1ABC> FK52AB', 0, 6) + + call expect_binary_payload_for_wspr_message('PJ4/K1ABC 37') + call expect_not_wspr_payload('K1ABC/ABCD 37') + + write(*,1000) ntests +1000 format('packjt77 protocol vector tests passed: ',i0) + +contains + + subroutine expect_hash_vector(callsign,want10,want12,want22) + character(len=*), intent(in) :: callsign + integer, intent(in) :: want10, want12, want22 + character(len=13) :: c13 + integer :: got10, got12, got22 + + c13=' ' + c13=callsign + got10=ihashcall(c13,10) + got12=ihashcall(c13,12) + got22=ihashcall(c13,22) + if(got10.ne.want10 .or. got12.ne.want12 .or. got22.ne.want22) then + write(*,1010) trim(callsign), got10, got12, got22, want10, want12, want22 +1010 format('Hash vector failure for "',a,'"; got ',i0,1x,i0,1x,i0, & + ' wanted ',i0,1x,i0,1x,i0) + error stop 1 + endif + + if(got10.lt.0 .or. got10.gt.1023 .or. got12.lt.0 .or. got12.gt.4095 .or. & + got22.lt.0 .or. got22.gt.4194303) then + write(*,1040) trim(callsign), got10, got12, got22 +1040 format('Hash range failure for "',a,'"; got ',i0,1x,i0,1x,i0) + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_hash_vector + + subroutine expect_pack_bits(input,want_i3,want_n3,pack_i3,pack_n3,expected_c77, & + expected_decode) + character(len=*), intent(in) :: input, expected_c77 + character(len=*), intent(in), optional :: expected_decode + integer, intent(in) :: want_i3, want_n3, pack_i3, pack_n3 + character(len=77) :: c77 + character(len=37) :: decoded + integer :: got_i3, got_n3 + logical :: ok + + call pack_standard(input,pack_i3,pack_n3,got_i3,got_n3,c77) + call assert_message_type('pack77',input,want_i3,want_n3,got_i3,got_n3) + call assert_binary_payload('pack77',input,c77) + if(c77.ne.expected_c77) then + write(*,1030) trim(input), c77, expected_c77 +1030 format('77-bit vector failure for "',a,'"; got ',a,' wanted ',a) + error stop 1 + endif + + if(present(expected_decode)) then + call reset_packjt77_state() + decoded=' ' + ok=.false. + call unpack77(c77,0,decoded,ok) + call assert_decode('pack77 vector',input,expected_decode,decoded,ok) + endif + + ntests=ntests+1 + end subroutine expect_pack_bits + + subroutine expect_unified_codec_bits(input,pack_i3,pack_n3) + character(len=*), intent(in) :: input + integer, intent(in) :: pack_i3, pack_n3 + character(len=77) :: first_c77, second_c77 + integer :: first_i3, first_n3, second_i3, second_n3 + + call pack_standard(input,pack_i3,pack_n3,first_i3,first_n3,first_c77) + call pack_standard(input,pack_i3,pack_n3,second_i3,second_n3,second_c77) + if(first_i3.ne.second_i3 .or. first_n3.ne.second_n3) then + write(*,1040) trim(input), first_i3, first_n3, second_i3, second_n3 +1040 format('Unified codec type failure for "',a,'"; first pack77 got ',i0,'.',i0, & + ' second pack77 got ',i0,'.',i0) + error stop 1 + endif + call assert_binary_payload('pack77',input,first_c77) + call assert_binary_payload('pack77',input,second_c77) + if(first_c77.ne.second_c77) then + write(*,1050) trim(input), first_c77, second_c77 +1050 format('Unified codec bit failure for "',a,'"; first pack77 ',a, & + ' second pack77 ',a) + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_unified_codec_bits + + subroutine expect_binary_payload_for_wspr_message(input) + character(len=*), intent(in) :: input + character(len=77) :: c77 + character(len=37) :: packed_input + integer :: got_i3, got_n3 + + packed_input=' ' + packed_input=input + call reset_packjt77_state() + + got_i3=-1 + got_n3=-1 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(packed_input) + call assert_pack77_result('pack77',packed_input,encoded) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + call assert_message_type('pack77',input,0,6,got_i3,got_n3) + call assert_binary_payload('pack77',input,c77) + + ntests=ntests+1 + end subroutine expect_binary_payload_for_wspr_message + + subroutine expect_not_wspr_payload(input) + character(len=*), intent(in) :: input + character(len=37) :: packed_input + type(pack77_result) :: encoded + + packed_input=' ' + packed_input=input + call reset_packjt77_state() + + encoded=pack77_result_from_api(packed_input) + if(encoded%encoded .and. encoded%i3.eq.0 .and. encoded%n3.eq.6) then + write(*,1060) trim(input) +1060 format('WSPR reject failure for "',a,'"; still packed as 0.6') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_not_wspr_payload + + subroutine pack_standard(input,pack_i3,pack_n3,got_i3,got_n3,c77) + character(len=*), intent(in) :: input + integer, intent(in) :: pack_i3, pack_n3 + integer, intent(out) :: got_i3, got_n3 + character(len=77), intent(out) :: c77 + character(len=37) :: packed_input + + packed_input=' ' + packed_input=input + call reset_packjt77_state() + got_i3=pack_i3 + got_n3=pack_n3 + c77='' + block + type(pack77_result) :: encoded + encoded=pack77_with_hint(packed_input,pack_i3,pack_n3) + call assert_pack77_result('pack77',packed_input,encoded) + call assert_true('pack77 gate not rejected',encoded%status.ne.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED) + got_i3=encoded%i3 + got_n3=encoded%n3 + c77=encoded%c77 + end block + end subroutine pack_standard + + subroutine reset_packjt77_state() + integer :: n10, n12, n22 + + call clear_all_state('N0AAA','N0BBB') + call save_hash_call(mycall13,hashmy10_configured,hashmy12_configured,hashmy22_configured) + hashdx10_configured=ihashcall(dxcall13,10) + call save_hash_call(dxcall13,n10,n12,n22) + call queue_hash_call_for_thread(dxcall13,1) + end subroutine reset_packjt77_state + +end program test_packjt77_protocol_vectors diff --git a/tests/unit/packjt77/test_packjt77_schema_decoder.f90 b/tests/unit/packjt77/test_packjt77_schema_decoder.f90 new file mode 100644 index 00000000..7c9816f5 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_schema_decoder.f90 @@ -0,0 +1,205 @@ +program test_packjt77_schema_decoder + + use packjt77_schema + use packjt77 + use packjt77_test_helpers + implicit none + + integer :: ntests + + ntests=0 + + call expect_type1_exact_fields() + call expect_type2_tag_decode() + call expect_invalid_binary_and_tag_fail() + call expect_type1_grid_boundary() + call expect_wspr_selector_padding_and_power_checks() + call expect_type5_grid_range_check() + call expect_type5_raw_invalid_serial_rejected() + call expect_failure_has_no_shared_state_side_effects() + + write(*,1000) ntests +1000 format('packjt77 schema decoder tests passed: ',i0) + +contains + + subroutine expect_type1_exact_fields() + character(len=77) :: c77 + type(pack77_type12_fields) :: fields + integer :: i3,n3 + logical :: ok + + c77='00001001101111011110001101010000011000010100100111011100000010100001100110001' + + call decode_pack77_tag(c77,i3,n3,ok) + call assert_true('Type 1 tag decode',ok) + call assert_int('Type 1 i3',1,i3) + call assert_int('Type 1 n3',0,n3) + + call decode_pack77_type1(c77,fields,ok) + call assert_true('Type 1 field decode',ok) + call assert_int('Type 1 n28a',10214965,fields%n28a) + call assert_int('Type 1 ipa',0,fields%ipa) + call assert_int('Type 1 n28b',12751800,fields%n28b) + call assert_int('Type 1 ipb',0,fields%ipb) + call assert_int('Type 1 ir',0,fields%ir) + call assert_int('Type 1 igrid4',10342,fields%igrid4) + + ntests=ntests+1 + end subroutine expect_type1_exact_fields + + subroutine expect_type2_tag_decode() + character(len=77) :: c77 + type(pack77_type12_fields) :: fields + integer :: i3,n3 + logical :: ok + + c77='00001001101111011110001101010000011000010100100111011100000010100001100110010' + + call decode_pack77_tag(c77,i3,n3,ok) + call assert_true('Type 2 tag decode',ok) + call assert_int('Type 2 i3',2,i3) + call assert_int('Type 2 n3',0,n3) + call decode_pack77_type2(c77,fields,ok) + call assert_true('Type 2 field decode',ok) + call assert_int('Type 2 n28a',10214965,fields%n28a) + call assert_int('Type 2 igrid4',10342,fields%igrid4) + + ntests=ntests+1 + end subroutine expect_type2_tag_decode + + subroutine expect_invalid_binary_and_tag_fail() + character(len=77) :: c77 + type(pack77_type12_fields) :: fields + integer :: i3,n3 + logical :: ok + + c77='00001001101111011110001101010000011000010100100111011100000010100001100110001' + c77(10:10)='x' + call decode_pack77_tag(c77,i3,n3,ok) + call assert_true('non-binary tag rejected',.not.ok) + + c77='00001001101111011110001101010000011000010100100111011100000010100001100110001' + c77(75:77)='010' + call decode_pack77_type1(c77,fields,ok) + call assert_true('wrong fixed i3 rejected',.not.ok) + + ntests=ntests+1 + end subroutine expect_invalid_binary_and_tag_fail + + subroutine expect_type1_grid_boundary() + character(len=37) :: input, decoded + character(len=77) :: c77 + logical :: ok + + input='K1ABC W9XYZ FN42' + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_pack77_result('pack77',input,encoded) + call assert_int('Type 1 boundary i3',1,encoded%i3) + call assert_int('Type 1 boundary n3',0,encoded%n3) + c77=encoded%c77 + end block + + write(c77(60:74),'(b15.15)') 32399 + decoded=' ' + ok=.false. + call unpack77_configured(c77,0,decoded,ok, & + unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) + call assert_true('Type 1 grid boundary succeeds',ok) + call assert_text_equal('Type 1 grid boundary decode', & + 'K1ABC W9XYZ RR99',decoded) + + write(c77(60:74),'(b15.15)') 32400 + decoded=' ' + ok=.true. + call unpack77_configured(c77,0,decoded,ok, & + unpack77_options(record_hashes=.false.,record_recent_calls=.false.)) + call assert_true('Type 1 invalid grid boundary fails',.not.ok) + + ntests=ntests+1 + end subroutine expect_type1_grid_boundary + + subroutine expect_wspr_selector_padding_and_power_checks() + character(len=77) :: c77 + type(pack77_wspr_type1_fields) :: type1_fields + type(pack77_wspr_type3_fields) :: type3_fields + logical :: ok + + c77=repeat('0',77) + c77(72:77)='110000' + c77(48:50)='110' + call decode_pack77_wspr_type1(c77,type1_fields,ok) + call assert_true('invalid WSPR Type 1 selector rejected',.not.ok) + call decode_pack77_wspr_type3(c77,type3_fields,ok) + call assert_true('invalid WSPR Type 3 selector rejected',.not.ok) + + c77=repeat('0',77) + c77(72:77)='110000' + c77(48:50)='010' + c77(51:51)='1' + call decode_pack77_wspr_type3(c77,type3_fields,ok) + call assert_true('nonzero WSPR padding rejected',.not.ok) + + c77=repeat('0',77) + c77(44:48)='11111' + c77(49:50)='00' + c77(72:77)='110000' + call decode_pack77_wspr_type1(c77,type1_fields,ok) + call assert_true('invalid WSPR raw power rejected',.not.ok) + + ntests=ntests+1 + end subroutine expect_wspr_selector_padding_and_power_checks + + subroutine expect_type5_grid_range_check() + character(len=77) :: c77 + type(pack77_type5_fields) :: fields + logical :: ok + + c77=repeat('0',77) + c77(50:74)=repeat('1',25) + c77(75:77)='101' + call decode_pack77_type5(c77,fields,ok) + call assert_true('Type 5 invalid grid rejected',.not.ok) + + ntests=ntests+1 + end subroutine expect_type5_grid_range_check + + subroutine expect_type5_raw_invalid_serial_rejected() + character(len=77) :: c77 + character(len=37) :: decoded + logical :: ok, unpack_ok + + call encode_pack77_type5(0,0,0,0,1,0,c77,ok) + call assert_true('Type 5 raw serial one encoded',ok) + write(c77(39:49),'(b11.11)') 0 + + decoded=' ' + unpack_ok=.true. + call unpack77(c77,0,decoded,unpack_ok) + call assert_true('Type 5 raw serial zero rejected',.not.unpack_ok) + + ntests=ntests+1 + end subroutine expect_type5_raw_invalid_serial_rejected + + subroutine expect_failure_has_no_shared_state_side_effects() + character(len=77) :: c77 + type(pack77_wspr_type3_fields) :: fields + logical :: ok + + call clear_all_state('','') + c77=repeat('0',77) + c77(48:50)='010' + c77(51:51)='1' + c77(72:77)='110000' + + call decode_pack77_wspr_type3(c77,fields,ok) + + call assert_true('schema decode failure rejected',.not.ok) + call assert_shared_hash_tables_empty('decoder failure') + + ntests=ntests+1 + end subroutine expect_failure_has_no_shared_state_side_effects + +end program test_packjt77_schema_decoder diff --git a/tests/unit/packjt77/test_packjt77_schema_encoder.f90 b/tests/unit/packjt77/test_packjt77_schema_encoder.f90 new file mode 100644 index 00000000..439f5e76 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_schema_encoder.f90 @@ -0,0 +1,99 @@ +program test_packjt77_schema_encoder + + use packjt77_schema + use packjt77_test_helpers + implicit none + + integer :: ntests + + ntests=0 + + call expect_type1_exact_bits() + call expect_type2_tag_bits() + call expect_range_failures() + call expect_bitstring_validation() + call expect_failure_has_no_shared_state_side_effects() + + write(*,1000) ntests +1000 format('packjt77 schema encoder tests passed: ',i0) + +contains + + subroutine expect_type1_exact_bits() + character(len=77) :: c77 + logical :: ok + + call encode_pack77_type1(10214965,0,12751800,0,0,10342,c77,ok) + + call assert_true('Type 1 schema encode',ok) + call assert_binary_payload('Type 1 schema','K1ABC W9XYZ FN42',c77) + call assert_text_equal('Type 1 c77',c77, & + '00001001101111011110001101010000011000010100100111011100000010100001100110001') + call assert_text_equal('Type 1 i3 bits',c77(75:77),'001') + ntests=ntests+1 + end subroutine expect_type1_exact_bits + + subroutine expect_type2_tag_bits() + character(len=77) :: c77 + logical :: ok + + call encode_pack77_type2(10214965,0,12751800,0,0,10342,c77,ok) + + call assert_true('Type 2 schema encode',ok) + call assert_binary_payload('Type 2 schema','tag-only portable layout',c77) + call assert_text_equal('Type 2 c77',c77, & + '00001001101111011110001101010000011000010100100111011100000010100001100110010') + call assert_text_equal('Type 2 i3 bits',c77(75:77),'010') + ntests=ntests+1 + end subroutine expect_type2_tag_bits + + subroutine expect_range_failures() + character(len=77) :: c77 + logical :: ok + + call encode_pack77_type1(-1,0,12751800,0,0,10342,c77,ok) + call assert_true('negative field rejected',.not.ok) + + call encode_pack77_type1(10214965,0,12751800,0,0,32768,c77,ok) + call assert_true('too-wide field rejected',.not.ok) + + call encode_pack77_type5(0,0,0,0,0,0,c77,ok) + call assert_true('Type 5 serial zero rejected',.not.ok) + + ntests=ntests+1 + end subroutine expect_range_failures + + subroutine expect_bitstring_validation() + character(len=77) :: c77 + logical :: ok + + call encode_pack77_free_text(repeat('1',71),c77,ok) + call assert_true('free-text bitstring accepted',ok) + call assert_text_equal('free-text tag bits',c77(72:77),'000000') + + call encode_pack77_free_text(repeat('1',70),c77,ok) + call assert_true('short bitstring rejected',.not.ok) + + call encode_pack77_free_text(repeat('1',72),c77,ok) + call assert_true('long bitstring rejected',.not.ok) + + call encode_pack77_free_text(repeat('1',70)//'X',c77,ok) + call assert_true('non-binary bitstring rejected',.not.ok) + + ntests=ntests+1 + end subroutine expect_bitstring_validation + + subroutine expect_failure_has_no_shared_state_side_effects() + character(len=77) :: c77 + logical :: ok + + call clear_all_state('','') + call encode_pack77_type1(10214965,0,12751800,0,0,32768,c77,ok) + + call assert_true('side-effect failure rejected',.not.ok) + call assert_shared_hash_tables_empty('schema failure') + + ntests=ntests+1 + end subroutine expect_failure_has_no_shared_state_side_effects + +end program test_packjt77_schema_encoder diff --git a/tests/unit/packjt77/test_packjt77_silent_rewrite_corpus.f90 b/tests/unit/packjt77/test_packjt77_silent_rewrite_corpus.f90 new file mode 100644 index 00000000..0fb12d82 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77_silent_rewrite_corpus.f90 @@ -0,0 +1,206 @@ +program test_packjt77_silent_rewrite_corpus + + use packjt77 + implicit none + + integer, parameter :: max_line=256 + character(len=max_line) :: corpus_path, arg, line, input, origin + character(len=37) :: decoded + character(len=77) :: c77 + integer :: unit, ios, sep, i3, n3 + integer :: total, exact, canon, reject, silent + logical :: success, assert_zero + + total=0 + exact=0 + canon=0 + reject=0 + silent=0 + assert_zero=.false. + + corpus_path='tests/unit/packjt77/silent_rewrite_corpus.txt' + if(command_argument_count().ge.1) call get_command_argument(1,corpus_path) + if(command_argument_count().ge.2) then + call get_command_argument(2,arg) + assert_zero=trim(arg).eq.'--assert-zero-silent' + endif + + open(newunit=unit,file=trim(corpus_path),status='old',action='read',iostat=ios) + if(ios.ne.0) then + write(*,1000) trim(corpus_path), ios +1000 format('failed to open silent-rewrite corpus "',a,'": ',i0) + error stop 1 + endif + + do + read(unit,'(a)',iostat=ios) line + if(ios.ne.0) exit + if(len_trim(line).eq.0) cycle + sep=index(line,'|') + if(sep.le.0) cycle + input=' ' + origin=' ' + input=adjustl(line(1:sep-1)) + origin=adjustl(line(sep+1:)) + call classify_case(trim(input),trim(origin),exact,canon,reject,silent) + total=total+1 + enddo + close(unit) + + write(*,1010) total, exact, canon, reject, silent +1010 format('SILENT_REWRITE_SUMMARY total=',i0,' exact=',i0,' canon=',i0, & + ' reject=',i0,' silent_rewrite=',i0) + if(assert_zero .and. silent.ne.0) error stop 1 + + ! Self-contained on purpose: this driver must also compile against older + ! source snapshots where shared grammar/test helper APIs may not exist. +contains + + subroutine classify_case(input_msg,origin,exact,canon,reject,silent) + character(len=*), intent(in) :: input_msg, origin + integer, intent(inout) :: exact, canon, reject, silent + character(len=37) :: packed_input + character(len=16) :: class + + packed_input=' ' + packed_input=input_msg + call reset_hash_state() + call pack77(packed_input,i3,n3,c77) + success=i3.ge.0 + if(.not.success) then + reject=reject+1 + class='REJECT' + call print_case(input_msg,origin,.false.,i3,n3,' ',class) + return + endif + + decoded=' ' + success=.false. + call reset_hash_state() + call unpack77(c77,0,decoded,success) + if(.not.success) then + silent=silent+1 + class='SILENT_REWRITE' + call print_case(input_msg,origin,.true.,i3,n3,decoded,class) + return + endif + + if(normalized_equal(input_msg,decoded)) then + exact=exact+1 + class='EXACT' + else if(canonical_match(input_msg,decoded)) then + canon=canon+1 + class='CANON' + else + silent=silent+1 + class='SILENT_REWRITE' + endif + call print_case(input_msg,origin,.true.,i3,n3,decoded,class) + end subroutine classify_case + + subroutine print_case(input_msg,origin,encoded,i3,n3,decoded_msg,class) + character(len=*), intent(in) :: input_msg, origin, decoded_msg, class + logical, intent(in) :: encoded + integer, intent(in) :: i3, n3 + + write(*,1020) trim(input_msg), trim(origin), encoded, i3, n3, & + trim(decoded_msg), trim(class) +1020 format(a,' | ',a,' | encoded=',l1,' | type=',i0,'.',i0, & + ' | decoded=',a,' | ',a) + end subroutine print_case + + logical function normalized_equal(left,right) result(equal) + character(len=*), intent(in) :: left, right + character(len=37) :: left_norm, right_norm + + call normalize_message(left,left_norm) + call normalize_message(right,right_norm) + equal=trim(left_norm).eq.trim(right_norm) + end function normalized_equal + + logical function canonical_match(left,right) result(matches) + character(len=*), intent(in) :: left, right + character(len=37) :: left_tokens(19), right_tokens(19), wrapped + integer :: left_n, right_n, i + + matches=.false. + call split_tokens(left,left_tokens,left_n) + call split_tokens(right,right_tokens,right_n) + if(left_n.ne.right_n) return + do i=1,left_n + if(trim(left_tokens(i)).eq.trim(right_tokens(i))) cycle + wrapped=' ' + wrapped='<'//trim(left_tokens(i))//'>' + if(trim(right_tokens(i)).eq.trim(wrapped)) cycle + if(trim(right_tokens(i)).eq.'<...>' .and. hash_like(left_tokens(i))) cycle + return + enddo + matches=.true. + end function canonical_match + + logical function hash_like(token) result(ok) + character(len=*), intent(in) :: token + integer :: n + + n=len_trim(token) + ok=.false. + if(n.le.0) return + ok=index(token(1:n),'/').gt.0 + if(n.ge.2) ok=ok .or. (token(1:1).eq.'<' .and. token(n:n).eq.'>') + end function hash_like + + subroutine normalize_message(input_msg,normalized) + character(len=*), intent(in) :: input_msg + character(len=37), intent(out) :: normalized + character(len=37) :: tokens(19) + integer :: nwords, i + + normalized=' ' + call split_tokens(input_msg,tokens,nwords) + do i=1,nwords + if(len_trim(normalized).gt.0) normalized=trim(normalized)//' ' + normalized=trim(normalized)//trim(tokens(i)) + enddo + end subroutine normalize_message + + subroutine split_tokens(input_msg,tokens,nwords) + character(len=*), intent(in) :: input_msg + character(len=37), intent(out) :: tokens(19) + integer, intent(out) :: nwords + character(len=1) :: c, previous + integer :: i, n + + tokens=' ' + nwords=0 + n=0 + previous=' ' + do i=1,len_trim(input_msg) + c=input_msg(i:i) + if(ichar(c).eq.0) c=' ' + if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) + if(c.eq.' ' .and. previous.eq.' ') cycle + if(c.ne.' ' .and. previous.eq.' ') then + nwords=nwords+1 + n=0 + if(nwords.gt.size(tokens)) return + endif + if(c.ne.' ') then + n=n+1 + if(n.le.len(tokens(1))) tokens(nwords)(n:n)=c + endif + previous=c + enddo + end subroutine split_tokens + + subroutine reset_hash_state() + calls10='' + calls12='' + calls22='' + recent_calls='' + ihash22=-1 + nzhash=0 + mycall13=' ' + dxcall13=' ' + end subroutine reset_hash_state + +end program test_packjt77_silent_rewrite_corpus diff --git a/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 b/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 new file mode 100644 index 00000000..d0ffac93 --- /dev/null +++ b/tests/unit/packjt77/test_packjt77sdvar_invariants.f90 @@ -0,0 +1,234 @@ +program test_packjt77sdvar_invariants + + use packjt77 + use packjt77_test_helpers + use ft8_mod1, only : idtone56_valid,idtone56,itone56,msg,lastrxmsg,mycall, & + hiscall,nlasttx,csyncsd_valid,csyncsdcq_valid + implicit none + + integer :: ntests + external :: genft8sdvar + external :: ft8sdvar + external :: ft8svar + external :: tonesdvar + + ntests=0 + + call expect_genft8sdvar_accepts_type1_template() + call expect_genft8sdvar_requires_expanded_dx_macro() + call expect_genft8sdvar_rejects_free_text_template() + call expect_invalid_sd_template_is_not_scored() + call expect_ft8svar_last_grid_template_is_valid() + call expect_failed_qso_template_invalidates_sync() + call expect_failed_cq_template_invalidates_sync() + call expect_genft8sdvar_rejects_hash_call_without_recording_hashes() + + write(*,1000) ntests +1000 format('packjt77 unified SD-var invariant tests passed: ',i0) + +contains + + subroutine expect_genft8sdvar_accepts_type1_template() + character(len=37) :: input, msgsent + integer :: i3, n3 + integer :: itone(79) + integer*1 :: msgbits(77) + + input='K1ABC W9XYZ RR73' + msgsent=' ' + msgbits=0 + itone=0 + i3=-1 + n3=-1 + + call genft8sdvar(input,i3,n3,msgsent,msgbits,itone) + + call assert_int('sdvar Type 1 template i3',1,i3) + call assert_int('sdvar Type 1 template n3',0,n3) + call assert_text_equal('sdvar Type 1 template decode','K1ABC W9XYZ RR73',msgsent) + call assert_true('sdvar Type 1 template message bits',any(msgbits.ne.0)) + call assert_true('sdvar Type 1 template tones',any(itone.ne.0)) + + ntests=ntests+1 + end subroutine expect_genft8sdvar_accepts_type1_template + + subroutine expect_genft8sdvar_requires_expanded_dx_macro() + character(len=37) :: input, direct, msgsent + integer :: i3, n3 + integer :: itone(79) + integer*1 :: msgbits(77) + + input='$DX K1ABC FN42' + direct='W9XYZ K1ABC FN42' + msgsent=' ' + msgbits=0 + itone=0 + i3=-1 + n3=-1 + + call genft8sdvar(input,i3,n3,msgsent,msgbits,itone) + + call assert_int('sdvar unexpanded DX macro i3',-1,i3) + call assert_int('sdvar unexpanded DX macro n3',-1,n3) + call assert_text_equal('sdvar unexpanded DX macro message', & + '*** bad message ***',msgsent) + call assert_true('sdvar unexpanded DX macro message bits', & + all(msgbits.eq.0)) + call assert_true('sdvar unexpanded DX macro tones',all(itone.eq.0)) + + call genft8sdvar(direct,i3,n3,msgsent,msgbits,itone) + + call assert_int('sdvar pre-expanded DX macro i3',1,i3) + call assert_int('sdvar pre-expanded DX macro n3',0,n3) + call assert_text_equal('sdvar pre-expanded DX macro decode',direct, & + msgsent) + call assert_true('sdvar pre-expanded DX macro message bits', & + any(msgbits.ne.0)) + call assert_true('sdvar pre-expanded DX macro tones',any(itone.ne.0)) + + ntests=ntests+1 + end subroutine expect_genft8sdvar_requires_expanded_dx_macro + + subroutine expect_invalid_sd_template_is_not_scored() + real :: s8(0:7,79) + integer :: itone(79) + character(len=37) :: msgd + character(len=37) :: msg37 + logical(1) :: lft8sd, lcq + + msgd='CQ PJ4/K1ABC' + s8=0.0 + s8(0,:)=1.0 + itone=-1 + msg37='' + lft8sd=.false. + lcq=.true. + + call ft8sdvar(s8,0.0,itone,msgd,msg37,lft8sd,lcq) + + call assert_true('invalid SD template not scored',.not.logical(lft8sd)) + call assert_text_equal('invalid SD template message unchanged','',msg37) + + ntests=ntests+1 + end subroutine expect_invalid_sd_template_is_not_scored + + subroutine expect_ft8svar_last_grid_template_is_valid() + real :: s8(0:7,79) + integer :: itone(79) + character(len=37) :: decoded + logical(1) :: lft8s + + call clear_all_state('','') + + mycall='N0AAA' + hiscall='W9XYZ' + nlasttx=1 + msg(53)='N0AAA W9XYZ AA00' + lastrxmsg(1)%lstate=.true. + lastrxmsg(1)%lastmsg='N0AAA W9XYZ FN42' + idtone56(53,1:58)=0 + itone56(53,1:79)=0 + idtone56_valid(53)=.false. + s8=0.0 + itone=0 + decoded='' + lft8s=.false. + + call ft8svar(s8,0.0,itone,decoded,lft8s,1,.false.) + + call assert_true('ft8svar last grid row valid',logical(idtone56_valid(53))) + call assert_text_equal('ft8svar last grid message', & + 'N0AAA W9XYZ FN42',msg(53)) + call assert_true('ft8svar last grid tones',any(itone56(53,1:79).ne.0)) + + ntests=ntests+1 + end subroutine expect_ft8svar_last_grid_template_is_valid + + subroutine expect_failed_qso_template_invalidates_sync() + character(len=37) :: msgd + + csyncsd_valid=.true. + msgd='<PJ4/K1ABC> W9XYZ -01' + + call tonesdvar(msgd,.false.) + + call assert_true('failed QSO template invalidates sync', & + .not.logical(csyncsd_valid)) + + ntests=ntests+1 + end subroutine expect_failed_qso_template_invalidates_sync + + subroutine expect_failed_cq_template_invalidates_sync() + character(len=37) :: msgd + + csyncsdcq_valid=.true. + msgd='CQ PJ4/K1ABC' + + call tonesdvar(msgd,.true.) + + call assert_true('failed CQ template invalidates sync', & + .not.logical(csyncsdcq_valid)) + + ntests=ntests+1 + end subroutine expect_failed_cq_template_invalidates_sync + + subroutine expect_genft8sdvar_rejects_free_text_template() + character(len=37) :: input, msgsent + integer :: i3, n3 + integer :: itone(79) + integer*1 :: msgbits(77) + + input='FREE TEXT MSG' + msgsent=' ' + msgbits=1 + itone=1 + i3=-1 + n3=-1 + + call genft8sdvar(input,i3,n3,msgsent,msgbits,itone) + + call assert_bad_sd_template('sdvar free-text template',i3,n3,msgsent,msgbits,itone) + + ntests=ntests+1 + end subroutine expect_genft8sdvar_rejects_free_text_template + + subroutine expect_genft8sdvar_rejects_hash_call_without_recording_hashes() + character(len=37) :: input, msgsent + integer :: i3, n3, itone(79) + integer*1 :: msgbits(77) + + call clear_all_state('','') + + input='<PJ4/K1ABC> W9XYZ RR73' + msgsent=' ' + msgbits=0 + itone=0 + i3=-1 + n3=-1 + + call genft8sdvar(input,i3,n3,msgsent,msgbits,itone) + + call assert_bad_sd_template('sdvar hash-call template',i3,n3,msgsent,msgbits,itone) + call assert_int('sdvar generator does not record nzhash',0,nzhash) + call assert_true('sdvar generator leaves calls10 empty',all(calls10.eq.'')) + call assert_true('sdvar generator leaves calls12 empty',all(calls12.eq.'')) + call assert_true('sdvar generator leaves calls22 empty',all(calls22.eq.'')) + call assert_true('sdvar generator leaves ihash22 empty',all(ihash22.eq.-1)) + + ntests=ntests+1 + end subroutine expect_genft8sdvar_rejects_hash_call_without_recording_hashes + + subroutine assert_bad_sd_template(label,i3,n3,msgsent,msgbits,itone) + character(len=*), intent(in) :: label + integer, intent(in) :: i3, n3, itone(79) + integer*1, intent(in) :: msgbits(77) + character(len=37), intent(in) :: msgsent + + call assert_int(trim(label)//' rejected i3',-1,i3) + call assert_int(trim(label)//' rejected n3',-1,n3) + call assert_text_equal(trim(label)//' rejected message','*** bad message ***',msgsent) + call assert_true(trim(label)//' zero message bits',all(msgbits.eq.0)) + call assert_true(trim(label)//' zero tones',all(itone.eq.0)) + end subroutine assert_bad_sd_template + +end program test_packjt77sdvar_invariants diff --git a/tests/unit/packjt77/test_packjt77var_invariants.f90 b/tests/unit/packjt77/test_packjt77var_invariants.f90 new file mode 100644 index 00000000..a2395c9c --- /dev/null +++ b/tests/unit/packjt77/test_packjt77var_invariants.f90 @@ -0,0 +1,93 @@ +program test_packjt77var_invariants + + use packjt77 + use packjt77_test_helpers + implicit none + + integer :: ntests + external :: genft8var + + ntests=0 + + call expect_genft8var_rejects_unexpanded_dx_macro() + call expect_configured_var_rejects_unqualified_hash_only_message() + + write(*,1000) ntests +1000 format('packjt77var invariant tests passed: ',i0) + +contains + + subroutine expect_genft8var_rejects_unexpanded_dx_macro() + character(len=37) :: input, direct, msgsent + integer :: i3, n3 + integer :: itone(79) + integer*1 :: msgbits(77) + + input='$DX K1ABC FN42' + direct='W9XYZ K1ABC FN42' + msgsent=' ' + msgbits=0 + itone=0 + i3=-1 + n3=-1 + + call genft8var(input,i3,n3,0,msgsent,msgbits,itone) + + call assert_int('var unexpanded DX macro i3',-1,i3) + call assert_int('var unexpanded DX macro n3',-1,n3) + call assert_text_equal('var unexpanded DX macro message', & + '*** bad message ***',msgsent) + call assert_true('var unexpanded DX macro message bits', & + all(msgbits.eq.0)) + call assert_true('var unexpanded DX macro tones',all(itone.eq.0)) + + call genft8var(direct,i3,n3,0,msgsent,msgbits,itone) + + call assert_int('var pre-expanded DX macro i3',1,i3) + call assert_int('var pre-expanded DX macro n3',0,n3) + call assert_text_equal('var pre-expanded DX macro decode',direct,msgsent) + call assert_true('var pre-expanded DX macro message bits', & + any(msgbits.ne.0)) + call assert_true('var pre-expanded DX macro tones',any(itone.ne.0)) + + ntests=ntests+1 + end subroutine expect_genft8var_rejects_unexpanded_dx_macro + + subroutine expect_configured_var_rejects_unqualified_hash_only_message() + character(len=77) :: c77 + character(len=13) :: c13 + character(len=37) :: decoded, input + integer :: n10, n12, n22 + logical :: ok + + input='PJ2/W1AW <W7ABC>' + call reset_packjt77var_state('N0AAA', 'N0BBB') + block + type(pack77_result) :: encoded + encoded=pack77_result_from_api(input) + call assert_pack77_result('configured-var delta',input,encoded) + call assert_int('configured-var delta i3',4,encoded%i3) + call assert_int('configured-var delta n3',0,encoded%n3) + c77=encoded%c77 + end block + + call reset_packjt77var_state('N0AAA', 'N0BBB') + call normalize_call('W7ABC',c13) + n10=ihashcall(c13,10) + n12=ihashcall(c13,12) + n22=ihashcall(c13,22) + call save_hash_call(c13,n10,n12,n22) + + decoded=' ' + ok=.true. + call unpack77_configured(c77,0,decoded,ok,unpack77_options(thread_index=1)) + if(ok) then + write(*,1010) trim(decoded) +1010 format('Configured-var hash-only delta decoded as "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_configured_var_rejects_unqualified_hash_only_message + +end program test_packjt77var_invariants diff --git a/tests/unit/q65/CMakeLists.txt b/tests/unit/q65/CMakeLists.txt new file mode 100644 index 00000000..698ea12d --- /dev/null +++ b/tests/unit/q65/CMakeLists.txt @@ -0,0 +1,35 @@ +add_executable (test_q65_workspace + test_q65_workspace.f90 + ${CMAKE_SOURCE_DIR}/lib/qra/q65/q65_workspace.f90) + +add_test (NAME test_q65_workspace COMMAND test_q65_workspace) + +add_executable (test_q65_source_encoding + test_q65_source_encoding.f90) +wsjt_link_common_fortran (test_q65_source_encoding) + +add_test (NAME test_q65_source_encoding COMMAND test_q65_source_encoding) + +add_executable (test_q65_decode_pipeline + q65_test_fixture.f90 + test_q65_decode_pipeline.f90) +set_source_files_properties (test_q65_decode_pipeline.f90 PROPERTIES + COMPILE_FLAGS "-Wno-unused-dummy-argument") +wsjt_link_common_fortran (test_q65_decode_pipeline) + +add_test (NAME test_q65_decode_pipeline COMMAND test_q65_decode_pipeline) +set_tests_properties (test_q65_decode_pipeline PROPERTIES + COST 10 + # Allow for hosted ARM emulation without leaving the test unbounded. + TIMEOUT 180) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_q65_decode_pipeline PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") +endif () + +add_executable (test_q65_llh_contracts + test_q65_llh_contracts.c) +target_include_directories (test_q65_llh_contracts PRIVATE + ${CMAKE_SOURCE_DIR}/lib/qra/q65) +target_link_libraries (test_q65_llh_contracts PRIVATE wsjt_cxx) +add_test (NAME test_q65_llh_contracts COMMAND test_q65_llh_contracts) diff --git a/tests/unit/q65/q65_test_fixture.f90 b/tests/unit/q65/q65_test_fixture.f90 new file mode 100644 index 00000000..9c3097b4 --- /dev/null +++ b/tests/unit/q65/q65_test_fixture.f90 @@ -0,0 +1,44 @@ +module q65_test_fixture + + use iso_fortran_env, only: int16 + implicit none + + integer, parameter :: q65_ntrperiod=60 + integer, parameter :: q65_nsamples=300*12000 + integer, parameter :: q65_nsymbols=85 + integer, parameter :: q65_tones(q65_nsymbols)=[ & + 0,3,28,56,36,21,7,6,0,10,56,0,0,1,0,41,26,35,54,33, & + 4,0,0,24,9,0,0,42,42,8,12,9,0,60,0,51,61,0,48,22, & + 22,10,46,60,20,0,5,3,4,0,11,41,23,5,0,54,47,56,1,0, & + 1,0,29,26,29,0,33,1,0,32,41,31,31,0,29,0,50,28,38,24, & + 33,30,41,10,0] + +contains + + subroutine make_q65_wave(iwave,nsubmode) + integer(int16), intent(out) :: iwave(:) + integer, intent(in) :: nsubmode + integer, parameter :: complex_rate=6000 + integer, parameter :: samples_per_symbol=3600 + integer, parameter :: leading_silence=complex_rate + real, parameter :: pi=3.14159265358979323846 + real, parameter :: amplitude=28000.0 + real :: phase,frequency,tone_spacing + integer :: symbol,sample,complex_sample + + iwave=0_int16 + phase=0.0 + tone_spacing=12000.0/7200.0*real(2**nsubmode) + do symbol=1,q65_nsymbols + frequency=1000.0+real(q65_tones(symbol))*tone_spacing + do sample=0,samples_per_symbol-1 + complex_sample=leading_silence+(symbol-1)*samples_per_symbol+sample + if(2*complex_sample+2.gt.size(iwave)) return + phase=phase+2.0*pi*frequency/real(complex_rate) + iwave(2*complex_sample+1)=int(nint(amplitude*cos(phase)),int16) + iwave(2*complex_sample+2)=int(nint(-amplitude*sin(phase)),int16) + enddo + enddo + end subroutine make_q65_wave + +end module q65_test_fixture diff --git a/tests/unit/q65/test_map65_polarization_score.f90 b/tests/unit/q65/test_map65_polarization_score.f90 new file mode 100644 index 00000000..9b4c1793 --- /dev/null +++ b/tests/unit/q65/test_map65_polarization_score.f90 @@ -0,0 +1,100 @@ +program test_map65_polarization_score + use iso_fortran_env, only: real64 + use map65_polarization_score_mod, only: generalized_polarization_score,polarization_matrix + implicit none + + real(real64), parameter :: pi=acos(-1.0_real64) + real(real64) :: angle,combine_angle,expected,g00,g01,g11,score + real(real64) :: projections(4),u0,u1 + logical :: valid + + projections=[3.0_real64,4.0_real64,5.0_real64,4.0_real64] + call polarization_matrix(projections,g00,g11,g01) + call assert_close(g00,3.0_real64,0.0_real64,'G00 reconstruction') + call assert_close(g11,5.0_real64,0.0_real64,'G11 reconstruction') + call assert_close(g01,0.0_real64,0.0_real64,'G01 reconstruction') + + call rank_one(22.5_real64,3.0_real64,g00,g11,g01) + call generalized_polarization_score(g00,g11,g01,1.0_real64,1.0_real64,0.0_real64, & + score,angle,combine_angle,valid) + if (.not.valid) error stop 'balanced background was rejected' + call assert_close(score,3.0_real64,1.0e-12_real64,'balanced rank-one score') + call assert_angle(angle,22.5_real64,1.0e-10_real64,'balanced physical angle') + call assert_angle(combine_angle,22.5_real64,1.0e-10_real64,'balanced combining angle') + expected=10.0_real64*log10(1.0_real64/cos(22.5_real64*pi/180.0_real64)**2) + call assert_close(expected,0.687693_real64,1.0e-6_real64,'worst-angle scalloping') + + call rank_one(30.0_real64,2.0_real64,g00,g11,g01) + call generalized_polarization_score(g00,g11,g01,4.0_real64,1.0_real64,0.0_real64, & + score,angle,combine_angle,valid) + u0=cos(30.0_real64*pi/180.0_real64) + u1=sin(30.0_real64*pi/180.0_real64) + expected=2.0_real64*(u0*u0/4.0_real64+u1*u1) + call assert_close(score,expected,1.0e-12_real64,'unequal-noise score') + call assert_angle(angle,30.0_real64,1.0e-10_real64,'unequal-noise physical angle') + call assert_angle(combine_angle,atan2(u1,u0/4.0_real64)*180.0_real64/pi, & + 1.0e-10_real64,'unequal-noise combining angle') + call rank_one(40.0_real64,1.7_real64,g00,g11,g01) + call generalized_polarization_score(g00,g11,g01,2.0_real64,3.0_real64,0.8_real64, & + score,angle,combine_angle,valid) + u0=cos(40.0_real64*pi/180.0_real64) + u1=sin(40.0_real64*pi/180.0_real64) + expected=1.7_real64*(3.0_real64*u0*u0-1.6_real64*u0*u1+2.0_real64*u1*u1)/5.36_real64 + call assert_close(score,expected,1.0e-12_real64,'correlated-noise score') + call assert_angle(angle,40.0_real64,1.0e-10_real64,'correlated-noise physical angle') + + call generalized_polarization_score(9.0_real64*g00,6.0_real64*g11, & + sqrt(54.0_real64)*g01,18.0_real64,18.0_real64,sqrt(54.0_real64)*0.8_real64, & + score,angle,combine_angle,valid) + call assert_close(score,expected,1.0e-11_real64,'receiver-gain invariance') + call assert_angle(angle,atan2(sqrt(6.0_real64)*u1,3.0_real64*u0)*180.0_real64/pi, & + 1.0e-10_real64,'receiver-gain physical angle') + + call generalized_polarization_score(g00,g11,g01,1.0_real64,1.0_real64,1.0_real64, & + score,angle,combine_angle,valid) + if (.not.valid) error stop 'singular background was rejected' + if (.not.(score >= 0.0_real64 .and. score < huge(score))) & + error stop 'regularized score was not finite' + + call generalized_polarization_score(g00,g11,g01,-1.0_real64,1.0_real64,0.0_real64, & + score,angle,combine_angle,valid) + if (valid) error stop 'invalid background was accepted' + + call generalized_polarization_score(g00,g11,g01,1.0_real64,1.0_real64,1.1_real64, & + score,angle,combine_angle,valid) + if (valid) error stop 'invalid background correlation was accepted' + +contains + + subroutine rank_one(degrees,amplitude,a00,a11,a01) + real(real64), intent(in) :: degrees,amplitude + real(real64), intent(out) :: a00,a11,a01 + real(real64) :: x,y + + x=cos(degrees*pi/180.0_real64) + y=sin(degrees*pi/180.0_real64) + a00=amplitude*x*x + a11=amplitude*y*y + a01=amplitude*x*y + end subroutine rank_one + + subroutine assert_close(actual,wanted,tolerance,label) + real(real64), intent(in) :: actual,wanted,tolerance + character(len=*), intent(in) :: label + + if (abs(actual-wanted) > tolerance) then + print '(a,2es24.15)', trim(label)//': ',actual,wanted + error stop 'numeric assertion failed' + endif + end subroutine assert_close + + subroutine assert_angle(actual,wanted,tolerance,label) + real(real64), intent(in) :: actual,wanted,tolerance + character(len=*), intent(in) :: label + real(real64) :: difference + + difference=abs(modulo(actual-wanted+90.0_real64,180.0_real64)-90.0_real64) + call assert_close(difference,0.0_real64,tolerance,label) + end subroutine assert_angle + +end program test_map65_polarization_score diff --git a/tests/unit/q65/test_map65_wideband_sync_rows.f90 b/tests/unit/q65/test_map65_wideband_sync_rows.f90 new file mode 100644 index 00000000..143f0c3a --- /dev/null +++ b/tests/unit/q65/test_map65_wideband_sync_rows.f90 @@ -0,0 +1,108 @@ +program test_map65_wideband_sync_rows + use wideband_sync, only: candidate,get_candidates,init_wideband_sync,outside_row_count,sync,wb_sync + use npar_ptrs_mod, only: nfft_active, nrate_active + implicit none + + integer, parameter :: jz=280, lag=11 + integer :: expanded_sync(22) + integer :: ia, ib, i, j, k, ncand, offset, peak(1), target_bin + real :: angle_error,ccf_before,df,response(4),xdt_before + real, allocatable :: savg(:,:), ss(:,:,:) + type(candidate) :: candidates(50) + logical :: found + + expanded_sync = [1,27,37,40,46,69,72,82,85,104,111,121,146,159,175,192, & + 198,211,221,237,243,272] + nrate_active=96000 + nfft_active=32768 + df=real(nrate_active)/real(nfft_active) + ia=nint(1000.0/df)+1 + ib=nint(2000.0/df)+1 + target_bin=(ia+ib)/2 + + allocate(ss(4,322,nfft_active),savg(4,nfft_active)) + ss=1.0 + savg=real(jz) + do i=ia,ib + do j=1,jz + ss(1,j,i)=1.0+0.001*real(mod(37*j+17*i,23)) + enddo + savg(1,i)=sum(ss(1,1:jz,i)) + enddo + + do j=1,size(expanded_sync) + k=expanded_sync(j)+lag + do offset=0,2 + if (k+offset <= jz) ss(1,k+offset,target_bin)= & + ss(1,k+offset,target_bin)+50.0 + enddo + enddo + savg(1,target_bin)=sum(ss(1,1:jz,target_bin)) + + call init_wideband_sync() + call wb_sync(ss,savg,.false.,.true.,jz,1,2) + peak=maxloc(sync(ia:ib)%ccfmax) + if (peak(1)+ia-1 /= target_bin) error stop 'late Q65 partial sync peak was not found' + if (sync(target_bin)%iflip /= 0) error stop 'late Q65 partial sync was misclassified' + if (abs(sync(target_bin)%xdt-(lag*2048.0/11025.0-1.0)) > 0.001) & + error stop 'late Q65 partial sync used the wrong lag' + + ccf_before=sync(target_bin)%ccfmax + xdt_before=sync(target_bin)%xdt + ss(1,jz+1:322,ia:ib)=1.0e20 + call wb_sync(ss,savg,.false.,.true.,jz,1,2) + + if (sync(target_bin)%ccfmax /= ccf_before) & + error stop 'unavailable spectrum rows changed Q65 sync strength' + if (sync(target_bin)%xdt /= xdt_before) & + error stop 'unavailable spectrum rows changed Q65 sync lag' + + if (outside_row_count(24,300,280) /= 24) & + error stop 'early Q65 carrier baseline used the wrong row count' + if (outside_row_count(-1,276,280) /= 5) & + error stop 'negative leading rows changed the carrier baseline count' + + do i=ia,ib + do j=1,jz + ss(:,j,i)=1.0+0.001*[real(mod(37*j+17*i,23)),real(mod(31*j+13*i,19)), & + real(mod(29*j+11*i,17)),real(mod(23*j+7*i,13))] + enddo + savg(:,i)=[sum(ss(1,1:jz,i)),sum(ss(2,1:jz,i)), & + sum(ss(3,1:jz,i)),sum(ss(4,1:jz,i))] + enddo + response=[cos(22.5*acos(-1.0)/180.0)**2,cos(-22.5*acos(-1.0)/180.0)**2, & + cos(-67.5*acos(-1.0)/180.0)**2,cos(-112.5*acos(-1.0)/180.0)**2] + do j=1,size(expanded_sync) + k=expanded_sync(j)+lag + do offset=0,2 + if (k+offset <= jz) ss(:,k+offset,target_bin)=ss(:,k+offset,target_bin)+50.0*response + enddo + enddo + do i=1,4 + savg(i,target_bin)=sum(ss(i,1:jz,target_bin)) + enddo + + call wb_sync(ss,savg,.true.,.false.,jz,1,2) + ccf_before=sync(target_bin)%ccfmax + call get_candidates(ss,savg,.true.,jz,1,2,0,1,candidates,ncand) + if (sync(target_bin)%ccfmax <= ccf_before) & + error stop 'continuous polarization did not improve the production Q65 score' + angle_error=abs(modulo(sync(target_bin)%pol-22.5+90.0,180.0)-90.0) + if (angle_error > 0.05) error stop 'continuous polarization recovered the wrong physical angle' + angle_error=abs(modulo(sync(target_bin)%combine_pol-22.5+90.0,180.0)-90.0) + if (angle_error > 0.05) error stop 'continuous polarization selected the wrong combining angle' + found=.false. + do i=1,ncand + if (candidates(i)%iflip == 0 .and. & + abs(candidates(i)%f-0.001*(target_bin-1)*df) < 0.0005*df) found=.true. + enddo + if (.not.found) error stop 'continuous polarization score did not reach Q65 candidate admission' + + savg(2,ia:ib)=4.0*real(jz) + savg(4,ia:ib)=0.0 + call wb_sync(ss,savg,.true.,.false.,jz,1,2) + ccf_before=sync(target_bin)%ccfmax + call get_candidates(ss,savg,.true.,jz,1,2,0,1,candidates,ncand) + if (sync(target_bin)%ccfmax /= ccf_before) & + error stop 'invalid covariance did not preserve the legacy Q65 score' +end program test_map65_wideband_sync_rows diff --git a/tests/unit/q65/test_q65_decode_pipeline.f90 b/tests/unit/q65/test_q65_decode_pipeline.f90 new file mode 100644 index 00000000..84b34dc0 --- /dev/null +++ b/tests/unit/q65/test_q65_decode_pipeline.f90 @@ -0,0 +1,209 @@ +module q65_pipeline_callback + + use q65_decode, only: q65_decoder + implicit none + + integer :: callback_count + integer :: callback_idec,callback_nused,callback_ntrperiod + integer :: callback_nutc,callback_nsnr + integer :: callback_iflagdec + real :: callback_snr1,callback_dt,callback_freq + character(len=37) :: callback_message + +contains + + + subroutine capture_callback(this,nutc,snr1,nsnr,dt,freq,decoded,idec, & + nused,ntrperiod,iflagdec) + class(q65_decoder), intent(inout) :: this + integer, intent(in) :: nutc,nsnr,idec,nused,ntrperiod,iflagdec + real, intent(in) :: snr1,dt,freq + character(len=37), intent(in) :: decoded + + callback_count=callback_count+1 + callback_nutc=nutc + callback_snr1=snr1 + callback_nsnr=nsnr + callback_dt=dt + callback_freq=freq + callback_message=decoded + callback_idec=idec + callback_nused=nused + callback_ntrperiod=ntrperiod + callback_iflagdec=iflagdec + end subroutine capture_callback + +end module q65_pipeline_callback + +program test_q65_decode_pipeline + + use iso_fortran_env, only: int16 + use map65_mmdec_mod, only: map65_mmdec + use q65_pipeline_callback + use prog_args, only: data_dir,temp_dir + use q65_decode, only: q65_decoder,cq0,msg0,nsnr0,nfreq0,xdt0 + use q65_test_fixture, only: make_q65_wave,q65_nsamples,q65_ntrperiod + use types, only: q3list + implicit none + + integer(int16), allocatable :: iwave(:) + integer, parameter :: map65_submodes(2)=[0,4] + integer :: nqf(20),navg0,nsubmode,isubmode + logical :: lclearave,single_decode,lagain,lnewdat,lapcqonly + type(q65_decoder) :: decoder + character(len=12) :: mycall,hiscall + character(len=6) :: hisgrid + + data_dir='.' + temp_dir='.' + mycall=' ' + hiscall=' ' + hisgrid=' ' + nqf=0 + navg0=0 + lclearave=.true. + single_decode=.true. + lagain=.false. + lnewdat=.false. + lapcqonly=.false. + call check_q65_ap_flag_masks() + allocate(iwave(q65_nsamples)) + + do nsubmode=0,4 + call make_q65_wave(iwave,nsubmode) + call run_direct_decode(decoder,iwave,nsubmode,1,want_iflagdec=0) + enddo + + ! The direct decoder loop owns exhaustive submode coverage. MAP65 is a thin + ! handoff, so exercise both ends of its forwarded submode range. + do isubmode=1,size(map65_submodes) + nsubmode=map65_submodes(isubmode) + call make_q65_wave(iwave,nsubmode) + call run_map65_decode(iwave,nsubmode,.true.) + enddo + + ! The wrapper's silent case also proves that the decoder emits no callback, + ! while additionally checking that no stale MAP65 state escapes. + iwave=0_int16 + call run_map65_decode(iwave,0,.false.) + + write(*,'(a)') 'Q65 raw decoder and MAP65 handoff tests passed' + +contains + + subroutine check_q65_ap_flag_masks() + integer :: apsym0(58),apmask(78),apsymbols(78),iaptype + integer :: codewords(63,411),ncw,j + character(len=12) :: list_mycall,list_hiscall + character(len=6) :: list_hisgrid + type(q3list) :: callers(50) + + apsym0=0 + call q65_ap(5,1,0,.false.,.false.,iaptype,apsym0,apmask,apsymbols) + if(iaptype.ne.3 .or. apmask(78).ne.1 .or. apsymbols(78).ne.0) then + error stop 'ordinary Q65 AP decoding changed bit 78 policy' + endif + + call q65_ap(5,1,1,.true.,.false.,iaptype,apsym0,apmask,apsymbols) + if(iaptype.ne.3 .or. apmask(78).ne.0) then + error stop 'Q65 Pileup AP decoding fixed bit 78 for call/grid messages' + endif + + list_mycall='K1ABC' + list_hiscall='W9XYZ' + list_hisgrid='FN42' + do j=1,40 + write(callers(j)%call,'(a2,i4.4)') 'K1',j + callers(j)%grid='FN42' + enddo + call q65_set_list2(list_mycall,list_hiscall,list_hisgrid,callers,40,codewords,ncw) + if(ncw.ne.411) error stop 'Q65 Pileup full AP list truncated at 40 callers' + end subroutine check_q65_ap_flag_masks + + subroutine run_direct_decode(decoder,samples,nsubmode,want_callback,want_iflagdec) + type(q65_decoder), intent(inout) :: decoder + integer(int16), intent(in) :: samples(:) + integer, intent(in) :: nsubmode,want_callback + integer, intent(in), optional :: want_iflagdec + logical :: want_success + + callback_count=0 + callback_message=' ' + callback_idec=-1 + callback_nused=-1 + callback_ntrperiod=-1 + callback_nutc=-1 + callback_nsnr=-999 + callback_snr1=0.0 + callback_dt=0.0 + callback_freq=0.0 + callback_iflagdec=-1 + want_success=want_callback.ne.0 + call decoder%decode(capture_callback,samples,1,100,q65_ntrperiod,nsubmode, & + 1000,150,3,850,1150,lclearave,single_decode,lagain,0,lnewdat,2.5, & + mycall,hiscall,hisgrid,0,0,.false.,lapcqonly,navg0,nqf) + if(want_success) then + if(callback_count.ne.1) error stop 'direct Q65 decode callback count changed' + if(trim(callback_message).ne.'K1ABC W9XYZ FN42') then + error stop 'direct Q65 decoder returned the wrong message' + endif + if(callback_idec.lt.0 .or. callback_ntrperiod.ne.q65_ntrperiod) then + error stop 'direct Q65 callback metadata changed' + endif + if(abs(callback_freq-1000.0).gt.8.0) error stop 'direct Q65 frequency changed' + if(abs(callback_dt).gt.0.15) error stop 'direct Q65 timing changed' + if(present(want_iflagdec)) then + if(callback_iflagdec.ne.want_iflagdec) then + error stop 'direct Q65 decode did not recover the expected flag bit' + endif + endif + else + if(callback_count.ne.0) error stop 'silent Q65 input produced a callback' + endif + end subroutine run_direct_decode + + subroutine run_map65_decode(samples,nsubmode,want_callback) + integer(int16), intent(in) :: samples(:) + integer, intent(in) :: nsubmode + logical, intent(in) :: want_callback + character(len=37) :: previous_message + integer :: nutc,nqd,nfa,nfb,nfqso,ntol,newdat,nagain,max_drift,ndepth + + nutc=100 + nqd=1 + nfa=850 + nfb=1150 + nfqso=1000 + ntol=150 + newdat=0 + nagain=1 + max_drift=0 + ndepth=3 + + nsnr0=-99 + nfreq0=-1 + xdt0=-99.0 + msg0=' ' + cq0=' ' + previous_message=msg0 + + call map65_mmdec(nutc,samples,nqd,q65_ntrperiod,nsubmode,nfa,nfb,nfqso, & + ntol,newdat,nagain,max_drift,ndepth,mycall,hiscall,hisgrid) + if(want_callback) then + if(nsnr0.le.-99) error stop 'MAP65 Q65 handoff missed a decode' + if(trim(msg0).ne.'K1ABC W9XYZ FN42') then + error stop 'MAP65 Q65 handoff returned the wrong message' + endif + if(cq0(1:2).ne.'q0') error stop 'MAP65 Q65 decode type changed' + if(abs(nfreq0-1000).gt.8) error stop 'MAP65 Q65 frequency changed' + if(abs(xdt0).gt.0.15) error stop 'MAP65 Q65 timing changed' + else + if(nsnr0.ne.-99 .or. nfreq0.ne.-1 .or. xdt0.ne.-99.0 .or. & + msg0.ne.previous_message .or. cq0.ne.' ') then + error stop 'MAP65 Q65 handoff exposed stale decode state' + endif + endif + end subroutine run_map65_decode + + +end program test_q65_decode_pipeline diff --git a/tests/unit/q65/test_q65_llh_contracts.c b/tests/unit/q65/test_q65_llh_contracts.c new file mode 100644 index 00000000..888674bd --- /dev/null +++ b/tests/unit/q65/test_q65_llh_contracts.c @@ -0,0 +1,42 @@ +#include "q65.h" + +#include <math.h> +#include <stdio.h> +#include <stdlib.h> + +static void require (int condition, char const * message) +{ + if (!condition) + { + fprintf (stderr, "FAIL: %s\n", message); + exit (1); + } +} + +int main (void) +{ + float intrinsics[64] = {0}; + int symbol = 0; + + for (int i = 0; i < 64; ++i) + intrinsics[i] = 1.0f; + + require (q65_check_llh (NULL, &symbol, 1, 64, intrinsics) == 1, + "valid codeword symbol rejected"); + + symbol = -1; + float llh = 123.0f; + require (q65_check_llh (&llh, &symbol, 1, 64, intrinsics) == 0, + "negative codeword symbol accepted"); + require (isinf (llh) && llh < 0.0f, + "invalid codeword symbol left LLH undefined"); + + symbol = 64; + llh = 123.0f; + require (q65_check_llh (&llh, &symbol, 1, 64, intrinsics) == 0, + "out-of-range codeword symbol accepted"); + require (isinf (llh) && llh < 0.0f, + "out-of-range codeword symbol left LLH undefined"); + + return 0; +} diff --git a/tests/unit/q65/test_q65_source_encoding.f90 b/tests/unit/q65/test_q65_source_encoding.f90 new file mode 100644 index 00000000..1b7eed2a --- /dev/null +++ b/tests/unit/q65/test_q65_source_encoding.f90 @@ -0,0 +1,194 @@ +program test_q65_source_encoding + + use q65_encoding, only: get_q65_tones + implicit none + + external :: genq65 + + integer :: ntests + + ntests=0 + + call expect_shared_vector('K1ABC W9XYZ FN42', & + [2,27,55,35,20,6,5,9,55,0,40,25,34,53,28,53,32,3,23,8, & + 41,41,7,11,8,59,50,60,47,21,21,9,45,59,19,4,2,3,10,40, & + 22,4,53,46,55,0,0,28,25,28,32,0,31,40,30,30,28,49,27,37, & + 23,32,29,40,9], & + [0,3,28,56,36,21,7,6,0,10,56,0,0,1,0,41,26,35,54,33, & + 4,0,0,24,9,0,0,42,42,8,12,9,0,60,0,51,61,0,48,22, & + 22,10,46,60,20,0,5,3,4,0,11,41,23,5,0,54,47,56,1,0, & + 1,0,29,26,29,0,33,1,0,32,41,31,31,0,29,0,50,28,38,24, & + 33,30,41,10,0]) + + call expect_shared_vector('K1ABC W9XYZ RR73', & + [2,27,55,35,20,6,5,9,55,1,62,36,50,51,52,51,38,5,17,14, & + 50,51,39,19,16,35,42,36,4,62,46,52,16,6,56,47,41,40,7,53, & + 11,25,40,51,23,32,1,53,48,53,41,9,29,20,34,18,16,57,19,45, & + 13,58,55,2,35], & + [0,3,28,56,36,21,7,6,0,10,56,0,0,2,0,63,37,51,52,39, & + 6,0,0,18,15,0,0,51,52,40,20,17,0,36,0,43,37,0,5,63, & + 47,53,17,7,57,0,48,42,41,0,8,54,12,26,0,41,52,24,33,0, & + 2,0,54,49,54,0,42,10,0,30,21,35,19,0,17,0,58,20,46,14, & + 59,56,3,36,0]) + + call expect_legacy_vector('K1ABC W9XYZ FN42', & + [0,3,28,56,36,21,7,6,0,10,56,0,0,1,0,41,26,35,54,33, & + 4,0,0,24,9,0,0,42,42,8,12,9,0,60,0,51,61,0,48,22, & + 22,10,46,60,20,0,5,3,4,0,11,41,23,5,0,54,47,56,1,0, & + 1,0,29,26,29,0,33,1,0,32,41,31,31,0,29,0,50,28,38,24, & + 33,30,41,10,0]) + + call expect_legacy_vector('K1ABC W9XYZ RR73', & + [0,3,28,56,36,21,7,6,0,10,56,0,0,2,0,63,37,51,52,39, & + 6,0,0,18,15,0,0,51,52,40,20,17,0,36,0,43,37,0,5,63, & + 47,53,17,7,57,0,48,42,41,0,8,54,12,26,0,41,52,24,33,0, & + 2,0,54,49,54,0,42,10,0,30,21,35,19,0,17,0,58,20,46,14, & + 59,56,3,36,0]) + + call expect_legacy_vector_flagged('K1ABC W9XYZ FN42', & + [0,3,28,56,36,21,7,6,0,10,56,0,0,1,0,41,26,36,29,10, & + 43,0,0,63,34,0,0,45,45,57,53,56,0,5,0,14,4,0,17,43, & + 43,63,27,13,37,0,52,54,53,0,48,13,51,33,0,18,11,20,37,0, & + 37,0,17,22,17,0,24,56,0,14,59,13,13,0,15,0,36,10,56,24, & + 33,30,41,10,0]) + + call expect_invalid_shared_message() + call expect_invalid_legacy_message() + + write(*,'(a,i0)') 'Q65 source encoding tests passed: ', ntests + +contains + + subroutine expect_shared_vector(input,want_codeword,want_tones) + character(len=*), intent(in) :: input + integer, intent(in) :: want_codeword(65), want_tones(85) + character(len=37) :: msg37,msgsent,want_msg + integer :: codeword(65), itone(85) + integer :: sync(22),i,k + logical :: success + + msg37=' ' + msg37=input + want_msg=' ' + want_msg=input + call get_q65_tones(msg37,codeword,itone,msgsent,success) + if(.not.success) error stop 'shared Q65 encoder rejected a vector' + call assert_message('shared Q65 encoder',msgsent,want_msg) + call assert_vector('shared Q65 codeword',codeword,want_codeword) + call assert_vector('shared Q65 tones',itone,want_tones) + + sync=[1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85] + k=0 + do i=1,85 + if(any(sync.eq.i)) then + if(itone(i).ne.0) error stop 'Q65 sync tone is not zero' + else + k=k+1 + if(itone(i).ne.want_codeword(merge(k,k+2,k.le.13))+1) then + error stop 'Q65 tone does not match shortened codeword' + endif + endif + enddo + if(k.ne.63) error stop 'Q65 shortened codeword length changed' + + ntests=ntests+1 + end subroutine expect_shared_vector + + subroutine expect_legacy_vector(input,want_tones) + character(len=*), intent(in) :: input + integer, intent(in) :: want_tones(85) + character(len=37) :: msg37,msgsent,want_msg + integer :: itone(85),i3,n3 + + msg37=' ' + msg37=input + want_msg=' ' + want_msg=input + itone=-1 + i3=-1 + n3=-1 + call genq65(msg37,0,msgsent,itone,i3,n3,0) + if(i3.lt.0 .or. n3.lt.0) error stop 'legacy Q65 encoder rejected a vector' + call assert_message('legacy Q65 encoder',msgsent,want_msg) + call assert_vector('legacy Q65 tones',itone,want_tones) + ntests=ntests+1 + end subroutine expect_legacy_vector + + subroutine expect_legacy_vector_flagged(input,want_tones) + ! Same as expect_legacy_vector, but with iflag=1 (the spare 78th bit + ! set) -- verifies the bit actually reaches the transmitted symbols, + ! and that it's the *only* difference from the unflagged encoding + ! (bar the accumulator's cascade through later symbols, expected of + ! a repeat-accumulate code). + character(len=*), intent(in) :: input + integer, intent(in) :: want_tones(85) + character(len=37) :: msg37,msgsent,want_msg + integer :: itone(85),i3,n3 + + msg37=' ' + msg37=input + want_msg=' ' + want_msg=input + itone=-1 + i3=-1 + n3=-1 + call genq65(msg37,0,msgsent,itone,i3,n3,1) + if(i3.lt.0 .or. n3.lt.0) error stop 'flagged Q65 encoder rejected a vector' + call assert_message('flagged Q65 encoder',msgsent,want_msg) + call assert_vector('flagged Q65 tones',itone,want_tones) + ntests=ntests+1 + end subroutine expect_legacy_vector_flagged + + subroutine expect_invalid_shared_message() + character(len=37) :: msg37,msgsent + integer :: codeword(65),itone(85) + logical :: success + + msg37='HELLO@WORLD' + call get_q65_tones(msg37,codeword,itone,msgsent,success) + if(success) error stop 'shared Q65 encoder accepted invalid input' + call assert_message('shared Q65 invalid message',msgsent, & + '*** bad message *** ') + if(any(codeword.ne.0) .or. any(itone.ne.0)) then + error stop 'shared Q65 invalid output was not cleared' + endif + ntests=ntests+1 + end subroutine expect_invalid_shared_message + + subroutine expect_invalid_legacy_message() + character(len=37) :: msg37,msgsent + integer :: itone(85),i3,n3 + + msg37='HELLO@WORLD' + call genq65(msg37,0,msgsent,itone,i3,n3,0) + if(i3.ne.-1 .or. n3.ne.-1) error stop 'legacy Q65 encoder accepted invalid input' + call assert_message('legacy Q65 invalid message',msgsent, & + '*** bad message *** ') + if(any(itone.ne.0)) error stop 'legacy Q65 invalid tones were not cleared' + ntests=ntests+1 + end subroutine expect_invalid_legacy_message + + subroutine assert_message(label,got,want) + character(len=*), intent(in) :: label,got,want + if(got.ne.want) then + write(*,'(a,": got [",a,"] wanted [",a,"]")') trim(label),got,want + error stop 1 + endif + end subroutine assert_message + + subroutine assert_vector(label,got,want) + character(len=*), intent(in) :: label + integer, intent(in) :: got(:),want(:) + integer :: i + + if(size(got).ne.size(want)) error stop 'vector size changed' + do i=1,size(got) + if(got(i).ne.want(i)) then + write(*,'(a,": index ",i0,": got ",i0," wanted ",i0)') & + trim(label),i,got(i),want(i) + error stop 1 + endif + enddo + end subroutine assert_vector + +end program test_q65_source_encoding diff --git a/tests/unit/q65/test_q65_waveform_generator.f90 b/tests/unit/q65/test_q65_waveform_generator.f90 new file mode 100644 index 00000000..b97fef13 --- /dev/null +++ b/tests/unit/q65/test_q65_waveform_generator.f90 @@ -0,0 +1,163 @@ +program test_q65_waveform_generator + + use iso_fortran_env, only: real32, real64 + use, intrinsic :: ieee_arithmetic, only: ieee_is_finite + use cgen65_mod, only: cgen65 + use gen_q65_cwave_mod, only: gen_q65_cwave + implicit none + + external :: gen_q65_wave + + integer, parameter :: sample_rate = 96000 + integer, parameter :: waveform_capacity = 60 * sample_rate + real(real64), parameter :: pi = 3.1415926535897932384626433832795_real64 + real(real64), parameter :: q65_symbol_duration = 7200.0_real64 / 12000.0_real64 + real(real64), parameter :: jt65_base_frequency = 118.0_real64 * 11025.0_real64 / 1024.0_real64 + + complex, allocatable :: q65_wave(:), jt65_wave(:) + integer*2, allocatable :: legacy_q65_wave(:) + + allocate(q65_wave(waveform_capacity), jt65_wave(waveform_capacity)) + allocate(legacy_q65_wave(2 * 60 * 11025)) + call test_q65_complex_wave(q65_wave, 1) + call test_q65_complex_wave(q65_wave, 2) + call test_q65_invalid_message(q65_wave) + call test_q65_legacy_wave(legacy_q65_wave) + call test_jt65_complex_wave(jt65_wave) + print '(a)', 'Q65 waveform generator tests passed' + +contains + + subroutine require(condition, description) + logical, intent(in) :: condition + character(len=*), intent(in) :: description + + if (.not. condition) then + print '(a)', 'FAIL: '//description + error stop 1 + end if + end subroutine require + + subroutine test_q65_complex_wave(waveform, tone_spacing) + complex, intent(inout) :: waveform(:) + integer, intent(in) :: tone_spacing + character(len=24) :: message, msgsent + integer :: nwave, expected_nwave, sample + real(real64) :: fsample, expected_frequency, measured_frequency + complex :: step + + fsample = real(sample_rate, real64) + message = 'K1ABC W9XYZ FN42' + waveform = cmplx(0.0_real32, 0.0_real32) + + call gen_q65_cwave(message, 1000, tone_spacing, fsample, msgsent, waveform, nwave) + + expected_nwave = int(85.0_real64 * q65_symbol_duration * fsample + 0.5_real64) + call require(nwave == expected_nwave, 'Q65 waveform length') + call require(trim(msgsent) == trim(message), 'Q65 generated message') + call require(all(ieee_is_finite(real(waveform(1:nwave)))), 'Q65 real samples are finite') + call require(all(ieee_is_finite(aimag(waveform(1:nwave)))), 'Q65 imaginary samples are finite') + call require(maxval(abs(abs(waveform(1:nwave)) - 1.0)) < 1.0e-5, & + 'Q65 complex envelope is constant') + + step = waveform(1) + call require(abs(real(step) - real(cos(2.0_real64*pi*1000.0_real64/fsample), real32)) < 1.0e-5, & + 'Q65 I orientation') + call require(abs(aimag(step) + real(sin(2.0_real64*pi*1000.0_real64/fsample), real32)) < 1.0e-5, & + 'Q65 Q orientation') + + sample = int(q65_symbol_duration * fsample) + 1000 + step = conjg(waveform(sample)) * waveform(sample + 1) + measured_frequency = -atan2(real(aimag(step), real64), real(real(step), real64)) * & + fsample / (2.0_real64*pi) + expected_frequency = 1000.0_real64 + 3.0_real64 * tone_spacing * 12000.0_real64 / 7200.0_real64 + call require(abs(measured_frequency - expected_frequency) < 0.2_real64, & + 'Q65 tone spacing') + call require_phase_steps(waveform, nwave - 1, 'Q65') + end subroutine test_q65_complex_wave + + subroutine test_q65_invalid_message(waveform) + complex, intent(inout) :: waveform(:) + character(len=24) :: message, msgsent + integer :: nwave + + message = 'HELLO@WORLD' + waveform = cmplx(1.0_real32, 1.0_real32) + call gen_q65_cwave(message, 1000, 1, real(sample_rate, real64), msgsent, waveform, nwave) + + call require(nwave == 0, 'invalid Q65 waveform length') + call require(trim(msgsent) == '*** bad message ***', 'invalid Q65 generated message') + call require(all(waveform == cmplx(0.0_real32, 0.0_real32)), 'invalid Q65 output is cleared') + end subroutine test_q65_invalid_message + + subroutine test_q65_legacy_wave(waveform) + integer*2, intent(inout) :: waveform(:) + character(len=22) :: message, msgsent + integer :: nwave, expected_nwave, sample + real(real64) :: envelope + + message = 'K1ABC W9XYZ FN42' + waveform = 0 + call gen_q65_wave(message, 1000, 1, msgsent, waveform, nwave) + + expected_nwave = 2 * int(85.0_real64 * q65_symbol_duration * 11025.0_real64 + 0.5_real64) + call require(nwave == expected_nwave, 'legacy Q65 waveform length') + call require(trim(msgsent) == trim(message), 'legacy Q65 generated message') + do sample = 1, nwave, 2 + envelope = sqrt(real(waveform(sample), real64)**2 + & + real(waveform(sample + 1), real64)**2) + call require(abs(envelope - 32767.0_real64) < 2.0_real64, & + 'legacy Q65 I/Q envelope stays constant') + end do + call require(abs(real(waveform(1)) - real(32767.0_real64 * & + cos(2.0_real64*pi*1000.0_real64/11025.0_real64), real32)) < 1.0, & + 'legacy Q65 I orientation') + call require(abs(real(waveform(2)) - real(32767.0_real64 * & + sin(2.0_real64*pi*1000.0_real64/11025.0_real64), real32)) < 1.0, & + 'legacy Q65 Q orientation') + end subroutine test_q65_legacy_wave + + subroutine test_jt65_complex_wave(waveform) + complex, intent(inout) :: waveform(:) + character(len=22) :: message, msgsent + integer :: nsendingsh, nwave, ndata + real(real64) :: samfac + complex :: step + + message = 'K1ABC W9XYZ FN42' + samfac = 1.0_real64 + waveform = cmplx(0.0_real32, 0.0_real32) + call cgen65(message, 1, samfac, nsendingsh, msgsent, waveform, nwave) + + ndata = int(126.0_real64 * real(sample_rate, real64) * samfac * 4096.0_real64 / 11025.0_real64) + call require(nsendingsh == 0, 'JT65 normal message shorthand flag') + call require(trim(msgsent) == trim(message), 'JT65 generated message') + call require(nwave == ndata + 48000, 'JT65 waveform length') + call require(all(ieee_is_finite(real(waveform(1:nwave)))), 'JT65 real samples are finite') + call require(all(ieee_is_finite(aimag(waveform(1:nwave)))), 'JT65 imaginary samples are finite') + call require(all(abs(waveform(ndata+1:nwave)) < 1.0e-5), 'JT65 padding is silent') + + step = waveform(1) + call require(abs(real(step) - real(cos(2.0_real64*pi*jt65_base_frequency/sample_rate), real32)) < 1.0e-5, & + 'JT65 I orientation') + call require(abs(aimag(step) + real(sin(2.0_real64*pi*jt65_base_frequency/sample_rate), real32)) < 1.0e-5, & + 'JT65 Q orientation') + call require_phase_steps(waveform, ndata - 1, 'JT65') + end subroutine test_jt65_complex_wave + + subroutine require_phase_steps(waveform, last_sample, description) + complex, intent(in) :: waveform(:) + integer, intent(in) :: last_sample + character(len=*), intent(in) :: description + complex :: step + real(real64) :: phase_step + integer :: sample + + do sample = 1, last_sample + step = conjg(waveform(sample)) * waveform(sample + 1) + phase_step = atan2(real(aimag(step), real64), real(real(step), real64)) + call require(abs(phase_step) < 0.25_real64, description//' phase step stays bounded') + end do + end subroutine require_phase_steps + +end program test_q65_waveform_generator diff --git a/tests/unit/q65/test_q65_workspace.f90 b/tests/unit/q65/test_q65_workspace.f90 new file mode 100644 index 00000000..3a0421bb --- /dev/null +++ b/tests/unit/q65/test_q65_workspace.f90 @@ -0,0 +1,44 @@ +program test_q65_workspace + + use q65_workspace, only: Q65_MAXFFT, Q65_NN, q65_workspace_type + + implicit none + + integer, parameter :: npts2=400 + integer, parameter :: ll=256 + type(q65_workspace_type) :: workspace + + call workspace%ensure(npts2,ll) + call assert_workspace_sizes(workspace,npts2,ll) + + workspace%c0(0)=cmplx(3.0,4.0) + workspace%s3(1)=7.0 + workspace%cs(0)=cmplx(5.0,6.0) + + call workspace%ensure(npts2/2,ll/2) + call assert_workspace_sizes(workspace,npts2/2,ll/2) + if(workspace%c0(0).ne.cmplx(3.0,4.0)) error stop 'c0 was reallocated' + if(workspace%s3(1).ne.7.0) error stop 's3 was reallocated' + if(workspace%cs(0).ne.cmplx(5.0,6.0)) error stop 'cs was reallocated' + + call workspace%ensure(2*npts2,2*ll) + call assert_workspace_sizes(workspace,2*npts2,2*ll) + +contains + + subroutine assert_workspace_sizes(workspace,npts2,ll) + type(q65_workspace_type), intent(in) :: workspace + integer, intent(in) :: npts2,ll + + if(.not.allocated(workspace%c0)) error stop 'c0 is not allocated' + if(.not.allocated(workspace%s3)) error stop 's3 is not allocated' + if(.not.allocated(workspace%cs)) error stop 'cs is not allocated' + if(lbound(workspace%c0,1).ne.0) error stop 'c0 lower bound changed' + if(lbound(workspace%cs,1).ne.0) error stop 'cs lower bound changed' + if(lbound(workspace%s3,1).ne.1) error stop 's3 lower bound changed' + if(size(workspace%c0).lt.npts2) error stop 'c0 capacity is too small' + if(size(workspace%s3).lt.ll*Q65_NN) error stop 's3 capacity is too small' + if(size(workspace%cs).ne.Q65_MAXFFT) error stop 'cs size changed' + end subroutine assert_workspace_sizes + +end program test_q65_workspace diff --git a/tests/unit/q65/test_q65code.cmake b/tests/unit/q65/test_q65code.cmake new file mode 100644 index 00000000..cfbb9939 --- /dev/null +++ b/tests/unit/q65/test_q65code.cmake @@ -0,0 +1,25 @@ +execute_process( + COMMAND "${Q65CODE}" "THIS FREE TEXT IS TOO LONG" + RESULT_VARIABLE fallback_result + OUTPUT_VARIABLE fallback_output + ERROR_VARIABLE fallback_error +) +if (NOT fallback_result EQUAL 0) + message(FATAL_ERROR "Legacy fallback failed (${fallback_result}):\n${fallback_output}${fallback_error}") +endif () +if (NOT fallback_output MATCHES "Message sent:[ ]+THIS FREE TEX") + message(FATAL_ERROR "Fallback output was unexpected:\n${fallback_output}") +endif () + +execute_process( + COMMAND "${Q65CODE}" "HELLO@WORLD" + RESULT_VARIABLE rejected_result + OUTPUT_VARIABLE rejected_output + ERROR_VARIABLE rejected_error +) +if (rejected_result EQUAL 0) + message(FATAL_ERROR "Unrepresentable message returned success:\n${rejected_output}") +endif () +if (NOT rejected_output MATCHES "Cannot encode message:[ ]+HELLO@WORLD") + message(FATAL_ERROR "Rejected message output was unexpected:\n${rejected_output}${rejected_error}") +endif () diff --git a/tests/unit/qmap/CMakeLists.txt b/tests/unit/qmap/CMakeLists.txt new file mode 100644 index 00000000..0d0b73ac --- /dev/null +++ b/tests/unit/qmap/CMakeLists.txt @@ -0,0 +1,45 @@ +add_executable (test_qmap_livecq_parser + test_livecq_parser.cpp + ${CMAKE_SOURCE_DIR}/qmap/livecq_parser.cpp + ${CMAKE_SOURCE_DIR}/validators/LiveCQCallsign.cpp +) +target_link_libraries (test_qmap_livecq_parser Qt5::Test) +add_test (NAME test_qmap_livecq_parser COMMAND test_qmap_livecq_parser) + +add_executable (test_qmap_plotter_initialization + test_plotter_initialization.cpp + ${CMAKE_SOURCE_DIR}/qmap/decode_click_coalescer.cpp + ${CMAKE_SOURCE_DIR}/qmap/plotter.cpp +) +target_link_libraries (test_qmap_plotter_initialization + wsjt_qt + qmap_impl + ${FFTW3_LIBRARIES} + Qt5::Test + Qt5::Widgets +) +add_test (NAME test_qmap_plotter_initialization COMMAND test_qmap_plotter_initialization) +if (WIN32) + set_tests_properties (test_qmap_plotter_initialization PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=windows" + ) +else () + set_tests_properties (test_qmap_plotter_initialization PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" + ) +endif () + +add_executable (test_qmap_ipc test_qmap_ipc.cpp) +target_link_libraries (test_qmap_ipc Qt5::Test) +add_test (NAME test_qmap_ipc COMMAND test_qmap_ipc) + +add_executable (test_qmap_decode_record test_qmap_decode_record.cpp) +target_link_libraries (test_qmap_decode_record wsjt_qt wsjt_fort_common Qt5::Test) +add_test (NAME test_qmap_decode_record COMMAND test_qmap_decode_record) + +add_executable (test_qmap_decode_click_coalescer + test_decode_click_coalescer.cpp + ${CMAKE_SOURCE_DIR}/qmap/decode_click_coalescer.cpp +) +target_link_libraries (test_qmap_decode_click_coalescer Qt5::Test Qt5::Widgets) +add_test (NAME test_qmap_decode_click_coalescer COMMAND test_qmap_decode_click_coalescer) diff --git a/tests/unit/qmap/test_decode_click_coalescer.cpp b/tests/unit/qmap/test_decode_click_coalescer.cpp new file mode 100644 index 00000000..284aa5e5 --- /dev/null +++ b/tests/unit/qmap/test_decode_click_coalescer.cpp @@ -0,0 +1,95 @@ +#include <QtTest> + +#include "qmap/decode_click_coalescer.h" +#include "qmap/qmap_click_policy.h" + +class TestDecodeClickCoalescer final : public QObject +{ + Q_OBJECT + +private slots: + void disarmsBeforeSingleClick(); + void coalescesUpdatedRecordByIdentity(); + void keepsDifferentRecordsSeparate(); + void protectsDoubleClickWhenDisarmIsOverwritten(); +}; + +namespace +{ + struct DispatchEvent + { + QByteArray row; + DecodeClickGesture gesture; + }; +} + +void TestDecodeClickCoalescer::disarmsBeforeSingleClick() +{ + QList<DispatchEvent> dispatched; + DecodeClickCoalescer coalescer {this, [&dispatched] (QByteArray const& row, + DecodeClickGesture gesture) { + dispatched.append ({row, gesture}); + }, 20}; + + coalescer.press ("K1ABC", "first"); + QCOMPARE (dispatched.size (), 1); + QVERIFY (dispatched.first ().gesture == DecodeClickGesture::Press); + QTRY_COMPARE_WITH_TIMEOUT (dispatched.size (), 2, 100); + QCOMPARE (dispatched.last ().row, QByteArray {"first"}); + QVERIFY (dispatched.last ().gesture == DecodeClickGesture::SingleClick); +} + +void TestDecodeClickCoalescer::coalescesUpdatedRecordByIdentity() +{ + QList<DispatchEvent> dispatched; + DecodeClickCoalescer coalescer {this, [&dispatched] (QByteArray const& row, + DecodeClickGesture gesture) { + dispatched.append ({row, gesture}); + }, 20}; + + coalescer.press ("K1ABC", "old record"); + coalescer.doubleClick ("K1ABC", "new record"); + QCOMPARE (dispatched.size (), 2); + QCOMPARE (dispatched.last ().row, QByteArray {"new record"}); + QVERIFY (dispatched.last ().gesture == DecodeClickGesture::DoubleClick); + QTest::qWait (30); + QCOMPARE (dispatched.size (), 2); +} + +void TestDecodeClickCoalescer::keepsDifferentRecordsSeparate() +{ + QList<DispatchEvent> dispatched; + DecodeClickCoalescer coalescer {this, [&dispatched] (QByteArray const& row, + DecodeClickGesture gesture) { + dispatched.append ({row, gesture}); + }, 20}; + + coalescer.press ("K1ABC", "first"); + coalescer.press ("K2XYZ", "second"); + QCOMPARE (dispatched.size (), 3); + QCOMPARE (dispatched.at (1).row, QByteArray {"first"}); + QVERIFY (dispatched.at (1).gesture == DecodeClickGesture::SingleClick); + QVERIFY (dispatched.last ().gesture == DecodeClickGesture::Press); + QTRY_COMPARE_WITH_TIMEOUT (dispatched.size (), 4, 100); + QCOMPARE (dispatched.last ().row, QByteArray {"second"}); + QVERIFY (dispatched.last ().gesture == DecodeClickGesture::SingleClick); +} + +void TestDecodeClickCoalescer::protectsDoubleClickWhenDisarmIsOverwritten() +{ + auto const failedDoubleClick = qmapClickPolicy (true, false, true, true); + QVERIFY (failedDoubleClick.disarmBeforeQsy); + QVERIFY (!failedDoubleClick.enableAutoTx); + QVERIFY (!failedDoubleClick.restartTransmission); + + auto const acceptedDoubleClick = qmapClickPolicy (true, true, false, true); + QVERIFY (acceptedDoubleClick.enableAutoTx); + QVERIFY (acceptedDoubleClick.restartTransmission); + + auto const failedSingleClick = qmapClickPolicy (false, false, true, false); + QVERIFY (failedSingleClick.disableAutoTx); +} + +QTEST_GUILESS_MAIN (TestDecodeClickCoalescer) + +#include "test_decode_click_coalescer.moc" diff --git a/tests/unit/qmap/test_livecq_parser.cpp b/tests/unit/qmap/test_livecq_parser.cpp new file mode 100644 index 00000000..4f0ff9ea --- /dev/null +++ b/tests/unit/qmap/test_livecq_parser.cpp @@ -0,0 +1,84 @@ +#include <QtTest> + +#include "qmap/livecq_parser.h" + +class TestQMapLiveCQParser final : public QObject +{ + Q_OBJECT + +private slots: + void parsesSupportedLayouts() + { + QMapLiveCQ::Record record; + QVERIFY(QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L", "1200.0"}, + 100, record)); + QCOMPARE(record.callsign, QString {"N5L"}); + QCOMPARE(record.grid, QString {"--"}); + QCOMPARE(record.message, QString {"CQ N5L"}); + QCOMPARE(record.receiveFrequency, 100); + QCOMPARE(record.scheduledFrequency, 1200); + + QVERIFY(QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L", "FN20", "1200.0"}, + 100, record)); + QCOMPARE(record.grid, QString {"FN20"}); + QCOMPARE(record.message, QString {"CQ N5L FN20"}); + + QVERIFY(QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "DX", "N5L", "1200.0"}, + 100, record)); + QCOMPARE(record.callsign, QString {"N5L"}); + QCOMPARE(record.grid, QString {"--"}); + QCOMPARE(record.message, QString {"CQ N5L"}); + + QVERIFY(QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "DX", "N5L", "FN20", "1200.0"}, + 100, record)); + QCOMPARE(record.grid, QString {"FN20"}); + QCOMPARE(record.message, QString {"CQ N5L FN20"}); + } + + void parsesHighFrequencyFraction() + { + QMapLiveCQ::Record record; + QVERIFY(QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L", "1200.750"}, + 100, record)); + QCOMPARE(record.receiveFrequency, -150); + QCOMPARE(record.scheduledFrequency, 1201); + } + + void rejectsMalformedRecordsBeforeIndexing() + { + QMapLiveCQ::Record record; + for (auto const& tokens : { + QStringList {}, + QStringList {"123456", "-10", "0.1", "1234", "-12", "60", "CQ"}, + QStringList {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L"}, + QStringList {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L", "FN20", "1200.0", "extra", "too-much"}}) { + QVERIFY(!QMapLiveCQ::parse(tokens, 100, record)); + } + } + + void rejectsMalformedFrequencyAndCalls() + { + QMapLiveCQ::Record record; + for (auto const& frequency : {QString {"1200"}, QString {"1200."}, + QString {"1200.x"}, QString {"1200.0.1"}}) { + QVERIFY(!QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5L", frequency}, + 100, record)); + } + QVERIFY(!QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "N5", "1200.0"}, + 100, record)); + QVERIFY(!QMapLiveCQ::parse( + {"123456", "-10", "0.1", "1234", "-12", "60", "CQ", "DX", "N5", "1200.0"}, + 100, record)); + } +}; + +QTEST_APPLESS_MAIN(TestQMapLiveCQParser) + +#include "test_livecq_parser.moc" diff --git a/tests/unit/qmap/test_plotter_initialization.cpp b/tests/unit/qmap/test_plotter_initialization.cpp new file mode 100644 index 00000000..f022a300 --- /dev/null +++ b/tests/unit/qmap/test_plotter_initialization.cpp @@ -0,0 +1,127 @@ +#include <memory> + +#include <QtTest> +#include <QApplication> +#include <QImage> +#include <QMouseEvent> +#include <QSignalSpy> + +#include "qmap/plotter.h" + +class TestablePlotter final : public CPlotter +{ +public: + using CPlotter::mousePressEvent; +}; + +class TestPlotterInitialization final : public QObject +{ + Q_OBJECT + +private slots: + void sizesHiddenPlotter(); + void ignoresOutOfSpanAndControlClicks(); + void paintsLabelsInTwoDSpectrumMode(); +}; + +void TestPlotterInitialization::sizesHiddenPlotter() +{ + // CPlotter embeds a ~12.5 MB m_zwf array as a direct member (qmap/plotter.h), + // so it must be heap-allocated -- a stack-local instance overflows the + // default thread stack. + auto const plotter = std::make_unique<CPlotter> (); + + QVERIFY (!plotter->isVisible ()); + plotter->ensureSized (1000, 280); + + QCOMPARE (plotter->plotWidth (), 1000); + QVERIFY (plotter->centerFreq () >= 0); + QVERIFY (plotter->binsPerPixel () > 0); +} + +void TestPlotterInitialization::ignoresOutOfSpanAndControlClicks() +{ + qRegisterMetaType<DecodeClickGesture> ("DecodeClickGesture"); + auto const plotter = std::make_unique<TestablePlotter> (); + plotter->ensureSized (1000, 280); + plotter->setFsample (96000); + plotter->show (); + QCoreApplication::processEvents (); + plotter->SetStartFreq (100); + plotter->m_fSpan = 100.f; + + QMapDecodeLabel label; + label.callsign = "K1ABC"; + label.receiveFrequencyKHz = 150.; + label.raw = QByteArray (static_cast<int> (QMapDecodeRowSize), 'x'); + plotter->setDecodeLabels ({label}); + + QSignalSpy clicked (plotter.get (), &CPlotter::decodeLabelClicked); + QVERIFY (clicked.isValid ()); + QImage image (plotter->size (), QImage::Format_ARGB32); + image.fill (Qt::transparent); + plotter->render (&image); + QPoint labelPoint; + for (int y = 30; y < 60 && labelPoint.isNull (); ++y) { + for (int x = 0; x < image.width () && labelPoint.isNull (); ++x) { + auto const color = image.pixelColor (x, y); + if (color.red () > 200 && color.green () > 200 && color.blue () < 100) + labelPoint = {x, y}; + } + } + QVERIFY (!labelPoint.isNull ()); + QMouseEvent event {QEvent::MouseButtonPress, QPointF (labelPoint), + Qt::LeftButton, Qt::LeftButton, Qt::NoModifier}; + plotter->mousePressEvent (&event); + QCOMPARE (clicked.size (), 1); + + clicked.clear (); + label.receiveFrequencyKHz = 1000.; + plotter->setDecodeLabels ({label}); + QMouseEvent outOfSpanEvent {QEvent::MouseButtonPress, QPointF (999, 35), + Qt::LeftButton, Qt::LeftButton, Qt::NoModifier}; + plotter->mousePressEvent (&outOfSpanEvent); + QCOMPARE (clicked.size (), 0); + + label.receiveFrequencyKHz = 150.; + plotter->setDecodeLabels ({label}); + QMouseEvent controlEvent {QEvent::MouseButtonPress, + QPointF (labelPoint.x (), labelPoint.y ()), + Qt::LeftButton, Qt::LeftButton, Qt::ControlModifier}; + plotter->mousePressEvent (&controlEvent); + QCOMPARE (clicked.size (), 0); +} + +void TestPlotterInitialization::paintsLabelsInTwoDSpectrumMode() +{ + auto const plotter = std::make_unique<CPlotter> (); + plotter->ensureSized (1000, 280); + plotter->setFsample (96000); + plotter->set2Dspec (true); + plotter->SetStartFreq (100); + + QMapDecodeLabel label; + label.callsign = "K1ABC"; + label.receiveFrequencyKHz = plotter->startFreq () + plotter->m_fSpan / 2.; + plotter->setDecodeLabels ({label}); + plotter->show (); + QCoreApplication::processEvents (); + + QImage image (plotter->size (), QImage::Format_ARGB32); + image.fill (Qt::transparent); + plotter->render (&image); + + int yellowPixels = 0; + for (int y = 30; y < 60; ++y) { + for (int x = 470; x < 530; ++x) { + auto const color = image.pixelColor (x, y); + if (color.red () > 200 && color.green () > 200 && color.blue () < 100) + ++yellowPixels; + } + } + QVERIFY (yellowPixels > 0); +} + +QTEST_MAIN (TestPlotterInitialization) + +#include "test_plotter_initialization.moc" diff --git a/tests/unit/qmap/test_qmap_decode_record.cpp b/tests/unit/qmap/test_qmap_decode_record.cpp new file mode 100644 index 00000000..54b165ec --- /dev/null +++ b/tests/unit/qmap/test_qmap_decode_record.cpp @@ -0,0 +1,97 @@ +#include <QtTest> + +#include "qmap/decode_label.h" +#include "qmap/qmap_decode_record.h" + +namespace +{ + QByteArray makeRow (QByteArray const& message) + { + QByteArray row (static_cast<int> (QMapDecodeRowSize), ' '); + row.replace (0, 6, "123430"); + row.replace (6, 9, " 123.456"); + row.replace (15, 7, " 120.0"); + row.replace (22, 7, " 0.12"); + row.replace (29, 5, " -15"); + row.replace (36, 3, "30A"); + row.replace (41, message.size (), message); + return row; + } +} + +class TestQMapDecodeRecord final : public QObject +{ + Q_OBJECT + +private slots: + void parsesFixedWidthRecord(); + void rejectsMalformedRecord(); + void replacesLabelWithLatestRecord(); + void prunesExpiredLabelsAcrossMidnight(); +}; + +void TestQMapDecodeRecord::parsesFixedWidthRecord() +{ + auto const row = makeRow ("CQ POTA W3SZ/2 FN20"); + auto const record = parseQMapDecodeRecord (row); + + QVERIFY (record); + QCOMPARE (record->raw, row); + QCOMPARE (record->time, QString {"123430"}); + QCOMPARE (record->callsign, QString {"W3SZ/2"}); + QCOMPARE (record->grid, QString {"FN20"}); + QCOMPARE (record->submode, QString {"30A"}); + QCOMPARE (record->receiveFrequencyKHz, 123.456); + QCOMPARE (record->scheduledFrequencyKHz, 120.0); + QCOMPARE (record->snr, -15); + QCOMPARE (record->secondsSinceMidnight, 12 * 3600 + 34 * 60 + 30); + QVERIFY (record->secondHalf); + QVERIFY (record->cq); +} + +void TestQMapDecodeRecord::rejectsMalformedRecord() +{ + QVERIFY (!parseQMapDecodeRecord (QByteArray {"short"})); + + auto row = makeRow ("CQ K1ABC FN42"); + row.replace (0, 6, "256099"); + QVERIFY (!parseQMapDecodeRecord (row)); +} + +void TestQMapDecodeRecord::replacesLabelWithLatestRecord() +{ + auto firstRow = makeRow ("CQ K1ABC FN42"); + auto secondRow = firstRow; + secondRow.replace (6, 9, " 222.333"); + secondRow.replace (29, 5, " -07"); + auto const first = parseQMapDecodeRecord (firstRow); + auto const second = parseQMapDecodeRecord (secondRow); + QVERIFY (first); + QVERIFY (second); + + QList<QMapDecodeLabel> labels; + upsertQMapDecodeLabel (labels, *first); + upsertQMapDecodeLabel (labels, *second); + + QCOMPARE (labels.size (), 1); + QCOMPARE (labels.first ().raw, secondRow); + QCOMPARE (labels.first ().receiveFrequencyKHz, 222.333); + QCOMPARE (labels.first ().snr, -7); +} + +void TestQMapDecodeRecord::prunesExpiredLabelsAcrossMidnight() +{ + auto record = *parseQMapDecodeRecord (makeRow ("CQ K1ABC FN42")); + record.secondsSinceMidnight = 23 * 3600 + 59 * 60; + QList<QMapDecodeLabel> labels {record}; + + pruneQMapDecodeLabels (labels, 60); + QCOMPARE (labels.size (), 1); + + pruneQMapDecodeLabels (labels, 3 * 60 + 1); + QVERIFY (labels.isEmpty ()); +} + +QTEST_GUILESS_MAIN (TestQMapDecodeRecord) + +#include "test_qmap_decode_record.moc" diff --git a/tests/unit/qmap/test_qmap_ipc.cpp b/tests/unit/qmap/test_qmap_ipc.cpp new file mode 100644 index 00000000..61524fbd --- /dev/null +++ b/tests/unit/qmap/test_qmap_ipc.cpp @@ -0,0 +1,98 @@ +#include <QtTest> + +#include <array> +#include <cstring> + +#include "qmap/qmap_ipc.h" + +class TestQMapIpc final : public QObject +{ + Q_OBJECT + +private slots: + void leavesIncompleteBatchPending(); + void acknowledgesCompletedBatch_data(); + void acknowledgesCompletedBatch(); + void decoderPublicationPreservesRequests(); + void reportsMappingCapabilities(); + void clearsOnlyMappedProtocolBytes(); +}; + +void TestQMapIpc::leavesIncompleteBatchPending() +{ + QMapDecodeBlock shared {}; + shared.ndecodes = 3; + + QVERIFY (!acknowledgeQMapDecodeBatch (shared)); + QCOMPARE (shared.ndecodes, 3); +} + +void TestQMapIpc::acknowledgesCompletedBatch_data() +{ + QTest::addColumn<int> ("completion"); + QTest::newRow ("live") << 1; + QTest::newRow ("disk") << 2; +} + +void TestQMapIpc::acknowledgesCompletedBatch() +{ + QFETCH (int, completion); + QMapDecodeBlock shared {}; + shared.ndecodes = 3; + shared.nQDecoderDone = completion; + + QVERIFY (acknowledgeQMapDecodeBatch (shared)); + QCOMPARE (shared.ndecodes, 0); + QCOMPARE (shared.nQDecoderDone, 0); +} + +void TestQMapIpc::decoderPublicationPreservesRequests() +{ + QMapSharedMemory shared {}; + shared.decodes.nWDecoderBusy = 1; + shared.decodes.nWTransmitting = 60; + shared.decodes.kHzRequested = 144; + shared.click.action = QMapClickAction::Select; + std::memset (shared.click.selectedDecode, 'x', sizeof shared.click.selectedDecode); + QMapDecodeBlock publication {}; + publication.ndecodes = 2; + + publishQMapDecodeBlock (shared, publication); + + QCOMPARE (shared.decodes.ndecodes, 2); + QCOMPARE (shared.decodes.nWDecoderBusy, 1); + QCOMPARE (shared.decodes.nWTransmitting, 60); + QCOMPARE (shared.decodes.kHzRequested, 144); + QCOMPARE (shared.click.action, QMapClickAction::Select); + QByteArray const selectedDecode {shared.click.selectedDecode, + static_cast<int> (sizeof shared.click.selectedDecode)}; + QCOMPARE (selectedDecode, QByteArray (static_cast<int> (QMapDecodeRowSize), 'x')); +} + +void TestQMapIpc::reportsMappingCapabilities() +{ + QVERIFY (!qmapDecoderRegionAvailable (qmap_decode_ipc::shared_memory_size - 1)); + QVERIFY (qmapDecoderRegionAvailable (qmap_decode_ipc::shared_memory_size)); + QVERIFY (!qmapClickMailboxAvailable (sizeof (QMapSharedMemory) - 1)); + QVERIFY (qmapClickMailboxAvailable (sizeof (QMapSharedMemory))); + QVERIFY (qmapClickMailboxAvailable (QMapSharedMemorySize)); +} + +void TestQMapIpc::clearsOnlyMappedProtocolBytes() +{ + std::array<unsigned char, QMapSharedMemorySize + 16> bytes; + bytes.fill (0xA5); + + clearQMapSharedMemory (bytes.data (), sizeof (QMapSharedMemory)); + + for (std::size_t i = 0; i < sizeof (QMapSharedMemory); ++i) + QCOMPARE (bytes[i], static_cast<unsigned char> (0)); + for (std::size_t i = sizeof (QMapSharedMemory); i < bytes.size (); ++i) + QCOMPARE (bytes[i], static_cast<unsigned char> (0xA5)); + QCOMPARE (qmapClearLength (0), std::size_t {0}); + QCOMPARE (qmapClearLength (QMapSharedMemorySize + 1), QMapSharedMemorySize); +} + +QTEST_GUILESS_MAIN (TestQMapIpc) + +#include "test_qmap_ipc.moc" diff --git a/tests/unit/streaming/CMakeLists.txt b/tests/unit/streaming/CMakeLists.txt new file mode 100644 index 00000000..5a367f45 --- /dev/null +++ b/tests/unit/streaming/CMakeLists.txt @@ -0,0 +1,16 @@ +add_executable (test_streaming_consumers test_streaming_consumers.cpp) +target_link_libraries (test_streaming_consumers Qt5::Test) +target_compile_definitions (test_streaming_consumers PRIVATE + JT9_EXECUTABLE="$<TARGET_FILE:jt9>" + WSPRD_EXECUTABLE="$<TARGET_FILE:wsprd>" +) + +add_test (NAME test_streaming_consumers COMMAND test_streaming_consumers) +set_tests_properties (test_streaming_consumers PROPERTIES + LABELS "streaming;runtime" + TIMEOUT 120 +) +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_streaming_consumers PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=${wsjt_tsan_fortran_options}") +endif () diff --git a/tests/unit/streaming/test_streaming_consumers.cpp b/tests/unit/streaming/test_streaming_consumers.cpp new file mode 100644 index 00000000..ba605fe1 --- /dev/null +++ b/tests/unit/streaming/test_streaming_consumers.cpp @@ -0,0 +1,373 @@ +#include <limits> + +#include <QJsonDocument> +#include <QJsonObject> +#include <QProcess> +#include <QTemporaryDir> +#include <QtTest> + +namespace +{ +constexpr quint32 Jt9AudioCapacityBytes = 30u * 60u * 12000u * 2u; +constexpr quint32 WsprdAudioCapacityBytes = 8u * 114u * 12000u * 2u; +constexpr int Ft4PeriodSamples = 21 * 3456; +constexpr int Jt9TenSecondPeriodSamples = 10 * 12000; + +struct ProcessResult +{ + bool started {}; + bool timedOut {}; + int exitCode {-1}; + QProcess::ExitStatus exitStatus {QProcess::CrashExit}; + QByteArray standardOutput; + QByteArray standardError; +}; + +struct ParsedEvents +{ + QList<QJsonObject> values; + QString error; +}; + +void appendLittleEndian32 (QByteArray& bytes, quint32 value) +{ + bytes.append (char (value & 0xffu)); + bytes.append (char ((value >> 8) & 0xffu)); + bytes.append (char ((value >> 16) & 0xffu)); + bytes.append (char ((value >> 24) & 0xffu)); +} + +QByteArray sessionHeader () +{ + QByteArray bytes {"WSJT", 4}; + bytes.append ('\0'); + bytes.append ('\1'); + bytes.append ('\x0c'); + bytes.append ('\0'); + return bytes; +} + +QByteArray declaredFrame (quint8 type, quint32 length) +{ + QByteArray bytes; + bytes.append (char (type)); + appendLittleEndian32 (bytes, length); + return bytes; +} + +QByteArray frame (quint8 type, QByteArray const& body) +{ + auto bytes = declaredFrame (type, quint32 (body.size ())); + bytes.append (body); + return bytes; +} + +QByteArray silentAudioFrame (int samples) +{ + return frame (0x01u, QByteArray (samples * 2, '\0')); +} + +QByteArray controlFrame (QByteArray const& json) +{ + return frame (0x02u, json); +} + +ProcessResult runProcess (QString const& executable, QStringList const& arguments, + QByteArray const& input, + QString const& workingDirectory, + int timeoutMs = 30000, + bool closeInput = true) +{ + QProcess process; + process.setProcessChannelMode (QProcess::SeparateChannels); + process.setWorkingDirectory (workingDirectory); + process.start (executable, arguments); + + ProcessResult result; + result.started = process.waitForStarted (5000); + if (!result.started) + { + result.standardError = process.errorString ().toUtf8 (); + return result; + } + + process.write (input); + if (closeInput) + { + process.closeWriteChannel (); + } + if (!process.waitForFinished (timeoutMs)) + { + result.timedOut = true; + process.kill (); + process.waitForFinished (5000); + } + + result.exitCode = process.exitCode (); + result.exitStatus = process.exitStatus (); + result.standardOutput = process.readAllStandardOutput (); + result.standardError = process.readAllStandardError (); + return result; +} + +ParsedEvents parseEvents (QByteArray const& output) +{ + ParsedEvents parsed; + auto const lines = output.split ('\n'); + for (auto const& line : lines) + { + if (line.trimmed ().isEmpty ()) + { + continue; + } + QJsonParseError jsonError; + auto const document = QJsonDocument::fromJson (line, &jsonError); + if (jsonError.error != QJsonParseError::NoError || !document.isObject ()) + { + parsed.error = QString {"invalid JSON event: %1"}.arg ( + QString::fromUtf8 (line)); + return parsed; + } + auto const event = document.object (); + if (event.value ("v").toInt (-1) != 1 || !event.value ("t").isString ()) + { + parsed.error = QString {"invalid event envelope: %1"}.arg ( + QString::fromUtf8 (line)); + return parsed; + } + auto const type = event.value ("t").toString (); + if (type == "error" && event.contains ("code")) + { + auto const code = event.value ("code"); + if (!code.isString () || code.toString ().isEmpty ()) + { + parsed.error = QString {"invalid coded error event: %1"}.arg ( + QString::fromUtf8 (line)); + return parsed; + } + auto const requiresDetail = + code.toString () == "frame_too_large" || + code.toString () == "unknown_mode" || + code.toString () == "invalid_trperiod" || + code.toString () == "invalid_wspr_type" || + code.toString () == "insufficient_audio"; + if (requiresDetail && !event.value ("detail").isString ()) + { + parsed.error = QString {"coded error is missing detail: %1"}.arg ( + QString::fromUtf8 (line)); + return parsed; + } + } + if (type == "warning" && + (!event.value ("code").isString () || + event.value ("code").toString ().isEmpty () || + !event.value ("discarded_samples").isDouble () || + event.value ("discarded_samples").toDouble () < 0.0)) + { + parsed.error = QString {"invalid warning event: %1"}.arg ( + QString::fromUtf8 (line)); + return parsed; + } + parsed.values.append (event); + } + return parsed; +} + +QList<QJsonObject> eventsMatching (QList<QJsonObject> const& events, + QString const& type, + QString const& code = {}) +{ + QList<QJsonObject> matching; + for (auto const& event : events) + { + if (event.value ("t").toString () == type && + (code.isEmpty () || event.value ("code").toString () == code)) + { + matching.append (event); + } + } + return matching; +} + +ProcessResult runJt9 (QByteArray const& input, QStringList options = {}) +{ + QTemporaryDir directory; + if (!directory.isValid ()) + { + return {}; + } + options << "-a" << directory.path () + << "-t" << directory.path () + << "--stream"; + return runProcess (QString::fromUtf8 (JT9_EXECUTABLE), options, input, + directory.path ()); +} + +ProcessResult runWsprd (QByteArray const& input, int timeoutMs = 30000, + bool closeInput = true) +{ + QTemporaryDir directory; + if (!directory.isValid ()) + { + return {}; + } + return runProcess (QString::fromUtf8 (WSPRD_EXECUTABLE), + {"-a", directory.path (), "-H", "-0"}, input, + directory.path (), timeoutMs, closeInput); +} + +void verifyCompleted (ProcessResult const& result, int expectedExitCode) +{ + QVERIFY2 (result.started, result.standardError.constData ()); + QVERIFY2 (!result.timedOut, result.standardError.constData ()); + QCOMPARE (result.exitStatus, QProcess::NormalExit); + QCOMPARE (result.exitCode, expectedExitCode); +} + +ParsedEvents verifyEvents (ProcessResult const& result) +{ + auto const parsed = parseEvents (result.standardOutput); + if (!parsed.error.isEmpty ()) + { + QTest::qFail (qPrintable (parsed.error), __FILE__, __LINE__); + } + if (parsed.values.isEmpty ()) + { + QTest::qFail ("consumer emitted no JSON events", __FILE__, __LINE__); + } + return parsed; +} +} + +class TestStreamingConsumers final : public QObject +{ + Q_OBJECT + +private slots: + void jt9RejectsOversizedFrames_data () + { + QTest::addColumn<quint32> ("declaredLength"); + QTest::newRow ("over capacity") << Jt9AudioCapacityBytes + 2u; + QTest::newRow ("uint32 max") << std::numeric_limits<quint32>::max (); + } + + void jt9RejectsOversizedFrames () + { + QFETCH (quint32, declaredLength); + auto const result = runJt9 (sessionHeader () + + declaredFrame (0x01u, declaredLength)); + verifyCompleted (result, 1); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "frame_too_large").size (), 1); + QCOMPARE (eventsMatching (events.values, "decode").size (), 0); + } + + void jt9RejectsUnknownMode_data () + { + QTest::addColumn<QByteArray> ("configure"); + QTest::newRow ("string") + << QByteArray {R"({"t":"configure","mode":"BOGUS","trperiod":1})"}; + QTest::newRow ("numeric") + << QByteArray {R"({"t":"configure","mode":999,"trperiod":1})"}; + } + + void jt9RejectsUnknownMode () + { + QFETCH (QByteArray, configure); + auto const input = sessionHeader () + controlFrame (configure) + + silentAudioFrame (Jt9TenSecondPeriodSamples + 2); + auto const result = runJt9 (input, {"-9", "-p", "10"}); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "unknown_mode").size (), 1); + auto const warnings = eventsMatching ( + events.values, "warning", "period_boundary_discard"); + QCOMPARE (warnings.size (), 1); + QCOMPARE (warnings.front ().value ("discarded_samples").toInt (), 2); + } + + void jt9RejectsOutOfRangeTrperiod_data () + { + QTest::addColumn<QByteArray> ("configure"); + QTest::newRow ("zero") + << QByteArray {R"({"t":"configure","trperiod":0})"}; + QTest::newRow ("above maximum") + << QByteArray {R"({"t":"configure","trperiod":1801})"}; + } + + void jt9RejectsOutOfRangeTrperiod () + { + QFETCH (QByteArray, configure); + auto const result = runJt9 (sessionHeader () + controlFrame (configure) + + controlFrame (R"({"t":"halt"})")); + verifyCompleted (result, 0); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "invalid_trperiod").size (), 1); + QCOMPARE (eventsMatching (events.values, "decode").size (), 0); + } + + void jt9ReportsBoundaryDiscardOnce () + { + auto const exact = runJt9 (sessionHeader () + + silentAudioFrame (Ft4PeriodSamples), {"--ft4"}); + verifyCompleted (exact, 0); + auto const exactEvents = verifyEvents (exact); + QCOMPARE (eventsMatching (exactEvents.values, "warning").size (), 0); + + auto const overflow = runJt9 ( + sessionHeader () + silentAudioFrame (Ft4PeriodSamples + 2), {"--ft4"}); + verifyCompleted (overflow, 0); + auto const overflowEvents = verifyEvents (overflow); + auto const warnings = eventsMatching ( + overflowEvents.values, "warning", "period_boundary_discard"); + QCOMPARE (warnings.size (), 1); + QCOMPARE (warnings.front ().value ("discarded_samples").toInt (), 2); + } + + void wsprdRejectsOversizedFrames_data () + { + QTest::addColumn<quint32> ("declaredLength"); + QTest::newRow ("over capacity") << WsprdAudioCapacityBytes + 2u; + QTest::newRow ("uint32 max") << std::numeric_limits<quint32>::max (); + } + + void wsprdRejectsOversizedFrames () + { + QFETCH (quint32, declaredLength); + auto const result = runWsprd (sessionHeader () + + declaredFrame (0x01u, declaredLength)); + verifyCompleted (result, 1); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "frame_too_large").size (), 1); + QCOMPARE (eventsMatching (events.values, "decode").size (), 0); + } + + void wsprdDispatchesConfigureStructurally () + { + auto const configure = QByteArray { + R"({"t":"configure","date":"260822","time":"1200","dialfreq":14.0956,"wspr_type":2,"mycall":"halt","mygrid":"FN20"})"}; + auto const result = runWsprd (sessionHeader () + controlFrame (configure) + + controlFrame (R"({"t":"halt"})")); + verifyCompleted (result, 1); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "insufficient_audio").size (), 1); + QCOMPARE (eventsMatching (events.values, "error", "missing_configure").size (), 0); + } + + void wsprdRejectsInvalidWsprType () + { + auto const configure = QByteArray { + R"({"t":"configure","date":"260822","time":"1200","dialfreq":14.0956,"wspr_type":3})"}; + auto const result = runWsprd (sessionHeader () + controlFrame (configure), + 3000, false); + verifyCompleted (result, 1); + auto const events = verifyEvents (result); + QCOMPARE (eventsMatching (events.values, "error", "invalid_wspr_type").size (), 1); + QCOMPARE (eventsMatching (events.values, "decode").size (), 0); + QCOMPARE (eventsMatching (events.values, "decode_finished").size (), 0); + } +}; + +QTEST_GUILESS_MAIN (TestStreamingConsumers) + +#include "test_streaming_consumers.moc" diff --git a/tests/unit/superfox/CMakeLists.txt b/tests/unit/superfox/CMakeLists.txt new file mode 100644 index 00000000..3334a12c --- /dev/null +++ b/tests/unit/superfox/CMakeLists.txt @@ -0,0 +1,31 @@ +add_executable (test_superfox_pack test_superfox_pack.f90) +target_include_directories (test_superfox_pack PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_superfox_pack) + +add_test (NAME test_superfox_pack COMMAND test_superfox_pack) + +add_executable (test_superfox_tx_handoff test_superfox_tx_handoff.f90) +target_include_directories (test_superfox_tx_handoff PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_superfox_tx_handoff) + +add_test (NAME test_superfox_tx_handoff COMMAND test_superfox_tx_handoff) + +add_executable (test_superfox_unpack test_superfox_unpack.f90) +target_include_directories (test_superfox_unpack PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_superfox_unpack) + +add_test (NAME test_superfox_unpack COMMAND test_superfox_unpack) +set_tests_properties (test_superfox_unpack PROPERTIES + PASS_REGULAR_EXPRESSION "CQ K1JT FN20;.*2S/IZFUZBRXJF") + +add_executable (test_superfox_unpack_unsupported + test_superfox_unpack_unsupported.f90) +target_include_directories (test_superfox_unpack_unsupported + PRIVATE ${CMAKE_BINARY_DIR}) +wsjt_link_common_fortran (test_superfox_unpack_unsupported) + +add_test (NAME test_superfox_unpack_unsupported + COMMAND test_superfox_unpack_unsupported) +set_tests_properties (test_superfox_unpack_unsupported PROPERTIES + PASS_REGULAR_EXPRESSION "unsupported i3=1 ignored" + FAIL_REGULAR_EXPRESSION "~") diff --git a/tests/unit/superfox/test_superfox_pack.f90 b/tests/unit/superfox/test_superfox_pack.f90 new file mode 100644 index 00000000..e204262f --- /dev/null +++ b/tests/unit/superfox/test_superfox_pack.f90 @@ -0,0 +1,456 @@ +program test_superfox_pack + + implicit none + + integer :: ntests + integer, parameter :: SFOX_PACK_OK=0 + integer, parameter :: SFOX_PACK_BAD_TOKEN=1 + integer, parameter :: SFOX_PACK_BAD_OTP=2 + integer, parameter :: SFOX_PACK_BAD_CQ=3 + integer, parameter :: SFOX_PACK_BAD_CALL=4 + integer, parameter :: SFOX_PACK_BAD_REPORT=5 + integer, parameter :: SFOX_PACK_BAD_FREE_TEXT=6 + + ntests=0 + + call expect_cq_round_trip('CQ K1JT FN20','K1JT','FN20') + call expect_cq_round_trip('CQ PJ4/K1ABC FK52','PJ4/K1ABC','FK52') + call expect_cq_round_trip('CQ K1JT AA00','K1JT','AA00') + call expect_cq_round_trip('CQ K1JT RR99','K1JT','RR99') + call expect_crc_vector() + call expect_invalid_pack('CQ',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1@JT FN20',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT FN2@',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT FN2',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT FN200',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT SS00',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ AB FN20',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ 123456789012 FN20',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ k1jt FN20',SFOX_PACK_BAD_CQ) + call expect_invalid_pack('CQ K1JT FN20 EXTRA',SFOX_PACK_BAD_CQ) + call expect_invalid_pack(' ',SFOX_PACK_BAD_TOKEN) + + call expect_standard_message('K1JT W1AW','K1JT','W1AW') + call expect_standard_report('K1JT W1AW +05','K1JT','W1AW',5) + call expect_standard_report('K1JT W1AW +12','K1JT','W1AW',12) + call expect_standard_report('K1JT W1AW -18','K1JT','W1AW',-18) + call expect_standard_message('K1JT W1AW AA5AU K9AN','K1JT','W1AW') + call expect_standard_message('K1JT W1AW AA5AU K9AN','K1JT','AA5AU') + call expect_standard_message('K1JT W1AW AA5AU K9AN','K1JT','K9AN') + call expect_invalid_pack('K1JT Q1ABC',SFOX_PACK_BAD_CALL) + call expect_invalid_pack('K1JT W1AW +13',SFOX_PACK_BAD_REPORT) + call expect_invalid_pack('K1JT W1AW -19',SFOX_PACK_BAD_REPORT) + call expect_invalid_pack('K1JT W1AW +XX',SFOX_PACK_BAD_REPORT) + call expect_invalid_pack('K1JT VERYLONGTOKEN1',SFOX_PACK_BAD_TOKEN) + call expect_too_many_words() + + call expect_free_text_message('K1JT W1AW','HELLO SUPERFOX') + call expect_free_text_message('K1JT W1AW','ABC+-./? 123') + call expect_free_text_four_report_records() + call expect_free_text_four_mixed_records() + call expect_invalid_free_text_capacity() + call expect_no_free_text_full_capacity() + call expect_invalid_no_free_text_capacity() + call expect_invalid_free_text('K1JT W1AW','hello superfox') + call expect_invalid_free_text('K1JT W1AW','HELLO:SUPERFOX') + call expect_invalid_otp('K1JT W1AW') + + call expect_more_cqs('K1JT') + call expect_otp_bits('K1JT W1AW',123456) + + write(*,1000) ntests +1000 format('superfox pack tests passed: ',i0) + +contains + + subroutine expect_crc_vector() + character(len=120) :: line + character(len=26) :: free_text + character(len=10) :: ckey + integer(kind=1) :: xin(0:49), raw(0:49) + integer :: crc21, i, pack_error + logical(kind=1) :: more_cqs, send_msg + + line='CQ K1JT FN20' + free_text=' ' + ckey='0000000000' + more_cqs=.false. + send_msg=.false. + call sfox_pack(line,ckey,more_cqs,send_msg,free_text,xin,pack_error) + call assert_int('SuperFox CRC pack status',SFOX_PACK_OK,pack_error) + do i=0,49 + raw(i)=xin(49-i) + enddo + crc21=128*128*raw(47)+128*raw(48)+raw(49) + call assert_int('SuperFox CRC21',1361017,crc21) + ntests=ntests+1 + end subroutine expect_crc_vector + + subroutine expect_standard_message(input,expected_fox,expected_hound) + character(len=*), intent(in) :: input, expected_fox, expected_hound + character(len=329) :: msgbits + character(len=13) :: got_fox + integer :: i3 + + call pack_and_decode_bits(input,.false.,.false.,' ',0,msgbits,i3) + call assert_int('SuperFox standard type',0,i3) + call decode_pack28_field(msgbits,1,got_fox) + call assert_text('SuperFox fox call',expected_fox,got_fox) + call assert_hound_present(msgbits,expected_hound) + + ntests=ntests+1 + end subroutine expect_standard_message + + subroutine expect_standard_report(input,expected_fox,expected_hound, & + expected_report) + character(len=*), intent(in) :: input, expected_fox, expected_hound + integer, intent(in) :: expected_report + character(len=329) :: msgbits + character(len=13) :: got_fox, got_hound + integer :: i3, report + + call pack_and_decode_bits(input,.false.,.false.,' ',0,msgbits,i3) + call assert_int('SuperFox report type',0,i3) + call decode_pack28_field(msgbits,1,got_fox) + call assert_text('SuperFox report fox call',expected_fox,got_fox) + call decode_pack28_field(msgbits,169,got_hound) + call assert_text('SuperFox report hound call',expected_hound,got_hound) + read(msgbits(281:285),'(b5)') report + call assert_int('SuperFox report',expected_report,report-18) + + ntests=ntests+1 + end subroutine expect_standard_report + + subroutine expect_free_text_message(input,free_text) + use packjt77, only: unpacktext77 + character(len=*), intent(in) :: input, free_text + character(len=329) :: msgbits + character(len=26) :: decoded + integer :: i3 + + call pack_and_decode_bits(input,.false.,.true.,free_text,0,msgbits,i3) + call assert_int('SuperFox free-text type',2,i3) + call unpacktext77(msgbits(161:231),decoded(1:13)) + call unpacktext77(msgbits(232:302),decoded(14:26)) + call trim_dots(decoded) + call assert_text('SuperFox free text',free_text,decoded) + + ntests=ntests+1 + end subroutine expect_free_text_message + + subroutine expect_invalid_free_text(input,free_text) + character(len=*), intent(in) :: input, free_text + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits_allow_failure(input,.false.,.true.,free_text, & + 0,msgbits,i3,SFOX_PACK_BAD_FREE_TEXT) + ntests=ntests+1 + end subroutine expect_invalid_free_text + + subroutine expect_free_text_four_report_records() + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits('K1JT K1RAA -01 K1RAB -02 K1RAC -03 K1RAD -04', & + .false.,.true.,'HELLO SUPERFOX',0,msgbits,i3) + call assert_int('SuperFox free-text four reports type',2,i3) + call assert_hound_present(msgbits,'K1RAA') + call assert_hound_present(msgbits,'K1RAB') + call assert_hound_present(msgbits,'K1RAC') + call assert_hound_present(msgbits,'K1RAD') + + ntests=ntests+1 + end subroutine expect_free_text_four_report_records + + subroutine expect_free_text_four_mixed_records() + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits('K1JT K1RRA K1RRB K1RPC -03 K1RPD -04', & + .false.,.true.,'HELLO SUPERFOX',0,msgbits,i3) + call assert_int('SuperFox free-text mixed type',2,i3) + call assert_hound_present(msgbits,'K1RRA') + call assert_hound_present(msgbits,'K1RRB') + call assert_hound_present(msgbits,'K1RPC') + call assert_hound_present(msgbits,'K1RPD') + + ntests=ntests+1 + end subroutine expect_free_text_four_mixed_records + + subroutine expect_invalid_free_text_capacity() + call expect_invalid_pack_with_free_text( & + 'K1JT K1RAA -01 K1RAB -02 K1RAC -03 K1RAD -04 K1RAE -05', & + SFOX_PACK_BAD_TOKEN) + end subroutine expect_invalid_free_text_capacity + + subroutine expect_no_free_text_full_capacity() + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits( & + 'K1JT K1AAA K1AAB K1AAC K1AAD K1AAE K1AAF -01 K1AAG -02 K1AAH -03 K1AAI -04', & + .false.,.false.,' ',0,msgbits,i3) + call assert_int('SuperFox no-free-text full capacity type',0,i3) + call assert_hound_present(msgbits,'K1AAA') + call assert_hound_present(msgbits,'K1AAE') + call assert_hound_present(msgbits,'K1AAF') + call assert_hound_present(msgbits,'K1AAI') + + ntests=ntests+1 + end subroutine expect_no_free_text_full_capacity + + subroutine expect_invalid_no_free_text_capacity() + call expect_invalid_pack( & + 'K1JT K1AAA K1AAB K1AAC K1AAD K1AAE K1AAF', & + SFOX_PACK_BAD_TOKEN) + end subroutine expect_invalid_no_free_text_capacity + + subroutine expect_more_cqs(input) + character(len=*), intent(in) :: input + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits(input,.true.,.false.,' ',0,msgbits,i3) + if(msgbits(306:306).ne.'1') then + write(*,1040) trim(input) +1040 format('SuperFox more-CQs bit was not set for "',a,'"') + error stop 1 + endif + + ntests=ntests+1 + end subroutine expect_more_cqs + + subroutine expect_otp_bits(input,expected_otp) + character(len=*), intent(in) :: input + integer, intent(in) :: expected_otp + character(len=329) :: msgbits + integer :: i3, got_otp + + call pack_and_decode_bits(input,.false.,.false.,' ',expected_otp,msgbits,i3) + read(msgbits(307:326),'(b20)') got_otp + call assert_int('SuperFox OTP bits',expected_otp,got_otp) + + ntests=ntests+1 + end subroutine expect_otp_bits + + subroutine expect_cq_round_trip(input,expected_call,expected_grid) + character(len=*), intent(in) :: input, expected_call, expected_grid + character(len=11) :: got_call + character(len=4) :: got_grid + integer :: i3 + + call pack_and_decode_cq(input,i3,got_call,got_grid) + call assert_int('SuperFox CQ type',3,i3) + call assert_text('SuperFox CQ call',expected_call,got_call) + call assert_text('SuperFox CQ grid',expected_grid,got_grid) + + ntests=ntests+1 + end subroutine expect_cq_round_trip + + subroutine expect_invalid_pack(input,expected_error) + character(len=*), intent(in) :: input + integer, intent(in) :: expected_error + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits_allow_failure(input,.false.,.false.,' ',0, & + msgbits,i3,expected_error) + ntests=ntests+1 + end subroutine expect_invalid_pack + + subroutine expect_invalid_pack_with_free_text(input,expected_error) + character(len=*), intent(in) :: input + integer, intent(in) :: expected_error + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits_allow_failure(input,.false.,.true., & + 'HELLO SUPERFOX',0,msgbits,i3,expected_error) + ntests=ntests+1 + end subroutine expect_invalid_pack_with_free_text + + subroutine expect_too_many_words() + call expect_invalid_pack( & + 'K1JT K1AA K1AB K1AC K1AD K1AE K1AF K1AG K1AH K1AI ' // & + 'K1AJ K1AK K1AL K1AM K1AN K1AO K1AP', & + SFOX_PACK_BAD_TOKEN) + end subroutine expect_too_many_words + + subroutine expect_invalid_otp(input) + character(len=*), intent(in) :: input + character(len=329) :: msgbits + integer :: i3 + + call pack_and_decode_bits_with_ckey(input,.false.,.false.,' ', & + 'OTP:BROKEN',msgbits,i3,SFOX_PACK_BAD_OTP) + ntests=ntests+1 + end subroutine expect_invalid_otp + + subroutine pack_and_decode_cq(input,i3,call_out,grid_out) + character(len=*), intent(in) :: input + integer, intent(out) :: i3 + character(len=11), intent(out) :: call_out + character(len=4), intent(out) :: grid_out + character(len=329) :: msgbits + character(len=38) :: c + integer(kind=8) :: n58 + integer :: i, j, n15 + + c=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/' + call pack_and_decode_bits(input,.false.,.false.,' ',0,msgbits,i3) + + call_out=' ' + grid_out=' ' + if(i3.ne.3) return + + read(msgbits(1:58),'(b58)') n58 + do i=11,1,-1 + j=mod(n58,38_8)+1 + call_out(i:i)=c(j:j) + n58=n58/38_8 + enddo + call_out=adjustl(call_out) + read(msgbits(59:73),'(b15)') n15 + call unpackgrid(n15,grid_out) + end subroutine pack_and_decode_cq + + subroutine pack_and_decode_bits(input,more_cqs,send_msg,free_text,otp, & + msgbits,i3) + character(len=*), intent(in) :: input, free_text + logical, intent(in) :: more_cqs, send_msg + integer, intent(in) :: otp + character(len=329), intent(out) :: msgbits + integer, intent(out) :: i3 + + call pack_and_decode_bits_allow_failure(input,more_cqs,send_msg, & + free_text,otp,msgbits,i3,SFOX_PACK_OK) + end subroutine pack_and_decode_bits + + subroutine pack_and_decode_bits_allow_failure(input,more_cqs,send_msg, & + free_text,otp,msgbits,i3,expected_error) + character(len=*), intent(in) :: input, free_text + logical, intent(in) :: more_cqs, send_msg + integer, intent(in) :: otp + integer, intent(in) :: expected_error + character(len=329), intent(out) :: msgbits + integer, intent(out) :: i3 + character(len=10) :: ckey + + write(ckey,1000) otp +1000 format('0000',i6.6) + call pack_and_decode_bits_with_ckey(input,more_cqs,send_msg,free_text, & + ckey,msgbits,i3,expected_error) + end subroutine pack_and_decode_bits_allow_failure + + subroutine pack_and_decode_bits_with_ckey(input,more_cqs,send_msg, & + free_text,ckey,msgbits,i3,expected_error) + character(len=*), intent(in) :: input, free_text, ckey + logical, intent(in) :: more_cqs, send_msg + integer, intent(in) :: expected_error + character(len=329), intent(out) :: msgbits + integer, intent(out) :: i3 + character(len=120) :: line + character(len=26) :: free_text_26 + integer(kind=1) :: xin(0:49), raw(0:49) + logical(kind=1) :: more_cqs_1, send_msg_1 + integer :: i, pack_error + + line=' ' + line=input + free_text_26=' ' + free_text_26=free_text + more_cqs_1=more_cqs + send_msg_1=send_msg + xin=0 + raw=0 + + call sfox_pack(line,ckey,more_cqs_1,send_msg_1,free_text_26,xin, & + pack_error) + if(pack_error.ne.expected_error) then + write(*,1010) trim(input), expected_error, pack_error +1010 format('SuperFox pack status mismatch for "',a,'"; expected ',i0, & + ' got ',i0) + error stop 1 + endif + if(expected_error.ne.SFOX_PACK_OK) then + msgbits='0' + i3=-1 + return + endif + + do i=0,49 + raw(i)=xin(49-i) + enddo + write(msgbits,1020) raw(0:46) +1020 format(47b7.7) + read(msgbits(327:329),'(b3)') i3 + end subroutine pack_and_decode_bits_with_ckey + + subroutine decode_pack28_field(msgbits,first_bit,call_out) + use packjt77, only: unpack28 + character(len=*), intent(in) :: msgbits + integer, intent(in) :: first_bit + character(len=13), intent(out) :: call_out + logical :: success + integer :: n28 + + call_out=' ' + read(msgbits(first_bit:first_bit+27),'(b28)') n28 + call unpack28(n28,call_out,success) + if(.not.success) then + write(*,1050) first_bit, n28 +1050 format('SuperFox pack28 decode failed at bit ',i0,' n28=',i0) + error stop 1 + endif + end subroutine decode_pack28_field + + subroutine assert_hound_present(msgbits,expected_hound) + character(len=*), intent(in) :: msgbits, expected_hound + character(len=13) :: got_hound + integer :: i, first_bit + + do i=1,9 + first_bit=28*i + 1 + call decode_pack28_field(msgbits,first_bit,got_hound) + if(trim(got_hound).eq.expected_hound) return + enddo + + write(*,1060) trim(expected_hound) +1060 format('SuperFox hound call "',a,'" was not present') + error stop 1 + end subroutine assert_hound_present + + subroutine trim_dots(text) + character(len=*), intent(inout) :: text + integer :: i + + do i=len(text),1,-1 + if(text(i:i).ne.'.') exit + text(i:i)=' ' + enddo + end subroutine trim_dots + + subroutine assert_int(label,expected,got) + character(len=*), intent(in) :: label + integer, intent(in) :: expected, got + + if(got.ne.expected) then + write(*,1070) trim(label), expected, got +1070 format(a,' failure; expected ',i0,' got ',i0) + error stop 1 + endif + end subroutine assert_int + + subroutine assert_text(label,expected,got) + character(len=*), intent(in) :: label, expected, got + + if(trim(got).ne.expected) then + write(*,1080) trim(label), trim(expected), trim(got) +1080 format(a,' failure; expected "',a,'" got "',a,'"') + error stop 1 + endif + end subroutine assert_text + +end program test_superfox_pack diff --git a/tests/unit/superfox/test_superfox_tx_handoff.f90 b/tests/unit/superfox/test_superfox_tx_handoff.f90 new file mode 100644 index 00000000..52a8033c --- /dev/null +++ b/tests/unit/superfox/test_superfox_tx_handoff.f90 @@ -0,0 +1,121 @@ +program test_superfox_tx_handoff + + implicit none + + integer, parameter :: NN=79 + integer, parameter :: NWAVE=(160+2)*134400*4 + real :: wave(NWAVE) + integer :: nslots, nfreq, i3bit(5), itone2(NN), itone3(151) + integer :: nslots2, nDataSlots + integer :: pack_error, i3 + integer(kind=1) :: mycall(12), msgbits2(77), xin(0:49), raw(0:49) + logical(kind=1) :: bSuperFox, bMoreCQs, bSendMsg + character(len=40) :: cmsg(5), cmsg2(5) + character(len=26) :: textMsg, freeTextMsg + character(len=120) :: line + character(len=11) :: foxcall + character(len=10) :: ckey + character(len=329) :: msgbits + character(len=13) :: got + integer :: i + + common/foxcom/wave,nslots,nfreq,i3bit,cmsg,mycall,textMsg,bMoreCQs,bSendMsg + common/foxcom2/itone2,msgbits2 + common/foxcom3/nslots2,cmsg2,itone3 + + wave=0.0 + nslots=4 + nfreq=750 + i3bit=0 + cmsg=' ' + mycall=0 + textMsg='HELLO SUPERFOX' + bMoreCQs=.false. + bSendMsg=.true. + + cmsg(1)='K1RAA K1JT -01' + cmsg(2)='K1RAB K1JT -02' + cmsg(3)='K1RAC K1JT -03' + cmsg(4)='K1RAD K1JT -04' + + bSuperFox=.true. + call foxgen(bSuperFox,' ') + + call assert_int('foxgen SuperFox row count',5,nslots2) + call assert_text('foxgen fourth data row','K1RAD K1JT -04',cmsg2(4)(1:14)) + call assert_text('foxgen free text row','HELLO SUPERFOX',cmsg2(5)(1:14)) + if(cmsg2(5)(39:39).ne.'1') error stop 'foxgen did not flag free text row' + + freeTextMsg=' ' + bMoreCQs=cmsg2(1)(40:40).eq.'1' + bSendMsg=cmsg2(nslots2)(39:39).eq.'1' + nDataSlots=nslots2 + if(bSendMsg) then + freeTextMsg=cmsg2(nslots2)(1:26) + nDataSlots=nslots2-1 + if(nDataSlots.gt.4) nDataSlots=4 + endif + + call foxgen2(nDataSlots,cmsg2,line,foxcall) + ckey='0000000000' + call sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error) + call assert_int('SuperFox handoff pack status',0,pack_error) + + do i=0,49 + raw(i)=xin(49-i) + enddo + write(msgbits,1000) raw(0:46) +1000 format(47b7.7) + read(msgbits(327:329),'(b3)') i3 + call assert_int('SuperFox handoff message type',2,i3) + + call decode_pack28_field(msgbits,29,got) + call assert_text('first SuperFox report hound','K1RAA',got) + call decode_pack28_field(msgbits,57,got) + call assert_text('second SuperFox report hound','K1RAB',got) + call decode_pack28_field(msgbits,85,got) + call assert_text('third SuperFox report hound','K1RAC',got) + call decode_pack28_field(msgbits,113,got) + call assert_text('fourth SuperFox report hound','K1RAD',got) + call assert_text('SuperFox handoff free text','HELLO SUPERFOX',freeTextMsg(1:14)) + + write(*,*) 'superfox tx handoff test passed' + +contains + + subroutine decode_pack28_field(bits,first_bit,call_out) + use packjt77, only: unpack28 + character(len=*), intent(in) :: bits + integer, intent(in) :: first_bit + character(len=13), intent(out) :: call_out + logical :: success + integer :: n28 + + call_out=' ' + read(bits(first_bit:first_bit+27),'(b28)') n28 + call unpack28(n28,call_out,success) + if(.not.success) error stop 'pack28 decode failed' + end subroutine decode_pack28_field + + subroutine assert_int(label,expected,got) + character(len=*), intent(in) :: label + integer, intent(in) :: expected, got + + if(got.ne.expected) then + write(*,1010) trim(label), expected, got +1010 format(a,' failure; expected ',i0,' got ',i0) + error stop 1 + endif + end subroutine assert_int + + subroutine assert_text(label,expected,got) + character(len=*), intent(in) :: label, expected, got + + if(trim(got).ne.expected) then + write(*,1020) trim(label), trim(expected), trim(got) +1020 format(a,' failure; expected "',a,'" got "',a,'"') + error stop 1 + endif + end subroutine assert_text + +end program test_superfox_tx_handoff diff --git a/tests/unit/superfox/test_superfox_unpack.f90 b/tests/unit/superfox/test_superfox_unpack.f90 new file mode 100644 index 00000000..8a243ed4 --- /dev/null +++ b/tests/unit/superfox/test_superfox_unpack.f90 @@ -0,0 +1,28 @@ +program test_superfox_unpack + + implicit none + + integer*1 xin(0:49), xdec(0:49) + logical*1 more_cqs, send_msg + character*120 line + character*26 free_text + character*10 ckey + character*13 foxcall + integer notp, pack_error + + line='CQ K1JT FN20' + free_text='2S/IZFUZBRXJF ' + ckey='0000123456' + more_cqs=.false. + send_msg=.true. + + call sfox_pack(line,ckey,more_cqs,send_msg,free_text,xin,pack_error) + if(pack_error.ne.0) error stop 'sfox_pack failed' + + xdec=xin(49:0:-1) + + notp=0 + foxcall='' + call sfox_unpack(123456,xdec,0,1500.0,0.0,foxcall,notp) + +end program test_superfox_unpack diff --git a/tests/unit/superfox/test_superfox_unpack_unsupported.f90 b/tests/unit/superfox/test_superfox_unpack_unsupported.f90 new file mode 100644 index 00000000..c4f5d86c --- /dev/null +++ b/tests/unit/superfox/test_superfox_unpack_unsupported.f90 @@ -0,0 +1,35 @@ +program test_superfox_unpack_unsupported + + implicit none + + integer*1 xin(0:49), xdec(0:49) + logical*1 more_cqs, send_msg + character*120 line + character*26 free_text + character*10 ckey + character*13 foxcall + character*329 msgbits + integer notp, pack_error + + line='K1JT W1AW' + free_text=' ' + ckey='0000123456' + more_cqs=.false. + send_msg=.false. + + call sfox_pack(line,ckey,more_cqs,send_msg,free_text,xin,pack_error) + if(pack_error.ne.0) error stop 'sfox_pack failed' + + xdec=xin(49:0:-1) + write(msgbits,1000) xdec(0:46) +1000 format(47b7.7) + msgbits(327:329)='001' + read(msgbits,1001) xdec(0:46) +1001 format(47b7) + + notp=0 + foxcall='' + call sfox_unpack(123456,xdec,0,1500.0,0.0,foxcall,notp) + write(*,*) 'unsupported i3=1 ignored' + +end program test_superfox_unpack_unsupported diff --git a/tests/unit/tci/CMakeLists.txt b/tests/unit/tci/CMakeLists.txt new file mode 100644 index 00000000..abe6fed1 --- /dev/null +++ b/tests/unit/tci/CMakeLists.txt @@ -0,0 +1,55 @@ +add_executable (test_tci_stream + test_tci_stream.cpp +) +target_link_libraries (test_tci_stream Qt5::Test) +add_test (NAME test_tci_stream COMMAND test_tci_stream) + +add_executable (test_tci_protocol + test_tci_protocol.cpp +) +target_link_libraries (test_tci_protocol Qt5::Test) +add_test (NAME test_tci_protocol COMMAND test_tci_protocol) + +add_library (tci_simulator STATIC + TciSimScript.cpp + TciSimScript.hpp + TciSimServer.cpp + TciSimServer.hpp +) +target_include_directories (tci_simulator PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries (tci_simulator PUBLIC Qt5::Core Qt5::Network Qt5::WebSockets) + +add_executable (test_tci_sim_smoke test_tci_sim_smoke.cpp) +target_link_libraries (test_tci_sim_smoke PRIVATE tci_simulator Qt5::Test) +add_test (NAME test_tci_sim_smoke COMMAND test_tci_sim_smoke) +set_tests_properties (test_tci_sim_smoke PROPERTIES TIMEOUT 30) + +add_executable (test_tci_transceiver_characterization + test_tci_transceiver_characterization.cpp +) +target_link_libraries (test_tci_transceiver_characterization PRIVATE + tci_simulator wsjt_qt wsjt_fort_common Qt5::Test) +add_test (NAME test_tci_transceiver_characterization + COMMAND test_tci_transceiver_characterization) +set_tests_properties (test_tci_transceiver_characterization PROPERTIES + COST 32 + TIMEOUT 120) + +add_executable (test_transceiver_base_period test_transceiver_base_period.cpp) +target_include_directories (test_transceiver_base_period PRIVATE ${CMAKE_SOURCE_DIR}) +target_link_libraries (test_transceiver_base_period PRIVATE wsjt_qt Qt5::Test) +add_test (NAME test_transceiver_base_period COMMAND test_transceiver_base_period) + +add_executable (test_tci_receive_ownership + test_tci_receive_ownership.cpp + ${CMAKE_SOURCE_DIR}/FastDecode.cpp) +target_include_directories (test_tci_receive_ownership PRIVATE ${CMAKE_BINARY_DIR}) +target_link_libraries (test_tci_receive_ownership PRIVATE + tci_simulator wsjt_qt wsjt_fort_common Qt5::Test) +add_test (NAME test_tci_receive_ownership COMMAND test_tci_receive_ownership) +set_tests_properties (test_tci_receive_ownership PROPERTIES + TIMEOUT 120 LABELS "receive-handoff;tci-receive") +if (WSJT_ENABLE_TSAN) + set_tests_properties (test_tci_receive_ownership PROPERTIES + ENVIRONMENT "TSAN_OPTIONS=halt_on_error=1:exitcode=66") +endif () diff --git a/tests/unit/tci/TciSimScript.cpp b/tests/unit/tci/TciSimScript.cpp new file mode 100644 index 00000000..ff8b6400 --- /dev/null +++ b/tests/unit/tci/TciSimScript.cpp @@ -0,0 +1,416 @@ +#include "TciSimScript.hpp" + +#include <utility> + +#include <QEventLoop> + +#include "moc_TciSimScript.cpp" + +TciSimScript::TciSimScript (TciSimServer * server, QObject * parent) + : QObject {parent} + , server_ {server} +{ + poll_timer_.setInterval (5); + delay_timer_.setSingleShot (true); + overall_timer_.setSingleShot (true); + connect (&poll_timer_, &QTimer::timeout, + this, &TciSimScript::poll_step); + connect (&delay_timer_, &QTimer::timeout, + this, &TciSimScript::delayed_step_ready); + connect (&overall_timer_, &QTimer::timeout, + this, &TciSimScript::overall_timeout); + connect (server_, &TciSimServer::client_gone, this, + [this] (int generation) + { + if (generation != close_generation_) return; + close_observed_ = true; + cursor_ = server_->cursor (server_->transcript ().size ()); + }); +} + +TciSimScript& TciSimScript::greet ( + TciSimGreeting greeting_value, int timeout_ms) +{ + steps_.push_back ({StepKind::Greet, {}, {}, qMax (0, timeout_ms), + greeting_value}); + return *this; +} + +TciSimScript& TciSimScript::expect ( + QString verb, ArgsPredicate predicate, int timeout_ms) +{ + append_expectation (StepKind::Expect, std::move (verb), + std::move (predicate), timeout_ms); + return *this; +} + +TciSimScript& TciSimScript::reply (QString text, int delay_ms) +{ + steps_.push_back ({StepKind::Reply, std::move (text), {}, + qMax (0, delay_ms), TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::push (QString text, int delay_ms) +{ + steps_.push_back ({StepKind::Push, std::move (text), {}, + qMax (0, delay_ms), TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::withhold ( + QString verb, ArgsPredicate predicate, int timeout_ms) +{ + append_expectation (StepKind::Withhold, std::move (verb), + std::move (predicate), timeout_ms); + return *this; +} + +TciSimScript& TciSimScript::delay (int delay_ms) +{ + steps_.push_back ({StepKind::Delay, {}, {}, qMax (0, delay_ms), + TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::close_normally (QString reason) +{ + steps_.push_back ({StepKind::CloseNormally, std::move (reason), {}, 2000, + TciSimGreeting::Minimal}); + return *this; +} + +TciSimScript& TciSimScript::reconnect (int timeout_ms) +{ + steps_.push_back ({StepKind::Reconnect, {}, {}, qMax (0, timeout_ms), + TciSimGreeting::Minimal}); + return *this; +} + +void TciSimScript::start (int overall_timeout_ms) +{ + if (running_) return; + + running_ = true; + succeeded_ = false; + current_step_ = 0; + reconnect_after_generation_ = server_->connection_generation (); + active_connection_generation_ = server_->client_connected () + ? server_->connection_generation () : 0; + last_consumed_generation_ = 0; + delayed_step_generation_ = 0; + close_generation_ = 0; + close_observed_ = false; + has_consumed_expectation_ = false; + close_requested_ = false; + cursor_ = server_->cursor (); + last_error_.clear (); + overall_timer_.start (qMax (1, overall_timeout_ms)); + QTimer::singleShot (0, this, &TciSimScript::execute_step); +} + +bool TciSimScript::run (int overall_timeout_ms) +{ + QEventLoop loop; + connect (this, &TciSimScript::finished, &loop, &QEventLoop::quit); + start (overall_timeout_ms); + if (running_) loop.exec (); + return succeeded_; +} + +void TciSimScript::stop () +{ + if (running_) fail (QStringLiteral ("script stopped")); +} + +bool TciSimScript::running () const +{ + return running_; +} + +bool TciSimScript::succeeded () const +{ + return succeeded_; +} + +int TciSimScript::failed_step () const +{ + return succeeded_ ? -1 : current_step_ + 1; +} + +QString TciSimScript::last_error () const +{ + return last_error_; +} + +QStringList TciSimScript::greeting_messages (TciSimGreeting greeting) +{ + switch (greeting) + { + case TciSimGreeting::Thetis: + return { + QStringLiteral ("protocol:Thetis,1.6"), + QStringLiteral ("device:HermesLite"), + QStringLiteral ("trx_count:1"), + QStringLiteral ("channels_count:2"), + QStringLiteral ("vfo:0,0,14074000"), + QStringLiteral ("vfo:0,1,14075000"), + QStringLiteral ("modulation:0,digu"), + QStringLiteral ("split_enable:0,false"), + QStringLiteral ("trx:0,false"), + QStringLiteral ("start"), + QStringLiteral ("ready"), + }; + case TciSimGreeting::Minimal: + return { + QStringLiteral ("protocol:TCI,1.6"), + QStringLiteral ("start"), + QStringLiteral ("ready"), + }; + } + return {}; +} + +void TciSimScript::execute_step () +{ + if (!running_) return; + if (current_step_ >= static_cast<int> (steps_.size ())) + { + finish (true); + return; + } + + auto const& step = steps_.at (current_step_); + switch (step.kind) + { + case StepKind::Greet: + if (!server_->client_connected ()) + { + start_polling (step.timeout_ms); + return; + } + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + for (auto const& message : greeting_messages (step.greeting)) + { + server_->send_text (message); + } + complete_step (); + return; + case StepKind::Expect: + case StepKind::Withhold: + if (current_expectation_satisfied ()) + { + complete_step (); + return; + } + start_polling (step.timeout_ms); + return; + case StepKind::Reply: + if (!has_consumed_expectation_ + || last_consumed_generation_ != active_connection_generation_) + { + fail (QStringLiteral ( + "reply requires an expectation consumed on the active connection")); + return; + } + delayed_step_generation_ = last_consumed_generation_; + if (step.timeout_ms > 0) + { + delay_timer_.start (step.timeout_ms); + } + else + { + delayed_step_ready (); + } + return; + case StepKind::Push: + case StepKind::Delay: + delayed_step_generation_ = active_connection_generation_; + if (step.timeout_ms > 0) + { + delay_timer_.start (step.timeout_ms); + } + else + { + delayed_step_ready (); + } + return; + case StepKind::CloseNormally: + if (!close_requested_) + { + if (!server_->client_connected ()) + { + fail (QStringLiteral ("cannot close without a connected client")); + return; + } + close_generation_ = server_->connection_generation (); + reconnect_after_generation_ = close_generation_; + close_observed_ = false; + close_requested_ = true; + server_->close_client (step.text); + start_polling (step.timeout_ms); + } + return; + case StepKind::Reconnect: + if (server_->client_connected () + && server_->connection_generation () > reconnect_after_generation_) + { + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + complete_step (); + return; + } + start_polling (step.timeout_ms); + return; + } +} + +void TciSimScript::poll_step () +{ + if (!running_) return; + auto const& step = steps_.at (current_step_); + bool complete {false}; + if (step.kind == StepKind::Greet) + { + complete = server_->client_connected (); + if (complete) + { + poll_timer_.stop (); + execute_step (); + return; + } + } + else if (step.kind == StepKind::Reconnect) + { + complete = server_->client_connected () + && server_->connection_generation () > reconnect_after_generation_; + } + else if (step.kind == StepKind::CloseNormally) + { + complete = close_observed_; + } + else + { + complete = current_expectation_satisfied (); + } + + if (complete) + { + poll_timer_.stop (); + if (step.kind == StepKind::CloseNormally) + { + close_requested_ = false; + } + else if (step.kind == StepKind::Reconnect) + { + active_connection_generation_ = server_->connection_generation (); + last_consumed_generation_ = 0; + has_consumed_expectation_ = false; + } + complete_step (); + } + else if (step_elapsed_.elapsed () >= step.timeout_ms) + { + fail (QStringLiteral ("%1 timed out after %2 ms") + .arg (step_description (step)).arg (step.timeout_ms)); + } +} + +void TciSimScript::delayed_step_ready () +{ + if (!running_) return; + auto const& step = steps_.at (current_step_); + if (step.kind == StepKind::Reply || step.kind == StepKind::Push) + { + if (server_->client_connected () + && server_->connection_generation () == delayed_step_generation_) + { + server_->send_text (step.text); + } + else if (step.kind == StepKind::Reply) + { + fail (QStringLiteral ("reply target connection is no longer active")); + return; + } + } + complete_step (); +} + +void TciSimScript::overall_timeout () +{ + if (running_) fail (QStringLiteral ("overall script timeout")); +} + +void TciSimScript::append_expectation ( + StepKind kind, QString verb, ArgsPredicate predicate, int timeout_ms) +{ + steps_.push_back ({kind, std::move (verb), std::move (predicate), + qMax (0, timeout_ms), TciSimGreeting::Minimal}); +} + +void TciSimScript::start_polling (int) +{ + step_elapsed_.restart (); + poll_timer_.start (); +} + +void TciSimScript::complete_step () +{ + poll_timer_.stop (); + delay_timer_.stop (); + ++current_step_; + QTimer::singleShot (0, this, &TciSimScript::execute_step); +} + +void TciSimScript::fail (QString reason) +{ + auto const step_number = current_step_ + 1; + last_error_ = QStringLiteral ("step %1: %2\nTranscript:\n%3") + .arg (step_number).arg (reason, server_->transcript_text ()); + finish (false); +} + +void TciSimScript::finish (bool succeeded_value) +{ + poll_timer_.stop (); + delay_timer_.stop (); + overall_timer_.stop (); + running_ = false; + succeeded_ = succeeded_value; + emit finished (succeeded_); +} + +bool TciSimScript::current_expectation_satisfied () +{ + auto const& step = steps_.at (current_step_); + TciSimServer::Message message; + if (!server_->consume (&cursor_, TciSimServer::Direction::ClientToServer, + step.text, &message, step.predicate, + active_connection_generation_)) + { + return false; + } + last_consumed_generation_ = message.connection_generation; + has_consumed_expectation_ = true; + return true; +} + +QString TciSimScript::step_description (Step const& step) const +{ + switch (step.kind) + { + case StepKind::Greet: return QStringLiteral ("waiting to greet a client"); + case StepKind::Expect: return QStringLiteral ("expecting %1").arg (step.text); + case StepKind::Reply: return QStringLiteral ("replying with %1").arg (step.text); + case StepKind::Push: return QStringLiteral ("pushing %1").arg (step.text); + case StepKind::Withhold: + return QStringLiteral ("expecting and withholding %1").arg (step.text); + case StepKind::Delay: return QStringLiteral ("delaying"); + case StepKind::CloseNormally: return QStringLiteral ("closing the client"); + case StepKind::Reconnect: return QStringLiteral ("waiting for reconnection"); + } + return QStringLiteral ("running script step"); +} diff --git a/tests/unit/tci/TciSimScript.hpp b/tests/unit/tci/TciSimScript.hpp new file mode 100644 index 00000000..c8f0a3b1 --- /dev/null +++ b/tests/unit/tci/TciSimScript.hpp @@ -0,0 +1,116 @@ +#ifndef TCI_SIM_SCRIPT_HPP__ +#define TCI_SIM_SCRIPT_HPP__ + +#include <functional> +#include <vector> + +#include <QElapsedTimer> +#include <QObject> +#include <QString> +#include <QStringList> +#include <QTimer> + +#include "TciSimServer.hpp" + +enum class TciSimGreeting +{ + Thetis, + Minimal, +}; + +class TciSimScript final + : public QObject +{ + Q_OBJECT + +public: + using ArgsPredicate = std::function<bool (QStringList const&)>; + + explicit TciSimScript (TciSimServer * server, QObject * parent = nullptr); + + TciSimScript& greet (TciSimGreeting greeting = TciSimGreeting::Thetis, + int timeout_ms = 2000); + TciSimScript& expect (QString verb, ArgsPredicate predicate = {}, + int timeout_ms = 2000); + TciSimScript& reply (QString text, int delay_ms = 0); + TciSimScript& push (QString text, int delay_ms = 0); + TciSimScript& withhold (QString verb, ArgsPredicate predicate = {}, + int timeout_ms = 2000); + TciSimScript& delay (int delay_ms); + TciSimScript& close_normally ( + QString reason = QStringLiteral ("scripted disconnect")); + TciSimScript& reconnect (int timeout_ms = 2000); + + void start (int overall_timeout_ms = 10000); + bool run (int overall_timeout_ms = 10000); + void stop (); + + bool running () const; + bool succeeded () const; + int failed_step () const; + QString last_error () const; + + static QStringList greeting_messages (TciSimGreeting greeting); + +signals: + void finished (bool succeeded); + +private slots: + void execute_step (); + void poll_step (); + void delayed_step_ready (); + void overall_timeout (); + +private: + enum class StepKind + { + Greet, + Expect, + Reply, + Push, + Withhold, + Delay, + CloseNormally, + Reconnect, + }; + + struct Step + { + StepKind kind; + QString text; + ArgsPredicate predicate; + int timeout_ms {0}; + TciSimGreeting greeting {TciSimGreeting::Minimal}; + }; + + void append_expectation (StepKind kind, QString verb, + ArgsPredicate predicate, int timeout_ms); + void start_polling (int timeout_ms); + void complete_step (); + void fail (QString reason); + void finish (bool succeeded); + bool current_expectation_satisfied (); + QString step_description (Step const& step) const; + + TciSimServer * server_; + std::vector<Step> steps_; + TciSimServer::Cursor cursor_; + QTimer poll_timer_; + QTimer delay_timer_; + QTimer overall_timer_; + QElapsedTimer step_elapsed_; + int current_step_ {-1}; + int reconnect_after_generation_ {0}; + int active_connection_generation_ {0}; + int last_consumed_generation_ {0}; + int delayed_step_generation_ {0}; + int close_generation_ {0}; + bool close_observed_ {false}; + bool has_consumed_expectation_ {false}; + bool close_requested_ {false}; + bool running_ {false}; + bool succeeded_ {false}; + QString last_error_; +}; + +#endif // TCI_SIM_SCRIPT_HPP__ diff --git a/tests/unit/tci/TciSimServer.cpp b/tests/unit/tci/TciSimServer.cpp new file mode 100644 index 00000000..95296232 --- /dev/null +++ b/tests/unit/tci/TciSimServer.cpp @@ -0,0 +1,328 @@ +#include "TciSimServer.hpp" + +#include <utility> + +#include <QEventLoop> +#include <QHostAddress> +#include <QTimer> +#include <QUrl> +#include <QtWebSockets/QWebSocket> +#include <QtWebSockets/QWebSocketServer> + +#include "moc_TciSimServer.cpp" + +TciSimServer::TciSimServer (QObject * parent) + : QObject {parent} + , server_ {new QWebSocketServer {QStringLiteral ("TCI simulator"), + QWebSocketServer::NonSecureMode, this}} + , client_ {nullptr} +{ + connect (server_, &QWebSocketServer::newConnection, + this, &TciSimServer::on_new_connection); +} + +TciSimServer::~TciSimServer () +{ + close (); +} + +bool TciSimServer::listen () +{ + if (server_->isListening ()) return true; + if (!server_->listen (QHostAddress::LocalHost, 0)) return false; + port_ = server_->serverPort (); + return true; +} + +void TciSimServer::close () +{ + if (client_) + { + client_->close (QWebSocketProtocol::CloseCodeNormal, + QStringLiteral ("simulator done")); + client_ = nullptr; + } + server_->close (); + port_ = 0; +} + +quint16 TciSimServer::port () const +{ + return port_; +} + +QString TciSimServer::url () const +{ + return QStringLiteral ("ws://127.0.0.1:%1").arg (port_); +} + +bool TciSimServer::client_connected () const +{ + return client_ && client_->state () == QAbstractSocket::ConnectedState; +} + +bool TciSimServer::client_disconnected () const +{ + return !client_; +} + +int TciSimServer::connection_generation () const +{ + return connection_generation_; +} + +int TciSimServer::connection_count () const +{ + return connection_count_; +} + +void TciSimServer::send_text (QString text) +{ + if (!client_connected ()) return; + if (!text.endsWith (';')) text += ';'; + record_text (Direction::ServerToClient, text, connection_generation_); + client_->sendTextMessage (text); +} + +bool TciSimServer::send_binary (QByteArray const& data) +{ + return client_connected () && client_->sendBinaryMessage (data) == data.size (); +} + +bool TciSimServer::flush () +{ + return client_connected () && client_->flush (); +} + +void TciSimServer::send_text_later (QString text, int delay_ms) +{ + auto const generation = connection_generation_; + QTimer::singleShot (qMax (0, delay_ms), this, + [this, generation, text = std::move (text)] () mutable + { + if (client_connected () + && connection_generation_ == generation) + { + send_text (std::move (text)); + } + }); +} + +void TciSimServer::close_client (QString const& reason) +{ + if (client_) + { + client_->close (QWebSocketProtocol::CloseCodeNormal, reason); + } +} + +void TciSimServer::abort_client () +{ + if (client_) client_->abort (); +} + +QVector<TciSimServer::Message> const& TciSimServer::transcript () const +{ + return transcript_; +} + +QVector<TciSimServer::Frame> const& TciSimServer::frames () const +{ + return frames_; +} + +TciSimServer::Cursor TciSimServer::cursor (int start_index) const +{ + return {qBound (0, start_index, transcript_.size ())}; +} + +bool TciSimServer::consume ( + Cursor * cursor_value, Direction direction, QString const& verb, + Message * message, + std::function<bool (QStringList const&)> const& predicate, + int connection_generation) const +{ + if (!cursor_value) return false; + + for (int i = qMax (0, cursor_value->next_index); i < transcript_.size (); ++i) + { + auto const& candidate = transcript_.at (i); + cursor_value->next_index = i + 1; + if (candidate.direction != direction || candidate.verb != verb) continue; + if (connection_generation > 0 + && candidate.connection_generation != connection_generation) continue; + if (predicate && !predicate (candidate.args)) continue; + if (message) *message = candidate; + return true; + } + cursor_value->next_index = transcript_.size (); + return false; +} + +QVector<TciSimServer::Message> TciSimServer::messages ( + Direction direction, QString const& verb) const +{ + QVector<Message> result; + for (auto const& message : transcript_) + { + if (message.direction == direction + && (verb.isEmpty () || message.verb == verb)) + { + result.append (message); + } + } + return result; +} + +int TciSimServer::count (Direction direction, QString const& verb) const +{ + int result {0}; + for (auto const& message : transcript_) + { + if (message.direction == direction + && (verb.isEmpty () || message.verb == verb)) + { + ++result; + } + } + return result; +} + +int TciSimServer::index_of ( + Direction direction, QString const& verb, int occurrence) const +{ + if (occurrence < 0) return -1; + for (int i = 0; i < transcript_.size (); ++i) + { + auto const& message = transcript_.at (i); + if (message.direction == direction && message.verb == verb + && occurrence-- == 0) + { + return i; + } + } + return -1; +} + +bool TciSimServer::occurs_before ( + Direction first_direction, QString const& first_verb, + Direction second_direction, QString const& second_verb) const +{ + auto const first = index_of (first_direction, first_verb); + auto const second = index_of (second_direction, second_verb); + return first >= 0 && second >= 0 && first < second; +} + +QString TciSimServer::transcript_text () const +{ + QStringList lines; + lines.reserve (frames_.size ()); + for (auto const& frame : frames_) + { + auto const arrow = frame.direction == Direction::ClientToServer + ? QStringLiteral ("client -> server") + : QStringLiteral ("server -> client"); + lines.append (QStringLiteral ("frame #%1 connection %2 %3: %4") + .arg (frame.ordinal) + .arg (frame.connection_generation) + .arg (arrow, frame.raw)); + } + return lines.join ('\n'); +} + +bool TciSimServer::wait_for ( + std::function<bool ()> const& predicate, int timeout_ms) +{ + if (predicate ()) return true; + + QEventLoop loop; + QTimer poller; + QTimer timeout; + bool matched {false}; + poller.setInterval (5); + timeout.setSingleShot (true); + connect (&poller, &QTimer::timeout, &loop, + [&predicate, &matched, &loop] () + { + if (!predicate ()) return; + matched = true; + loop.quit (); + }); + connect (&timeout, &QTimer::timeout, &loop, &QEventLoop::quit); + poller.start (); + timeout.start (qMax (0, timeout_ms)); + loop.exec (); + return matched || predicate (); +} + +void TciSimServer::on_new_connection () +{ + while (auto * candidate = server_->nextPendingConnection ()) + { + if (client_) + { + candidate->close (QWebSocketProtocol::CloseCodePolicyViolated, + QStringLiteral ("one client at a time")); + candidate->deleteLater (); + continue; + } + + client_ = candidate; + connection_generation_ = ++connection_count_; + client_->setProperty ("tciConnectionGeneration", connection_generation_); + connect (client_, &QWebSocket::textMessageReceived, + this, &TciSimServer::on_text_message); + connect (client_, &QWebSocket::disconnected, + this, &TciSimServer::on_disconnected); + emit client_arrived (connection_generation_); + } +} + +void TciSimServer::on_text_message (QString const& text) +{ + auto * socket = qobject_cast<QWebSocket *> (sender ()); + auto const generation = socket + ? socket->property ("tciConnectionGeneration").toInt () + : connection_generation_; + record_text (Direction::ClientToServer, text, generation); + emit text_received (text, generation); +} + +void TciSimServer::on_disconnected () +{ + auto * socket = qobject_cast<QWebSocket *> (sender ()); + auto const generation = socket + ? socket->property ("tciConnectionGeneration").toInt () + : connection_generation_; + if (socket == client_) client_ = nullptr; + if (socket) socket->deleteLater (); + emit client_gone (generation); +} + +void TciSimServer::record_text ( + Direction direction, QString const& text, int generation) +{ + frames_.append ({direction, generation, next_frame_ordinal_++, text}); + auto const commands = text.split (';', Qt::SkipEmptyParts); + for (auto const& command : commands) + { + transcript_.append (parse_message (direction, generation, + next_ordinal_++, command)); + } +} + +TciSimServer::Message TciSimServer::parse_message ( + Direction direction, int generation, quint64 ordinal, QString const& raw) +{ + Message result {direction, generation, ordinal, raw, {}, {}}; + auto const separator = raw.indexOf (':'); + if (separator < 0) + { + result.verb = raw.trimmed (); + return result; + } + + result.verb = raw.left (separator).trimmed (); + result.args = raw.mid (separator + 1).split (',', Qt::KeepEmptyParts); + return result; +} diff --git a/tests/unit/tci/TciSimServer.hpp b/tests/unit/tci/TciSimServer.hpp new file mode 100644 index 00000000..c64c0a09 --- /dev/null +++ b/tests/unit/tci/TciSimServer.hpp @@ -0,0 +1,111 @@ +#ifndef TCI_SIM_SERVER_HPP__ +#define TCI_SIM_SERVER_HPP__ + +#include <functional> + +#include <QObject> +#include <QString> +#include <QStringList> +#include <QVector> + +class QWebSocket; +class QWebSocketServer; + +class TciSimServer final + : public QObject +{ + Q_OBJECT + +public: + enum class Direction + { + ClientToServer, + ServerToClient, + }; + + struct Message + { + Direction direction; + int connection_generation; + quint64 ordinal; + QString raw; + QString verb; + QStringList args; + }; + + struct Frame + { + Direction direction; + int connection_generation; + quint64 ordinal; + QString raw; + }; + + struct Cursor + { + int next_index {0}; + }; + + explicit TciSimServer (QObject * parent = nullptr); + ~TciSimServer () override; + + bool listen (); + void close (); + quint16 port () const; + QString url () const; + + bool client_connected () const; + bool client_disconnected () const; + int connection_generation () const; + int connection_count () const; + + void send_text (QString text); + bool send_binary (QByteArray const& data); + bool flush (); + void send_text_later (QString text, int delay_ms); + void close_client (QString const& reason = QStringLiteral ("simulator close")); + void abort_client (); + + QVector<Message> const& transcript () const; + QVector<Frame> const& frames () const; + Cursor cursor (int start_index = 0) const; + bool consume (Cursor * cursor, Direction direction, QString const& verb, + Message * message = nullptr, + std::function<bool (QStringList const&)> const& predicate = {}, + int connection_generation = 0) const; + QVector<Message> messages (Direction direction, QString const& verb = {}) const; + int count (Direction direction, QString const& verb = {}) const; + int index_of (Direction direction, QString const& verb, int occurrence = 0) const; + bool occurs_before (Direction first_direction, QString const& first_verb, + Direction second_direction, QString const& second_verb) const; + QString transcript_text () const; + + bool wait_for (std::function<bool ()> const& predicate, int timeout_ms); + +signals: + void client_arrived (int connection_generation); + void client_gone (int connection_generation); + void text_received (QString const& raw, int connection_generation); + +private slots: + void on_new_connection (); + void on_text_message (QString const& text); + void on_disconnected (); + +private: + void record_text (Direction direction, QString const& text, int generation); + static Message parse_message (Direction direction, int generation, + quint64 ordinal, QString const& raw); + + QWebSocketServer * server_; + QWebSocket * client_; + quint16 port_ {0}; + int connection_generation_ {0}; + int connection_count_ {0}; + quint64 next_ordinal_ {0}; + quint64 next_frame_ordinal_ {0}; + QVector<Message> transcript_; + QVector<Frame> frames_; +}; + +#endif // TCI_SIM_SERVER_HPP__ diff --git a/tests/unit/tci/test_tci_protocol.cpp b/tests/unit/tci/test_tci_protocol.cpp new file mode 100644 index 00000000..95b4e01d --- /dev/null +++ b/tests/unit/tci/test_tci_protocol.cpp @@ -0,0 +1,110 @@ +#include <limits> + +#include <QtTest> + +#include "Transceiver/TCIProtocol.hpp" + +class TestTciProtocol final + : public QObject +{ + Q_OBJECT + +private slots: + void parsesFrequency_data () + { + QTest::addColumn<QString> ("text"); + QTest::addColumn<quint64> ("expected"); + + QTest::newRow ("ordinary HF") << QString {"14074000"} << quint64 {14074000u}; + QTest::newRow ("below signed 32-bit boundary") << QString {"2147483647"} << quint64 {2147483647u}; + QTest::newRow ("at signed 32-bit boundary") << QString {"2147483648"} << quint64 {2147483648u}; + QTest::newRow ("above signed 32-bit boundary") << QString {"2147483649"} << quint64 {2147483649u}; + QTest::newRow ("10.368 GHz") << QString {"10368000000"} << quint64 {10368000000u}; + QTest::newRow ("upper supported TCI range") << QString {"250000000000"} << quint64 {250000000000u}; + QTest::newRow ("leading zeros") << QString {"00014074000"} << quint64 {14074000u}; + QTest::newRow ("zero") << QString {"0"} << quint64 {0u}; + QTest::newRow ("quint64 maximum") + << QString {"18446744073709551615"} << (std::numeric_limits<quint64>::max) (); + } + + void parsesFrequency () + { + QFETCH (QString, text); + QFETCH (quint64, expected); + + quint64 frequency {99u}; + QVERIFY (TciProtocol::parse_frequency (text, &frequency)); + QCOMPARE (frequency, expected); + } + + void rejectsMalformedFrequency_data () + { + QTest::addColumn<QString> ("text"); + + QTest::newRow ("empty") << QString {}; + QTest::newRow ("negative") << QString {"-14074000"}; + QTest::newRow ("positive sign") << QString {"+14074000"}; + QTest::newRow ("leading whitespace") << QString {" 14074000"}; + QTest::newRow ("trailing whitespace") << QString {"14074000 "}; + QTest::newRow ("group separator") << QString {"14,074,000"}; + QTest::newRow ("decimal") << QString {"14074.000"}; + QTest::newRow ("exponent") << QString {"14074e3"}; + QTest::newRow ("trailing text") << QString {"14074000Hz"}; + QTest::newRow ("unicode digit") << QString::fromUtf8 ("١٤٠٧٤٠٠٠"); + QTest::newRow ("replacement character") + << QString {"14"} + QChar {QChar::ReplacementCharacter} + QString {"074000"}; + QTest::newRow ("overflow") << QString {"18446744073709551616"}; + } + + void rejectsMalformedFrequency () + { + QFETCH (QString, text); + + quint64 frequency {99u}; + QVERIFY (!TciProtocol::parse_frequency (text, &frequency)); + QCOMPARE (frequency, quint64 {99u}); + } + + void rejectsMissingOutput () + { + QVERIFY (!TciProtocol::parse_frequency (QString {"14074000"}, nullptr)); + } + + void comparesFrequencyDifference_data () + { + QTest::addColumn<quint64> ("lhs"); + QTest::addColumn<quint64> ("rhs"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("ordinary HF below threshold") + << quint64 {14074000u} << quint64 {15073999u} << false; + QTest::newRow ("below threshold") + << quint64 {10368000000u} << quint64 {10368999999u} << false; + QTest::newRow ("exact threshold") + << quint64 {10368000000u} << quint64 {10369000000u} << false; + QTest::newRow ("above threshold") + << quint64 {10368000000u} << quint64 {10369000001u} << true; + QTest::newRow ("above threshold reversed") + << quint64 {10369000001u} << quint64 {10368000000u} << true; + QTest::newRow ("signed boundary adjacent") + << quint64 {2147483647u} << quint64 {2147483648u} << false; + QTest::newRow ("upper supported range") + << quint64 {250000000000u} << quint64 {249998999999u} << true; + QTest::newRow ("quint64 upper edge") + << (std::numeric_limits<quint64>::max) () + << (std::numeric_limits<quint64>::max) () - quint64 {1000001u} << true; + } + + void comparesFrequencyDifference () + { + QFETCH (quint64, lhs); + QFETCH (quint64, rhs); + QFETCH (bool, expected); + + QCOMPARE (TciProtocol::frequency_difference_exceeds (lhs, rhs, quint64 {1000000u}), expected); + } +}; + +QTEST_MAIN (TestTciProtocol) + +#include "test_tci_protocol.moc" diff --git a/tests/unit/tci/test_tci_receive_ownership.cpp b/tests/unit/tci/test_tci_receive_ownership.cpp new file mode 100644 index 00000000..3f061130 --- /dev/null +++ b/tests/unit/tci/test_tci_receive_ownership.cpp @@ -0,0 +1,451 @@ +#include <QtTest> +#include <QMutexLocker> +#include <QThread> +#include <boost/log/keywords/channel.hpp> + +#include <algorithm> +#include <array> +#include <atomic> +#include <chrono> +#include <condition_variable> +#include <cstring> +#include <functional> +#include <memory> +#include <mutex> +#include <vector> + +#include "DecDataMutex.hpp" +#include "FastDecode.hpp" +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" +#include "Transceiver/TCITransceiver.hpp" +#include "widgets/itoneAndicw.h" +#include "wsjtx_config.h" + +namespace +{ +dec_data_t storage {}; +constexpr int block = 3456; +constexpr int captureCount = block; + +struct ReceiveClock +{ + std::mutex mutex; + std::condition_variable changed; + qint64 timestamp = 104000; // 14 s into a 15 s period; 105000 wraps to zero. + bool armed = false, paused = false, released = false, timedOut = false; + + qint64 now () + { + std::unique_lock<std::mutex> lock {mutex}; + if (armed) + { + armed = false; + paused = true; + changed.notify_all (); + timedOut = !changed.wait_for (lock, std::chrono::seconds {5}, [&] { return released; }); + } + return timestamp; + } + void set (qint64 value) { std::lock_guard<std::mutex> lock {mutex}; timestamp = value; } + void arm () { std::lock_guard<std::mutex> lock {mutex}; armed = true; } + bool waitPaused () + { + std::unique_lock<std::mutex> lock {mutex}; + return changed.wait_for (lock, std::chrono::seconds {5}, [&] { return paused; }); + } + void release () + { + std::lock_guard<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + } +}; + +// The real decoder launcher is linked; only the downstream decoder is a probe. +struct DecodeProbe +{ + std::mutex mutex; + std::condition_variable changed; + bool released = false, timedOut = false; + std::vector<short> samples; + int frames = 0; + double period = 0; + QByteArray myCall, hisCall; + void release () + { + std::lock_guard<std::mutex> lock {mutex}; + released = true; + changed.notify_all (); + } +}; +DecodeProbe * activeProbe = nullptr; + +struct Job +{ + std::array<int, 15> arguments {}; + std::array<char, 8000> messages {}; + char myCall[12], hisCall[12]; + double period = 15; + Job () + { + arguments[1] = captureCount; + arguments[3] = 1; + arguments[9] = 104; + std::memcpy (myCall, "K1ABC ", 12); + std::memcpy (hisCall, "W9XYZ ", 12); + } + QFuture<FastDecodeResult> submit (short const * samples = storage.d2) + { + return startFastDecode (samples, arguments.data (), period, + myCall, hisCall); + } +}; + +class Harness +{ +public: + Harness () : logger_ {boost::log::keywords::channel = "TCI_RECEIVE_TEST"} + { + QObject::connect (&server, &TciSimServer::client_arrived, &server, [this] (int) { + server.send_text (TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';')); + }); + QObject::connect (&server, &TciSimServer::text_received, &server, + [this] (QString const& text, int) { + for (auto const& command : text.split (';', Qt::SkipEmptyParts)) + { + auto const verb = command.section (':', 0, 0); + if (verb == "split_enable") server.send_text ("split_enable:0,false"); + else if (verb == "audio_start" || verb == "audio_stop" + || verb == "modulation" || verb == "rx_enable" + || verb == "trx" || verb == "start" || verb == "stop") + server.send_text (command); + else if (verb == "vfo") + server.send_text (command.count (',') >= 2 ? command : "vfo:0,0,14074000"); + } + }); + context_ = new QObject; + context_->moveToThread (&thread_); + QObject::connect (&thread_, &QThread::finished, context_, &QObject::deleteLater); + thread_.start (); + } + + ~Harness () + { + clock.release (); + auto stopped = std::make_shared<std::atomic_bool> (false); + QMetaObject::invokeMethod (context_, [this, stopped] { + if (rig) { rig->stop (); delete rig; rig = nullptr; } + stopped->store (true); + }, Qt::QueuedConnection); + server.wait_for ([&] { return stopped->load (); }, 10000); + // Complete destruction before logger, clock and transport storage expire. + thread_.quit (); + thread_.wait (); + server.close (); + } + + bool start () + { + if (!server.listen ()) return false; + QString const address = QStringLiteral ("127.0.0.1:%1").arg (server.port ()); + QMetaObject::invokeMethod (context_, [this, address] { + rig = new TCITransceiver (&logger_, {}, "0", address, true, tci__audio, + context_, [this] { return clock.now (); }); + QObject::connect (rig, &Transceiver::failure, rig, [this] (QString const&) { + failed_.store (true); + }); + QObject::connect (rig, &Transceiver::tciframeswritten, rig, [this] (qint64) { + ++notifications_; + }); + QObject::connect (rig, &Transceiver::receiveAudio, &audioContext_, + [this] (ReceiveAudio audio) { + receiver_.accept (audio, storage); + }, Qt::QueuedConnection); + // A ready message is an ordered fence behind preceding binary frames. + QObject::connect (rig, &TCITransceiver::tci_done7, rig, [this] { + std::lock_guard<std::mutex> lock {fenceMutex_}; + ++fences_; + fenceChanged_.notify_all (); + }); + rig->start (1); + state_.online (true); + state_.frequency (14074000); + state_.mode (Transceiver::USB); + state_.period (15); + state_.audio (true); + state_.volume (0); + rig->set (state_, 2); + started_.store (true); + }, Qt::QueuedConnection); + return server.wait_for ([this] { return started_.load (); }, 10000) + && !failed_.load () && server.client_connected (); + } + + bool enableAudio (bool enabled) + { + QMetaObject::invokeMethod (context_, [this, enabled] { + state_.audio (enabled); + rig->set (state_, ++sequence_); + }, Qt::BlockingQueuedConnection); + return !failed_.load (); + } + + bool fence () + { + std::unique_lock<std::mutex> lock {fenceMutex_}; + auto const before = fences_; + server.send_text ("ready"); + server.flush (); + // No GUI event dispatch here: queued audio notifications may stay pending. + return fenceChanged_.wait_for (lock, std::chrono::seconds {5}, + [&] { return fences_ > before; }); + } + + bool packet (std::vector<float> const& pcm, int offset, int count, int receiver = 0) + { + QByteArray bytes; + if (!TciStream::prepare_float_frame (&bytes, 2 * count)) return false; + auto * header = TciStream::header (&bytes); + header->receiver = receiver; + header->sampleRate = 48000; + header->format = TciStream::Float32Format; + header->type = TciStream::RxAudioStream; + header->length = 2 * count; + header->channels = 2; + auto * payload = TciStream::float_payload (&bytes); + for (int i = 0; i < count; ++i) + { + payload[2 * i] = pcm[offset + i]; + payload[2 * i + 1] = -pcm[offset + i]; // Distinct unused right channel. + } + bool const sent = server.send_binary (bytes); + return sent; + } + + bool feed (std::vector<float> const& pcm, std::vector<int> const& chunks = {4096}, + int receiver = 0) + { + int offset = 0, index = 0; + while (offset < int (pcm.size ())) + { + int count = std::min (chunks[index++ % chunks.size ()], int (pcm.size ()) - offset); + if (!packet (pcm, offset, count, receiver)) return false; + offset += count; + } + return fence (); + } + + std::vector<short> snapshot () + { + QCoreApplication::sendPostedEvents (&audioContext_, QEvent::MetaCall); + QMutexLocker lock {&dec_data_mutex ()}; + return {storage.d2, storage.d2 + storage.params.kin}; + } + int notifications () const { return notifications_.load (); } + + TciSimServer server; + ReceiveClock clock; + TCITransceiver * rig = nullptr; +private: + Transceiver::logger_type logger_; + QThread thread_; + QObject * context_ = nullptr; + QObject audioContext_; + ReceiveAudioConsumer receiver_; + Transceiver::TransceiverState state_; + unsigned sequence_ = 2; + std::atomic_bool started_ {false}, failed_ {false}; + std::atomic_int notifications_ {0}; + std::mutex fenceMutex_; + std::condition_variable fenceChanged_; + int fences_ = 0; +}; + +std::vector<float> signal (int outputFrames, float value) +{ + return std::vector<float> (4 * outputFrames, value); +} +} + +dec_data_t& dec_data = storage; +int volatile itone[MAX_NUM_SYMBOLS] {}; +int volatile icw[NUM_CW_SYMBOLS] {}; +float gran () { return 0; } + +extern "C" void fast_decode_ (short samples[], int arguments[], double * period, + char[], char myCall[], char hisCall[], + fortran_charlen_t, fortran_charlen_t, fortran_charlen_t) +{ + auto& probe = *activeProbe; + std::unique_lock<std::mutex> lock {probe.mutex}; + probe.timedOut = !probe.changed.wait_for (lock, std::chrono::seconds {5}, + [&] { return probe.released; }); + if (probe.timedOut) return; + probe.frames = arguments[1]; + if (probe.frames >= 0 && probe.frames <= 360000) + probe.samples.assign (samples, samples + probe.frames); + probe.period = *period; + probe.myCall = QByteArray (myCall, 12); + probe.hisCall = QByteArray (hisCall, 12); +} + +class TestTciReceiveOwnership : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void packetization_preserves_audio () + { + Harness h; + QVERIFY (h.start ()); + auto pcm = signal (captureCount, 0.0f); + for (std::size_t i = 0; i < pcm.size (); ++i) + pcm[i] = (int (i % 31) - 15) / 32.0f; + // fil4 has persistent FIR history. Feed the same silent pre-roll for each + // run; do not reset it through test-only access to Fortran saved state. + QVERIFY (h.feed (signal (block, 0.0f))); + QVERIFY (h.feed (pcm)); + auto first = h.snapshot (); + QVERIFY (h.enableAudio (false)); + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, 0.0f), {4095})); + QVERIFY (h.feed (pcm, {4095})); + auto second = h.snapshot (); + QCOMPARE (first.size (), std::size_t (2 * block)); + QCOMPARE (second.size (), first.size ()); + QVERIFY (std::any_of (first.begin () + block, first.end (), [] (short x) { return x != 0; })); + // Discard pre-roll output: its first taps legitimately contain history + // from the preceding stream. Compare only identically conditioned audio. + QVERIFY (std::equal (first.begin () + block, first.end (), second.begin () + block)); + } + + void ignored_audio_does_not_change_reception () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto before = h.snapshot (); + int const notifications = h.notifications (); + + QVERIFY (h.feed (signal (block, -0.25f), {4096}, 1)); + QVERIFY (before == h.snapshot ()); + QCOMPARE (h.notifications (), notifications); + + QVERIFY (h.enableAudio (false)); + QVERIFY (h.feed (signal (block, -0.25f))); + QVERIFY (before == h.snapshot ()); + QCOMPARE (h.notifications (), notifications); + // An accepted block is a positive control proving the transport and gate + // work, rather than mistaking an idle or disconnected receiver for success. + QVERIFY (h.enableAudio (true)); + QVERIFY (h.feed (signal (block, -0.25f))); + QCOMPARE (h.snapshot ().size (), std::size_t (block)); + } + + void submitted_job_survives_period_reuse () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto const expected = h.snapshot (); + Job job; + DecodeProbe probe; + activeProbe = &probe; + auto future = job.submit (); + h.clock.set (105000); + bool const fed = h.feed (signal (captureCount, -0.25f)); + auto const replacement = h.snapshot (); + probe.release (); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (fed); + QVERIFY (!probe.timedOut); + QCOMPARE (replacement.size (), expected.size ()); + QVERIFY (replacement != expected); + QCOMPARE (probe.samples.size (), expected.size ()); + QCOMPARE (probe.samples.back (), expected.back ()); + QVERIFY (probe.samples == expected); + QCOMPARE (probe.frames, captureCount); + QCOMPARE (probe.period, 15.0); + QCOMPARE (probe.myCall, QByteArray ("K1ABC ", 12)); + QCOMPARE (probe.hisCall, QByteArray ("W9XYZ ", 12)); + } + + void capture_vs_transport_append () + { + Harness h; + QVERIFY (h.start ()); + QVERIFY (h.feed (signal (captureCount, 0.125f))); + auto const expected = h.snapshot (); + // Leave one stereo frame before the next real downsampler output block. + auto next = signal (block, -0.25f); + next.pop_back (); + QVERIFY (h.feed (next)); + h.clock.arm (); + QVERIFY (h.packet (std::vector<float> { -0.25f }, 0, 1)); + h.server.flush (); + bool const paused = h.clock.waitPaused (); + Job job; + DecodeProbe probe; + probe.released = true; + activeProbe = &probe; + h.clock.release (); + // Both real sample accesses follow release, with no completion ordering. + auto future = job.submit (); + bool const finished = h.fence (); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (paused); + QVERIFY (finished); + QVERIFY (!h.clock.timedOut); + QVERIFY (!probe.timedOut); + QCOMPARE (h.snapshot ().size (), std::size_t (captureCount + block)); + QVERIFY (probe.samples == expected); + } + + void delayed_notification_retains_period_identity () + { + Harness h; + QVERIFY (h.start ()); + Job job; + DecodeProbe probe; + probe.released = true; + activeProbe = &probe; + QObject consumer; + bool handled = false; + int rejected = 0; + auto received = std::make_unique<dec_data_t> (); + ReceiveAudioConsumer receiver; + QFuture<FastDecodeResult> future; + QObject::connect (h.rig, &Transceiver::receiveAudio, &consumer, [&] (ReceiveAudio audio) { + if (!receiver.accept (audio, *received)) { ++rejected; return; } + if (handled || audio->end () != captureCount) return; + handled = true; + future = job.submit (received->d2); + }, Qt::QueuedConnection); + // Transport fences do not dispatch the main thread's queued callbacks. + bool const fedA = h.feed (signal (captureCount, 0.125f)); + auto const expected = h.snapshot (); + h.clock.set (105000); + bool const fedB = h.feed (signal (captureCount, -0.25f)); + auto const replacement = h.snapshot (); + QCoreApplication::sendPostedEvents (&consumer, QEvent::MetaCall); + future.waitForFinished (); + activeProbe = nullptr; + QVERIFY (fedA); + QVERIFY (fedB); + QVERIFY (handled); + QVERIFY (rejected > 0); + QVERIFY (!probe.timedOut); + QCOMPARE (expected.size (), std::size_t (captureCount)); + QCOMPARE (replacement.size (), expected.size ()); + QVERIFY (replacement != expected); + QCOMPARE (probe.samples.size (), expected.size ()); + QCOMPARE (probe.samples.back (), replacement.back ()); + QVERIFY (probe.samples == replacement); + // Stale A is rejected; B still reaches the production decode boundary. + } +}; + +QTEST_GUILESS_MAIN (TestTciReceiveOwnership) +#include "test_tci_receive_ownership.moc" diff --git a/tests/unit/tci/test_tci_sim_smoke.cpp b/tests/unit/tci/test_tci_sim_smoke.cpp new file mode 100644 index 00000000..582bb66a --- /dev/null +++ b/tests/unit/tci/test_tci_sim_smoke.cpp @@ -0,0 +1,387 @@ +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" + +#include <memory> + +#include <QElapsedTimer> +#include <QTimer> +#include <QtTest> +#include <QtWebSockets/QWebSocket> + +namespace +{ + struct ReconnectState + { + bool client_disconnected {false}; + bool server_disconnected {false}; + bool reopened {false}; + }; + + void reconnect_once_after_retirement ( + QWebSocket& client, TciSimServer& server) + { + auto state = std::make_shared<ReconnectState> (); + auto reopen = [state, &client, &server] + { + if (state->reopened || !state->client_disconnected + || !state->server_disconnected) + { + return; + } + state->reopened = true; + QTimer::singleShot (0, &client, + [&client, &server] + { + client.open (QUrl {server.url ()}); + }); + }; + + QObject::connect (&client, &QWebSocket::disconnected, &client, + [state, reopen] + { + state->client_disconnected = true; + reopen (); + }); + QObject::connect (&server, &TciSimServer::client_gone, &client, + [state, reopen] (int) + { + state->server_disconnected = true; + reopen (); + }); + } +} + +class TestTciSim final + : public QObject +{ + Q_OBJECT + +private slots: + void recordsOrderedFullDuplexTranscript () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + + client.sendTextMessage (QStringLiteral ( + "vfo:0,0,14074000;vfo:0,1,14075000;split_enable:0,true;")); + QVERIFY (server.wait_for ([&server] + { + return server.count ( + TciSimServer::Direction::ClientToServer) == 3; + }, 1000)); + server.send_text (QStringLiteral ("vfo:0,0,14074000;trx:0,false")); + + auto const& frames = server.frames (); + QCOMPARE (frames.size (), 2); + QCOMPARE (frames.at (0).raw, QStringLiteral ( + "vfo:0,0,14074000;vfo:0,1,14075000;split_enable:0,true;")); + QCOMPARE (frames.at (1).raw, + QStringLiteral ("vfo:0,0,14074000;trx:0,false;")); + QCOMPARE (frames.at (0).ordinal, quint64 {0}); + QCOMPARE (frames.at (1).ordinal, quint64 {1}); + + auto const& transcript = server.transcript (); + QCOMPARE (transcript.size (), 5); + QCOMPARE (transcript.at (0).direction, + TciSimServer::Direction::ClientToServer); + QCOMPARE (transcript.at (0).connection_generation, 1); + QCOMPARE (transcript.at (0).ordinal, quint64 {0}); + QCOMPARE (transcript.at (0).raw, QStringLiteral ("vfo:0,0,14074000")); + QCOMPARE (transcript.at (0).verb, QStringLiteral ("vfo")); + QCOMPARE (transcript.at (0).args, + QStringList ({"0", "0", "14074000"})); + QCOMPARE (transcript.at (1).verb, QStringLiteral ("vfo")); + QCOMPARE (transcript.at (2).verb, QStringLiteral ("split_enable")); + QCOMPARE (transcript.at (3).direction, + TciSimServer::Direction::ServerToClient); + QCOMPARE (transcript.at (4).verb, QStringLiteral ("trx")); + QVERIFY (server.occurs_before (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), + TciSimServer::Direction::ClientToServer, + QStringLiteral ("split_enable"))); + } + + void cursorConsumesRepeatedCommands () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + client.sendTextMessage (QStringLiteral ( + "vfo:0,0,7074000;vfo:0,0,14074000;vfo:0,0,21074000;")); + QVERIFY (server.wait_for ([&server] + { + return server.count ( + TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")) == 3; + }, 1000)); + + auto cursor = server.cursor (); + TciSimServer::Message message; + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message)); + QCOMPARE (message.args.at (2), QStringLiteral ("7074000")); + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message)); + QCOMPARE (message.args.at (2), QStringLiteral ("14074000")); + QVERIFY (server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), &message, + [] (QStringList const& args) + { + return args.value (2) == QStringLiteral ("21074000"); + })); + QCOMPARE (message.ordinal, quint64 {2}); + QVERIFY (!server.consume (&cursor, TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"))); + QCOMPARE (server.count (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")), 3); + QCOMPARE (server.index_of (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo"), 2), 2); + } + + void scriptGreetsDelaysAndWithholds () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + QStringList received; + bool command_sent {false}; + QElapsedTimer delayed_reply; + connect (&client, &QWebSocket::textMessageReceived, this, + [&client, &received, &command_sent, + &delayed_reply] (QString const& text) + { + received.append (text); + if (text != QStringLiteral ("ready;") || command_sent) return; + command_sent = true; + delayed_reply.start (); + client.sendTextMessage (QStringLiteral ("vfo:0,0,14074000;")); + }); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Thetis) + .withhold (QStringLiteral ("vfo"), + [] (QStringList const& args) + { + return args.value (2) == QStringLiteral ("14074000"); + }) + .delay (30) + .push (QStringLiteral ("vfo:0,0,14074000")); + client.open (QUrl {server.url ()}); + QVERIFY2 (script.run (2000), qPrintable (script.last_error ())); + QVERIFY (received.contains (QStringLiteral ("ready;"))); + QVERIFY (command_sent); + QVERIFY (delayed_reply.elapsed () >= 20); + QCOMPARE (server.count (TciSimServer::Direction::ClientToServer, + QStringLiteral ("vfo")), 1); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("vfo")), 3); + } + + void scriptClosesAndAcceptsReconnect () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .close_normally () + .reconnect () + .greet (TciSimGreeting::Minimal); + client.open (QUrl {server.url ()}); + QVERIFY2 (script.run (3000), qPrintable (script.last_error ())); + QCOMPARE (server.connection_count (), 2); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ready")), 2); + auto const ready = server.messages (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ready")); + QCOMPARE (ready.at (0).connection_generation, 1); + QCOMPARE (ready.at (1).connection_generation, 2); + } + + void reconnectExpectationsIgnoreOldConnectionCommands () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + int client_connection_count {0}; + connect (&client, &QWebSocket::connected, this, + [&client, &client_connection_count] + { + ++client_connection_count; + if (client_connection_count == 2) + { + QTimer::singleShot (30, &client, + [&client] + { + client.sendTextMessage ( + QStringLiteral ("future:2;")); + }); + } + }); + + TciSimScript script {&server}; + script.expect (QStringLiteral ("trigger")) + .close_normally () + .reconnect () + .expect (QStringLiteral ("future"), + [] (QStringList const& args) {return args == QStringList {"2"};}); + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + QTimer::singleShot (0, &client, + [&client] + { + client.sendTextMessage ( + QStringLiteral ("trigger;future:1;")); + }); + QVERIFY2 (script.run (3000), qPrintable (script.last_error ())); + auto const future = server.messages (TciSimServer::Direction::ClientToServer, + QStringLiteral ("future")); + QCOMPARE (future.size (), 2); + QCOMPARE (future.at (0).connection_generation, 1); + QCOMPARE (future.at (1).connection_generation, 2); + } + + void delayedPushDoesNotCrossConnectionGeneration () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + reconnect_once_after_retirement (client, server); + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&client, &server] + { + return server.client_connected () + && client.state () == QAbstractSocket::ConnectedState; + }, 1000)); + + TciSimScript script {&server}; + script.push (QStringLiteral ("old-generation"), 50); + QTimer::singleShot (10, &server, [&server] {server.close_client ();}); + QVERIFY2 (script.run (1000), qPrintable (script.last_error ())); + QVERIFY (server.wait_for ([&server] {return server.connection_count () == 2;}, 1000)); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("old-generation")), 0); + } + + void replyUsesTheConsumedExpectationGeneration () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + QStringList received; + connect (&client, &QWebSocket::textMessageReceived, this, + [&client, &received] (QString const& text) + { + received.append (text); + if (text == QStringLiteral ("ready;")) + { + client.sendTextMessage (QStringLiteral ("request:1;")); + } + }); + + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .expect (QStringLiteral ("request")) + .reply (QStringLiteral ("ack:1")); + client.open (QUrl {server.url ()}); + + QVERIFY2 (script.run (2000), qPrintable (script.last_error ())); + QVERIFY (server.wait_for ([&received] + { + return received.contains (QStringLiteral ("ack:1;")); + }, 1000)); + auto const replies = server.messages ( + TciSimServer::Direction::ServerToClient, QStringLiteral ("ack")); + QCOMPARE (replies.size (), 1); + QCOMPARE (replies.first ().connection_generation, 1); + } + + void replyWithoutAnExpectationFails () + { + TciSimServer server; + QVERIFY (server.listen ()); + + QWebSocket client; + TciSimScript script {&server}; + script.greet (TciSimGreeting::Minimal) + .reply (QStringLiteral ("ack:1")); + client.open (QUrl {server.url ()}); + + QVERIFY (!script.run (1000)); + QVERIFY (script.last_error ().contains ( + QStringLiteral ("reply requires an expectation"))); + QCOMPARE (server.count (TciSimServer::Direction::ServerToClient, + QStringLiteral ("ack")), 0); + } + + void closeWithoutAClientFails () + { + TciSimServer server; + QVERIFY (server.listen ()); + + TciSimScript script {&server}; + script.close_normally (); + + QVERIFY (!script.run (100)); + QVERIFY (script.last_error ().contains ( + QStringLiteral ("cannot close without a connected client"))); + QCOMPARE (server.connection_count (), 0); + } + + void failureIncludesTranscript () + { + TciSimServer server; + QVERIFY (server.listen ()); + QWebSocket client; + client.open (QUrl {server.url ()}); + QVERIFY (server.wait_for ([&server] { return server.client_connected (); }, 1000)); + client.sendTextMessage (QStringLiteral ("vfo:0,0,7074000;")); + + TciSimScript script {&server}; + script.expect (QStringLiteral ("trx"), {}, 20); + QVERIFY (!script.run (500)); + QCOMPARE (script.failed_step (), 1); + QVERIFY (script.last_error ().contains (QStringLiteral ("expecting trx"))); + QVERIFY (script.last_error ().contains (QStringLiteral ("vfo:0,0,7074000"))); + } + + void waitForShortCircuits () + { + TciSimServer server; + QElapsedTimer elapsed; + elapsed.start (); + QVERIFY (server.wait_for ([] { return true; }, 1000)); + QVERIFY (elapsed.elapsed () < 100); + } +}; + +QTEST_MAIN (TestTciSim) + +#include "test_tci_sim_smoke.moc" diff --git a/tests/unit/tci/test_tci_stream.cpp b/tests/unit/tci/test_tci_stream.cpp new file mode 100644 index 00000000..a9c8cfb4 --- /dev/null +++ b/tests/unit/tci/test_tci_stream.cpp @@ -0,0 +1,204 @@ +#include <cstddef> + +#include <QtTest> + +#include "Transceiver/TCIStream.hpp" + +class TestTciStream final + : public QObject +{ + Q_OBJECT + +private slots: + void preservesWireHeaderLayout () + { + QCOMPARE (sizeof (TciStream::Header), size_t {64}); + QCOMPARE (offsetof (TciStream::Header, length), size_t {20}); + QCOMPARE (offsetof (TciStream::Header, type), size_t {24}); + QCOMPARE (offsetof (TciStream::Header, channels), size_t {28}); + } + + void preparesExactZeroedFloatFrame () + { + QByteArray frame (128, '\x7f'); + + QVERIFY (TciStream::prepare_float_frame (&frame, 2048u)); + QCOMPARE (frame.size (), 64 + 2048 * int (sizeof (float))); + for (auto byte : frame) + { + QCOMPARE (byte, char {0}); + } + QVERIFY (TciStream::has_complete_float_payload (frame, 2048u)); + QVERIFY (!TciStream::has_complete_float_payload (frame.left (frame.size () - 1), 2048u)); + } + + void rejectsOversizedFloatFrame () + { + QByteArray frame; + QVERIFY (!TciStream::prepare_float_frame (&frame, TciStream::MaxFloatSamples + 1u)); + QVERIFY (!TciStream::checked_float_frame_size (1u, nullptr)); + } + + void recognizesChannelHeaderVersions_data () + { + QTest::addColumn<QString> ("version"); + QTest::addColumn<bool> ("expected"); + + QTest::newRow ("pre-channel header") << QString {"1.8"} << false; + QTest::newRow ("first channel header") << QString {"1.9"} << true; + QTest::newRow ("patch version") << QString {"1.9.1"} << true; + QTest::newRow ("current protocol") << QString {"2.0"} << true; + QTest::newRow ("invalid") << QString {"ExpertSDR3"} << false; + QTest::newRow ("missing") << QString {} << false; + } + + void recognizesChannelHeaderVersions () + { + QFETCH (QString, version); + QFETCH (bool, expected); + + QCOMPARE (TciStream::protocol_has_channels (version), expected); + } + + void validatesChronoParameters_data () + { + QTest::addColumn<bool> ("modern"); + QTest::addColumn<quint32> ("header_channels"); + QTest::addColumn<quint32> ("length"); + QTest::addColumn<quint32> ("format"); + QTest::addColumn<quint32> ("codec"); + QTest::addColumn<quint32> ("sample_rate"); + QTest::addColumn<bool> ("expected_valid"); + QTest::addColumn<quint32> ("expected_channels"); + + QTest::newRow ("legacy ignores reserved") + << false << quint32 {0xdeadbeefu} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {2}; + QTest::newRow ("modern mono") + << true << quint32 {1} << quint32 {3} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {1}; + QTest::newRow ("modern stereo") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {2}; + QTest::newRow ("zero-length mono") + << true << quint32 {1} << quint32 {0} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << true << quint32 {1}; + QTest::newRow ("odd stereo") + << true << quint32 {2} << quint32 {3} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("invalid modern channels") + << true << quint32 {0} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported format") + << true << quint32 {2} << quint32 {2048} + << quint32 {0} << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported codec") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << quint32 {1} << quint32 {48000} + << false << quint32 {0}; + QTest::newRow ("unsupported sample rate") + << true << quint32 {2} << quint32 {2048} + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {24000} + << false << quint32 {0}; + QTest::newRow ("oversized") + << true << quint32 {1} << TciStream::MaxFloatSamples + 1u + << TciStream::Float32Format << TciStream::UncompressedCodec << quint32 {48000} + << false << quint32 {0}; + } + + void validatesChronoParameters () + { + QFETCH (bool, modern); + QFETCH (quint32, header_channels); + QFETCH (quint32, length); + QFETCH (quint32, format); + QFETCH (quint32, codec); + QFETCH (quint32, sample_rate); + QFETCH (bool, expected_valid); + QFETCH (quint32, expected_channels); + + TciStream::Header chrono {}; + chrono.sampleRate = sample_rate; + chrono.format = format; + chrono.codec = codec; + chrono.length = length; + chrono.channels = header_channels; + quint32 channels {99u}; + + QCOMPARE (TciStream::valid_tx_chrono (chrono, modern, 48000u, &channels), expected_valid); + if (expected_valid) + { + QCOMPARE (channels, expected_channels); + } + } + + void buildsConformingStereoResponse () + { + TciStream::Header chrono {}; + chrono.receiver = 1u; + chrono.sampleRate = 48000u; + chrono.length = 2048u; + QByteArray response; + + QVERIFY (TciStream::prepare_tx_audio_frame (&response, chrono, 2u)); + QCOMPARE (response.size (), 8256); + auto const * header = TciStream::header (response); + QCOMPARE (header->receiver, quint32 {1}); + QCOMPARE (header->sampleRate, quint32 {48000}); + QCOMPARE (header->format, TciStream::Float32Format); + QCOMPARE (header->codec, TciStream::UncompressedCodec); + QCOMPARE (header->length, quint32 {2048}); + QCOMPARE (header->type, quint32 {TciStream::TxAudioStream}); + QCOMPARE (header->channels, quint32 {2}); + for (auto reserved : header->reserved) + { + QCOMPARE (reserved, quint32 {0}); + } + for (quint32 i = 0u; i < header->length; ++i) + { + QCOMPARE (TciStream::float_payload (response)[i], 0.0f); + } + } + + void rejectsInvalidResponseChannelShape () + { + TciStream::Header chrono {}; + chrono.length = 3u; + QByteArray response; + + QVERIFY (!TciStream::prepare_tx_audio_frame (&response, chrono, 0u)); + QVERIFY (!TciStream::prepare_tx_audio_frame (&response, chrono, 2u)); + QVERIFY (TciStream::prepare_tx_audio_frame (&response, chrono, 1u)); + QCOMPARE (response.size (), 64 + 3 * int (sizeof (float))); + } + + void packsMonoAndStereoChannelFrames () + { + float mono[2] {}; + auto * mono_end = TciStream::write_channel_frame (0.25f, 1u, mono); + mono_end = TciStream::write_channel_frame (-0.5f, 1u, mono_end); + QCOMPARE (mono_end, mono + 2); + QCOMPARE (mono[0], 0.25f); + QCOMPARE (mono[1], -0.5f); + + float stereo[4] {}; + auto * stereo_end = TciStream::write_channel_frame (0.25f, 2u, stereo); + stereo_end = TciStream::write_channel_frame (-0.5f, 2u, stereo_end); + QCOMPARE (stereo_end, stereo + 4); + QCOMPARE (stereo[0], 0.25f); + QCOMPARE (stereo[1], 0.25f); + QCOMPARE (stereo[2], -0.5f); + QCOMPARE (stereo[3], -0.5f); + } +}; + +QTEST_MAIN (TestTciStream) + +#include "test_tci_stream.moc" diff --git a/tests/unit/tci/test_tci_transceiver_characterization.cpp b/tests/unit/tci/test_tci_transceiver_characterization.cpp new file mode 100644 index 00000000..17c3a395 --- /dev/null +++ b/tests/unit/tci/test_tci_transceiver_characterization.cpp @@ -0,0 +1,912 @@ +#include <functional> +#include <memory> + +#include <boost/log/keywords/channel.hpp> + +#include <QCoreApplication> +#include <QElapsedTimer> +#include <QTest> +#include <QTimer> +#include <QVector> + +#include "commons.h" +#include "TciSimScript.hpp" +#include "TciSimServer.hpp" +#include "Transceiver/TCITransceiver.hpp" +#include "widgets/itoneAndicw.h" + +namespace +{ + dec_data_t test_dec_data {}; + + using Direction = TciSimServer::Direction; + using Message = TciSimServer::Message; + using State = Transceiver::TransceiverState; + using Frequency = Transceiver::Frequency; + using CommandHandler = std::function<bool (QString const&, QStringList const&, int)>; + + Frequency constexpr initial_frequency {14074000}; + + using RigFactory = std::function<std::unique_ptr<Transceiver> ( + Transceiver::logger_type *, QString const&)>; + + RigFactory legacy_rig_factory () + { + return [] (Transceiver::logger_type * logger, QString const& address) + { + return std::unique_ptr<Transceiver> { + new TCITransceiver {logger, {}, QStringLiteral ("0"), address, + true, 0}}; + }; + } + + int message_index ( + TciSimServer const& server, int start, Direction direction, + QString const& verb, + std::function<bool (Message const&)> const& predicate = {}) + { + auto const& transcript = server.transcript (); + for (int i = qMax (0, start); i < transcript.size (); ++i) + { + auto const& message = transcript.at (i); + if (message.direction == direction && message.verb == verb + && (!predicate || predicate (message))) + { + return i; + } + } + return -1; + } + + bool has_args (Message const& message, QStringList const& args) + { + return message.args == args; + } + + class RigHarness + { + public: + using StatePredicate = std::function<bool (State const&)>; + + explicit RigHarness (RigFactory factory = legacy_rig_factory ()) + : logger_ {boost::log::keywords::channel = "TCI_CHARACTERIZATION"} + , factory_ {std::move (factory)} + { + QObject::connect (&server_, &TciSimServer::client_arrived, &server_, + [this] (int) + { + server_.send_text (startup_greeting ()); + }); + QObject::connect (&server_, &TciSimServer::text_received, &server_, + [this] (QString const& text, int generation) + { + handle_client_text (text, generation); + }); + } + + ~RigHarness () + { + tearing_down_ = true; + command_handler_ = {}; + destroy_rig (); + server_.close (); + } + + bool listen () + { + if (!server_.listen ()) return false; + create_rig (); + return true; + } + + bool start (unsigned sequence_number = 1) + { + auto const update_cursor = observations_.size (); + auto const previous_generation = server_.connection_generation (); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, sequence_number] + { + rig->start (sequence_number); + }); + auto const completed = server_.wait_for ( + [this, update_cursor, previous_generation, sequence_number] + { + return server_.client_connected () + && server_.connection_generation () > previous_generation + && observed_state_since ( + update_cursor, sequence_number, + [] (State const& state) {return state.online ();}); + }, 7000); + return completed && server_.client_connected () + && server_.connection_generation () > previous_generation + && observed_state_since ( + update_cursor, sequence_number, + [] (State const& state) {return state.online ();}); + } + + bool restart (unsigned sequence_number) + { + return start (sequence_number); + } + + bool stop () + { + auto const completed = std::make_shared<bool> (false); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, completed] + { + rig->stop (); + *completed = true; + }); + return server_.wait_for ( + [this, completed] + { + return *completed && server_.client_disconnected (); + }, 7000); + } + + int set (State state, unsigned sequence_number) + { + auto const update_cursor = observations_.size (); + auto * rig = rig_.get (); + QTimer::singleShot (0, rig, + [rig, state, sequence_number] + { + rig->set (state, sequence_number); + }); + return update_cursor; + } + + void set_now (State const& state, unsigned sequence_number) + { + rig_->set (state, sequence_number); + } + + void schedule_set (State state, unsigned sequence_number) + { + QTimer::singleShot (0, &server_, + [this, state, sequence_number] + { + if (!tearing_down_ && rig_) + { + rig_->set (state, sequence_number); + } + }); + } + + void set_command_handler (CommandHandler handler) + { + command_handler_ = std::move (handler); + } + + TciSimServer& server () {return server_;} + Transceiver& rig () {return *rig_;} + State const& state () const {return state_;} + int observation_count () const {return observations_.size ();} + int failure_count () const {return failures_.size ();} + + bool observed_state_since ( + int cursor, StatePredicate const& predicate) const + { + for (int i = qMax (0, cursor); i < observations_.size (); ++i) + { + if (predicate (observations_.at (i).state)) return true; + } + return false; + } + + bool observed_state_since ( + int cursor, unsigned sequence_number, + StatePredicate const& predicate) const + { + for (int i = qMax (0, cursor); i < observations_.size (); ++i) + { + auto const& observation = observations_.at (i); + if (observation.sequence_number == sequence_number + && predicate (observation.state)) + { + return true; + } + } + return false; + } + + bool wait_for_state ( + int cursor, unsigned sequence_number, + StatePredicate predicate, int timeout_ms = 6000) + { + auto const failure_cursor = failures_.size (); + auto const completed = server_.wait_for ( + [this, cursor, sequence_number, &predicate, failure_cursor] + { + return failures_.size () > failure_cursor + || observed_state_since (cursor, sequence_number, predicate); + }, timeout_ms); + return completed && failures_.size () == failure_cursor + && observed_state_since (cursor, sequence_number, predicate); + } + + bool wait_for_current_state (StatePredicate predicate, int timeout_ms = 1000) + { + return server_.wait_for ([this, &predicate] {return predicate (state_);}, + timeout_ms); + } + + bool wait_for_failure (int cursor, int timeout_ms = 6000) + { + return server_.wait_for ([this, cursor] {return failures_.size () > cursor;}, + timeout_ms); + } + + QString diagnostics () const + { + auto const sequence = observations_.isEmpty () + ? 0u : observations_.last ().sequence_number; + auto const failure = failures_.isEmpty () + ? QStringLiteral ("none") : failures_.last (); + return QStringLiteral ( + "connected=%1 generation=%2 updates=%3 sequence=%4 online=%5 " + "rx=%6 tx=%7 split=%8 ptt=%9 failure=%10\n%11") + .arg (server_.client_connected ()) + .arg (server_.connection_generation ()) + .arg (observations_.size ()) + .arg (sequence) + .arg (state_.online ()) + .arg (state_.frequency ()) + .arg (state_.tx_frequency ()) + .arg (state_.split ()) + .arg (state_.ptt ()) + .arg (failure, server_.transcript_text ()); + } + + private: + struct StateObservation + { + State state; + unsigned sequence_number; + }; + + static QString startup_greeting () + { + return TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';') + + ';'; + } + + void create_rig () + { + auto const address = QStringLiteral ("127.0.0.1:%1").arg (server_.port ()); + rig_ = factory_ (&logger_, address); + QObject::connect ( + rig_.get (), &Transceiver::update, &server_, + [this] (State const& state, unsigned sequence_number) + { + state_ = state; + observations_.append ({state, sequence_number}); + }); + QObject::connect ( + rig_.get (), &Transceiver::failure, &server_, + [this] (QString const& reason) {failures_.append (reason);}); + } + + void destroy_rig () + { + if (!rig_) return; + + bool client_gone = !server_.client_connected (); + auto const connection = QObject::connect ( + &server_, &TciSimServer::client_gone, &server_, + [&client_gone] (int) {client_gone = true;}); + rig_->stop (); + if (!client_gone) + { + server_.wait_for ([&client_gone] {return client_gone;}, 1000); + } + QObject::disconnect (connection); + rig_.reset (); + QCoreApplication::processEvents (QEventLoop::AllEvents, 20); + } + + void handle_client_text (QString const& text, int generation) + { + auto const commands = text.split (';', Qt::SkipEmptyParts); + for (auto const& command : commands) + { + auto const separator = command.indexOf (':'); + auto const verb = separator < 0 + ? command.trimmed () : command.left (separator).trimmed (); + auto const args = separator < 0 + ? QStringList {} : command.mid (separator + 1).split (',', Qt::KeepEmptyParts); + if (command_handler_ && command_handler_ (verb, args, generation)) continue; + acknowledge (verb, args); + } + } + + void acknowledge (QString const& verb, QStringList const& args) + { + if (verb == QStringLiteral ("vfo") && args.size () >= 3) + { + server_.send_text (QStringLiteral ("vfo:%1,%2,%3") + .arg (args.at (0), args.at (1), args.at (2))); + } + else if (verb == QStringLiteral ("modulation") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("modulation:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("split_enable")) + { + auto const enabled = args.size () >= 2 ? args.at (1) : args.value (0); + server_.send_text (QStringLiteral ("split_enable:0,%1").arg (enabled)); + } + else if (verb == QStringLiteral ("trx") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("trx:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("rx_enable") && args.size () >= 2) + { + server_.send_text (QStringLiteral ("rx_enable:%1,%2") + .arg (args.at (0), args.at (1))); + } + else if (verb == QStringLiteral ("start") || verb == QStringLiteral ("stop")) + { + server_.send_text (verb); + } + } + + TciSimServer server_; + Transceiver::logger_type logger_; + RigFactory factory_; + std::unique_ptr<Transceiver> rig_; + CommandHandler command_handler_; + QVector<StateObservation> observations_; + QStringList failures_; + State state_; + bool tearing_down_ {false}; + }; + + State state_from (RigHarness const& harness) + { + auto state = harness.state (); + state.online (true); + return state; + } +} + +// The TCI object references application-owned DSP globals through wsjt_qt. +dec_data_t& dec_data = test_dec_data; +int volatile itone[MAX_NUM_SYMBOLS] {}; +int volatile icw[NUM_CW_SYMBOLS] {}; + +float gran () +{ + return 0.0f; +} + +class TestTciTransceiverCharacterization final + : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase () + { + Logger::disable (); + qRegisterMetaType<Transceiver::TransceiverState> (); + } + + void startup_adopts_greeting_and_preserves_framing () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + QCOMPARE (server.connection_count (), 1); + QCOMPARE (harness.state ().frequency (), initial_frequency); + QCOMPARE (harness.state ().tx_frequency (), Frequency {0}); + QCOMPARE (harness.state ().mode (), Transceiver::DIG_U); + QVERIFY (!harness.state ().split ()); + + auto const& frames = server.frames (); + QVERIFY (!frames.isEmpty ()); + QCOMPARE (frames.first ().raw, + TciSimScript::greeting_messages (TciSimGreeting::Thetis).join (';') + + ';'); + + auto const device = message_index (server, 0, Direction::ServerToClient, + QStringLiteral ("device")); + auto const rx_vfo = message_index (server, device + 1, Direction::ServerToClient, + QStringLiteral ("vfo")); + auto const mode = message_index (server, rx_vfo + 1, Direction::ServerToClient, + QStringLiteral ("modulation")); + auto const ready = message_index (server, mode + 1, Direction::ServerToClient, + QStringLiteral ("ready")); + QVERIFY2 (device >= 0 && rx_vfo > device && mode > rx_vfo + && ready > mode, + qPrintable (harness.diagnostics ())); + } + + void rx_vfo_acknowledgement_precedes_dependent_mode () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + Frequency constexpr target {14074100}; + auto const operation_start = harness.server ().transcript ().size (); + harness.set_command_handler ( + [&harness] (QString const& verb, QStringList const& args, int) + { + if (verb == QStringLiteral ("vfo") && args == QStringList {"0", "0", "14074100"}) + { + harness.server ().send_text_later ( + QStringLiteral ("unexpected:payload;vfo:1,0,14074100"), 5); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074100"), 30); + return true; + } + return false; + }); + + auto requested = state_from (harness); + requested.frequency (target); + requested.mode (Transceiver::USB); + auto const update_cursor = harness.set (requested, 10); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 10, + [] (State const& state) + { + return state.frequency () == target && state.mode () == Transceiver::USB; + }), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const vfo_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "0", "14074100"});}); + auto const vfo_ack = message_index ( + server, vfo_command + 1, Direction::ServerToClient, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "0", "14074100"});}); + auto const mode_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("modulation"), + [] (Message const& message) {return has_args (message, {"0", "usb"});}); + QVERIFY2 (vfo_command >= 0 && vfo_ack > vfo_command && mode_command > vfo_ack, + qPrintable (harness.diagnostics ())); + QCOMPARE (harness.state ().frequency (), target); + QCOMPARE (harness.state ().mode (), Transceiver::USB); + + auto const vfo_count = server.count (Direction::ClientToServer, + QStringLiteral ("vfo")); + auto const mode_count = server.count (Direction::ClientToServer, + QStringLiteral ("modulation")); + QTest::qWait (75); + QCOMPARE (server.count (Direction::ClientToServer, QStringLiteral ("vfo")), + vfo_count); + QCOMPARE (server.count (Direction::ClientToServer, + QStringLiteral ("modulation")), mode_count); + } + + void unacknowledged_rx_vfo_fails_boundedly_without_dependent_commands () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {7074125}; + auto const operation_start = harness.server ().transcript ().size (); + harness.set_command_handler ( + [] (QString const& verb, QStringList const& args, int) + { + return verb == QStringLiteral ("vfo") + && args == QStringList {"0", "0", "7074125"}; + }); + auto requested = state_from (harness); + requested.frequency (target); + requested.mode (Transceiver::USB); + + QElapsedTimer deadline; + deadline.start (); + harness.set (requested, 20); + QVERIFY2 (harness.wait_for_failure (failure_cursor), + qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const attempts = server.messages (Direction::ClientToServer, + QStringLiteral ("vfo")); + int matching_attempts {0}; + for (auto const& attempt : attempts) + { + if (attempt.ordinal < static_cast<quint64> (operation_start)) continue; + QVERIFY2 (has_args (attempt, {"0", "0", "7074125"}), + qPrintable (harness.diagnostics ())); + ++matching_attempts; + } + QVERIFY2 (matching_attempts >= 1, qPrintable (harness.diagnostics ())); + QCOMPARE (message_index (server, operation_start, Direction::ClientToServer, + QStringLiteral ("modulation")), -1); + QVERIFY (deadline.elapsed () < 6000); + QVERIFY (harness.failure_count () - failure_cursor <= 1); + QVERIFY (harness.wait_for_current_state ( + [] (State const& state) {return !state.online ();})); + + auto const attempts_after_failure = matching_attempts; + QTest::qWait (50); + int attempts_after_wait {0}; + for (auto const& attempt : server.messages (Direction::ClientToServer, + QStringLiteral ("vfo"))) + { + if (attempt.ordinal >= static_cast<quint64> (operation_start) + && has_args (attempt, {"0", "0", "7074125"})) + { + ++attempts_after_wait; + } + } + QCOMPARE (attempts_after_wait, attempts_after_failure); + } + + void split_and_tx_vfo_settle_before_ptt () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + Frequency constexpr tx_frequency {14076000}; + auto const operation_start = harness.server ().transcript ().size (); + struct AcknowledgementState + { + bool split_scheduled {false}; + bool split_sent {false}; + bool tx_vfo_scheduled {false}; + bool tx_vfo_sent {false}; + bool ptt_before_prerequisites {false}; + }; + auto const acknowledgements = std::make_shared<AcknowledgementState> (); + harness.set_command_handler ( + [&harness, acknowledgements] (QString const& verb, + QStringList const& args, int) + { + if (verb == QStringLiteral ("split_enable") + && args == QStringList {"0", "true"}) + { + if (!acknowledgements->split_scheduled + && !acknowledgements->split_sent) + { + acknowledgements->split_scheduled = true; + QTimer::singleShot ( + 25, &harness.server (), + [&harness, acknowledgements] + { + acknowledgements->split_sent = true; + harness.server ().send_text ( + QStringLiteral ("split_enable:0,true")); + }); + } + return !acknowledgements->split_sent; + } + if (verb == QStringLiteral ("vfo") + && args == QStringList {"0", "1", "14076000"}) + { + if (!acknowledgements->tx_vfo_scheduled + && !acknowledgements->tx_vfo_sent) + { + acknowledgements->tx_vfo_scheduled = true; + QTimer::singleShot ( + 25, &harness.server (), + [&harness, acknowledgements] + { + acknowledgements->tx_vfo_sent = true; + harness.server ().send_text ( + QStringLiteral ("vfo:0,1,14076000")); + }); + } + return !acknowledgements->tx_vfo_sent; + } + if (verb == QStringLiteral ("trx") + && args == QStringList {"0", "true"}) + { + acknowledgements->ptt_before_prerequisites = + acknowledgements->ptt_before_prerequisites + || !acknowledgements->split_sent + || !acknowledgements->tx_vfo_sent; + } + return false; + }); + auto requested = state_from (harness); + requested.tx_frequency (tx_frequency); + requested.split (true); + requested.ptt (true); + auto const update_cursor = harness.set (requested, 30); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 30, + [] (State const& state) + { + return state.split () && state.tx_frequency () == tx_frequency + && state.ptt (); + }), qPrintable (harness.diagnostics ())); + + auto const& server = harness.server (); + auto const split_command = message_index ( + server, operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + auto const split_ack = message_index ( + server, operation_start, Direction::ServerToClient, QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + auto const tx_vfo_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("vfo"), + [] (Message const& message) + { + return has_args (message, {"0", "1", "14076000"}); + }); + auto const tx_vfo_ack = message_index ( + server, operation_start, Direction::ServerToClient, QStringLiteral ("vfo"), + [] (Message const& message) {return has_args (message, {"0", "1", "14076000"});}); + auto const ptt_command = message_index ( + server, operation_start, Direction::ClientToServer, QStringLiteral ("trx"), + [] (Message const& message) {return message.args.size () >= 2 + && message.args.at (0) == "0" + && message.args.at (1) == "true";}); + QVERIFY2 (!acknowledgements->ptt_before_prerequisites && split_command >= 0 + && split_ack > split_command && tx_vfo_command >= 0 + && tx_vfo_ack > tx_vfo_command && ptt_command > split_ack + && ptt_command > tx_vfo_ack, + qPrintable (harness.diagnostics ())); + QVERIFY (harness.state ().split ()); + QCOMPARE (harness.state ().tx_frequency (), tx_frequency); + QVERIFY (harness.state ().ptt ()); + } + + void unsolicited_split_divergence_converges_without_ptt () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + + auto requested = state_from (harness); + requested.tx_frequency (14076050); + requested.split (true); + auto const setup_cursor = harness.set (requested, 35); + QVERIFY2 (harness.wait_for_state ( + setup_cursor, 35, + [] (State const& state) {return state.split ();}), + qPrintable (harness.diagnostics ())); + QVERIFY (harness.state ().split ()); + + auto const operation_start = harness.server ().transcript ().size (); + auto const observation_cursor = harness.observation_count (); + harness.server ().send_text (QStringLiteral ("split_enable:0,false")); + + QVERIFY (harness.server ().wait_for ( + [&harness, operation_start, observation_cursor] + { + return message_index ( + harness.server (), operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}) + >= 0 + || harness.observed_state_since ( + observation_cursor, + [] (State const& state) {return !state.split ();}); + }, 1000)); + + auto const correction = message_index ( + harness.server (), operation_start, Direction::ClientToServer, + QStringLiteral ("split_enable"), + [] (Message const& message) {return has_args (message, {"0", "true"});}); + if (correction >= 0) + { + QVERIFY (harness.server ().wait_for ( + [&harness] {return harness.state ().split ();}, 1000)); + } + else + { + QVERIFY2 (!harness.state ().split (), + qPrintable (harness.diagnostics ())); + } + QCOMPARE (message_index (harness.server (), operation_start, + Direction::ClientToServer, + QStringLiteral ("trx")), -1); + } + + void explicit_stop_can_restart_on_a_new_connection_generation () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const first_generation = harness.server ().connection_generation (); + + QVERIFY2 (harness.stop (), qPrintable (harness.diagnostics ())); + QVERIFY2 (harness.restart (41), qPrintable (harness.diagnostics ())); + + QVERIFY (harness.server ().connection_generation () > first_generation); + auto const second_generation = harness.server ().connection_generation (); + QVERIFY (harness.state ().online ()); + QCOMPARE (harness.state ().frequency (), initial_frequency); + + auto requested = state_from (harness); + requested.frequency (14074125); + auto const update_cursor = harness.set (requested, 42); + QVERIFY2 (harness.wait_for_state ( + update_cursor, 42, + [] (State const& state) {return state.frequency () == 14074125;}), + qPrintable (harness.diagnostics ())); + QCOMPARE (harness.state ().frequency (), Frequency {14074125}); + auto const fresh_command = message_index ( + harness.server (), 0, Direction::ClientToServer, QStringLiteral ("vfo"), + [second_generation] (Message const& message) + { + return message.connection_generation == second_generation + && has_args (message, {"0", "0", "14074125"}); + }); + QVERIFY2 (fresh_command >= 0, qPrintable (harness.diagnostics ())); + } + + void in_flight_disconnect_is_bounded () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + harness.set_command_handler ( + [&harness] (QString const& verb, QStringList const& args, int) + { + if (verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074150"}) return false; + QTimer::singleShot (0, &harness.server (), + [&harness] {harness.server ().close_client ();}); + return true; + }); + auto requested = state_from (harness); + requested.frequency (14074150); + + QElapsedTimer deadline; + deadline.start (); + harness.set (requested, 42); + QVERIFY (harness.server ().wait_for ( + [&harness] {return harness.server ().client_disconnected ();}, 1000)); + + harness.set_command_handler ({}); + QVERIFY2 (harness.stop (), qPrintable (harness.diagnostics ())); + QVERIFY (deadline.elapsed () < 8000); + QVERIFY (harness.failure_count () - failure_cursor <= 1); + } + + void unexpected_stale_and_duplicate_messages_leave_coherent_state () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {14074200}; + auto const operation_start = harness.server ().transcript ().size (); + bool injected {false}; + harness.set_command_handler ( + [&harness, &injected] (QString const& verb, QStringList const& args, int) + { + if (injected || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074200"}) return false; + injected = true; + harness.server ().send_text ( + QStringLiteral ("unexpected:payload;vfo:1,0,not-a-frequency")); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074199"), 10); + harness.server ().send_text_later ( + QStringLiteral ("vfo:0,0,14074200;vfo:0,0,14074200"), 25); + return true; + }); + auto requested = state_from (harness); + requested.frequency (target); + harness.set (requested, 50); + + QVERIFY (harness.server ().wait_for ( + [&harness] + { + int correct_acks {0}; + for (auto const& message : harness.server ().messages ( + Direction::ServerToClient, QStringLiteral ("vfo"))) + { + if (has_args (message, {"0", "0", "14074200"})) ++correct_acks; + } + return correct_acks == 2; + }, 1000)); + QCOMPARE (harness.failure_count (), failure_cursor); + QVERIFY (harness.wait_for_current_state ( + [] (State const& state) {return state.frequency () == target;})); + QCOMPARE (harness.state ().frequency (), target); + + int requested_attempts {0}; + for (auto const& message : harness.server ().messages ( + Direction::ClientToServer, QStringLiteral ("vfo"))) + { + if (message.ordinal >= static_cast<quint64> (operation_start) + && has_args (message, {"0", "0", "14074200"})) + { + ++requested_attempts; + } + } + QVERIFY (requested_attempts >= 1); + } + + void reentrant_duplicate_request_is_bounded_and_coherent () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr target {14074250}; + auto requested = state_from (harness); + requested.frequency (target); + bool reentered {false}; + harness.set_command_handler ( + [&harness, &reentered, requested] (QString const& verb, + QStringList const& args, int) + { + if (reentered || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074250"}) return false; + reentered = true; + harness.schedule_set (requested, 61); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074250"), 25); + return true; + }); + + auto const reentrant_cursor = harness.observation_count (); + harness.set_now (requested, 60); + QCOMPARE (harness.failure_count (), failure_cursor); + QCOMPARE (harness.state ().frequency (), target); + QVERIFY (reentered); + QVERIFY2 (harness.observed_state_since ( + reentrant_cursor, 61, + [] (State const& state) {return state.frequency () == target;}), + qPrintable (harness.diagnostics ())); + } + + void reentrant_superseding_request_remains_recoverable () + { + RigHarness harness; + QVERIFY (harness.listen ()); + QVERIFY2 (harness.start (), qPrintable (harness.diagnostics ())); + auto const failure_cursor = harness.failure_count (); + + Frequency constexpr first_target {14074300}; + Frequency constexpr latest_target {14074350}; + auto first = state_from (harness); + first.frequency (first_target); + auto latest = first; + latest.frequency (latest_target); + bool reentered {false}; + harness.set_command_handler ( + [&harness, &reentered, latest] (QString const& verb, + QStringList const& args, int) + { + if (reentered || verb != QStringLiteral ("vfo") + || args != QStringList {"0", "0", "14074300"}) return false; + reentered = true; + harness.schedule_set (latest, 71); + harness.server ().send_text_later (QStringLiteral ("vfo:0,0,14074300"), 25); + return true; + }); + + auto const reentrant_cursor = harness.observation_count (); + harness.set_now (first, 70); + auto const settled = harness.state ().frequency (); + QVERIFY (settled == first_target || settled == latest_target); + QCOMPARE (harness.failure_count (), failure_cursor); + QVERIFY2 (harness.observed_state_since ( + reentrant_cursor, 71, + [] (State const&) {return true;}), + qPrintable (harness.diagnostics ())); + + harness.set_now (latest, 72); + QCOMPARE (harness.failure_count (), failure_cursor); + QCOMPARE (harness.state ().frequency (), latest_target); + QVERIFY (reentered); + } +}; + +QTEST_GUILESS_MAIN (TestTciTransceiverCharacterization) + +#include "test_tci_transceiver_characterization.moc" diff --git a/tests/unit/tci/test_transceiver_base_period.cpp b/tests/unit/tci/test_transceiver_base_period.cpp new file mode 100644 index 00000000..976e6651 --- /dev/null +++ b/tests/unit/tci/test_transceiver_base_period.cpp @@ -0,0 +1,164 @@ +#include "Transceiver/TransceiverBase.hpp" + +#include <stdexcept> + +#include <boost/log/keywords/channel.hpp> + +#include <QSignalSpy> +#include <QtTest> + +namespace +{ + class PeriodRecordingTransceiver final + : public TransceiverBase + { + public: + explicit PeriodRecordingTransceiver (logger_type * logger) + : TransceiverBase {logger, nullptr} + { + } + + QVector<double> applied_periods; + QStringList events; + double backend_period {15.0}; + bool fail_next_period {false}; + + protected: + int do_start () override {return 0;} + void do_stop () override {backend_period = 15.0;} + void do_frequency (Frequency, MODE, bool) override {} + void do_tx_frequency (Frequency, MODE, bool) override {} + void do_mode (MODE) override {} + void do_ptt (bool) override {} + + void do_period (double period) override + { + events.append (QStringLiteral ("period")); + if (fail_next_period) + { + fail_next_period = false; + throw std::runtime_error {"period rejected"}; + } + backend_period = period; + applied_periods.append (period); + } + + void do_modulator_start (TxEvidence::TxRequest const&) override + { + events.append (QStringLiteral ("modulator")); + } + }; + + Transceiver::TransceiverState online_state () + { + Transceiver::TransceiverState state; + state.online (true); + return state; + } +} + +class TestTransceiverBasePeriod final + : public QObject +{ + Q_OBJECT + +private slots: + void initial_period_is_applied_even_when_it_matches_state_default () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + QVector<double> expected {120.0}; + + rig.set (online_state (), 1); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } + + void unchanged_period_is_not_reapplied () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0}; + + rig.set (state, 1); + rig.set (state, 2); + + QCOMPARE (rig.applied_periods, expected); + } + + void changed_period_is_applied_once () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0, 15.0}; + + rig.set (state, 1); + state.period (15.0); + rig.set (state, 2); + rig.set (state, 3); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 15.0); + } + + void period_is_reapplied_after_restart () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QVector<double> expected {120.0, 120.0}; + + rig.set (state, 1); + rig.stop (); + rig.start (2); + state = online_state (); + rig.set (state, 3); + + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } + + void period_is_applied_before_modulator_start () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + auto state = online_state (); + QStringList expected {QStringLiteral ("period"), + QStringLiteral ("modulator")}; + state.tx_audio (true); + + rig.set (state, 1); + + QCOMPARE (rig.events, expected); + } + + void failed_period_is_retried () + { + Transceiver::logger_type logger { + boost::log::keywords::channel = "TEST"}; + PeriodRecordingTransceiver rig {&logger}; + QSignalSpy failures {&rig, &Transceiver::failure}; + auto state = online_state (); + QVector<double> expected {120.0}; + rig.fail_next_period = true; + + rig.set (state, 1); + rig.set (state, 2); + + QCOMPARE (failures.count (), 1); + QCOMPARE (rig.applied_periods, expected); + QCOMPARE (rig.backend_period, 120.0); + } +}; + +QTEST_GUILESS_MAIN (TestTransceiverBasePeriod) + +#include "test_transceiver_base_period.moc" diff --git a/tests/unit/wsprd/CMakeLists.txt b/tests/unit/wsprd/CMakeLists.txt new file mode 100644 index 00000000..47580f6c --- /dev/null +++ b/tests/unit/wsprd/CMakeLists.txt @@ -0,0 +1,7 @@ +add_executable (test_wsprd_utils + test_wsprd_utils.c + ${CMAKE_SOURCE_DIR}/lib/lookup3.c + ${CMAKE_SOURCE_DIR}/lib/wsprd/wsprd_utils.c + ${CMAKE_SOURCE_DIR}/lib/wsprd/nhash.c) + +add_test (NAME test_wsprd_utils COMMAND test_wsprd_utils) diff --git a/tests/unit/wsprd/test_wsprd_utils.c b/tests/unit/wsprd/test_wsprd_utils.c new file mode 100644 index 00000000..6a840f22 --- /dev/null +++ b/tests/unit/wsprd/test_wsprd_utils.c @@ -0,0 +1,253 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "lib/wsprd/nhash.h" +#include "lib/wsprd/wsprd_utils.h" + +struct wspr_vector { + const char *name; + signed char data[11]; + const char *message; + const char *callsign; +}; + +static int failures = 0; + +static void expect_string(const char *label, const char *actual, + const char *expected) +{ + if( strcmp(actual, expected) != 0 ) { + fprintf(stderr, "%s: expected '%s', got '%s'\n", + label, expected, actual); + failures++; + } +} + +static void expect_int(const char *label, int actual, int expected) +{ + if( actual != expected ) { + fprintf(stderr, "%s: expected %d, got %d\n", + label, expected, actual); + failures++; + } +} + +static void decode_vector(const struct wspr_vector *vector, + char *hashtab, char *loctab) +{ + char call_loc_pow[23] = {0}; + char callsign[13] = {0}; + int noprint = unpk_((signed char *)vector->data, hashtab, loctab, + call_loc_pow, callsign); + + expect_int(vector->name, noprint, 0); + expect_string(vector->name, call_loc_pow, vector->message); + expect_string(vector->name, callsign, vector->callsign); +} + +static void expect_hash_entry(const char *callsign, const char *grid, + char *hashtab, char *loctab) +{ + int ihash = nhash(callsign, strlen(callsign), (uint32_t)146); + expect_string(callsign, hashtab + ihash * WSPRD_CALLSIGN_SIZE, callsign); + if( grid != NULL ) { + expect_string(callsign, loctab + ihash * WSPRD_GRID4_SIZE, grid); + } +} + +static void expect_hash_slot(int ihash, const char *callsign, const char *grid, + char *hashtab, char *loctab) +{ + expect_string(callsign, hashtab + ihash * WSPRD_CALLSIGN_SIZE, callsign); + expect_string(callsign, loctab + ihash * WSPRD_GRID4_SIZE, grid); +} + +static void run_with_fresh_tables(void (*test)(char *, char *)) +{ + char *hashtab = calloc(WSPRD_HASH_COUNT * WSPRD_CALLSIGN_SIZE, 1); + char *loctab = calloc(WSPRD_HASH_COUNT * WSPRD_GRID4_SIZE, 1); + if( hashtab == NULL || loctab == NULL ) { + fprintf(stderr, "failed to allocate WSPR hash tables\n"); + exit(2); + } + + test(hashtab, loctab); + + free(hashtab); + free(loctab); +} + +static const struct wspr_vector k1abc = { + "K1ABC FN42 33", + {-9, 12, 35, -117, 13, 24, 64, 0, 0, 0, 0}, + "K1ABC FN42 33", + "K1ABC" +}; + +static const struct wspr_vector n1d = { + "N1D FN42 33", + {-9, -99, 1, -117, 13, 24, 64, 0, 0, 0, 0}, + "N1D FN42 33", + "N1D" +}; + +static const struct wspr_vector five_n = { + "5N/6O0O 37", + {45, 15, -83, 104, 42, -103, -64, 0, 0, 0, 0}, + "5N/6O0O 37", + "5N/6O0O" +}; + +static const struct wspr_vector pj4 = { + "PJ4/K1ABC 37", + {-9, 12, 35, -127, 14, -103, -64, 0, 0, 0, 0}, + "PJ4/K1ABC 37", + "PJ4/K1ABC" +}; + +static const struct wspr_vector rover = { + "K1ABC/R 37", + {-9, 12, 35, -115, 79, 121, -64, 0, 0, 0, 0}, + "K1ABC/R 37", + "K1ABC/R" +}; + +static const struct wspr_vector k1abc_type3_unresolved = { + "<K1ABC> FN42AA 33", + {-100, 54, -76, -77, 47, 39, -128, 0, 0, 0, 0}, + "<...> FN42AA 33", + "<...>" +}; + +static const struct wspr_vector k1abc_type3_resolved = { + "<K1ABC> FN42AA 33", + {-100, 54, -76, -77, 47, 39, -128, 0, 0, 0, 0}, + "<K1ABC> FN42AA 33", + "<K1ABC>" +}; + +static const struct wspr_vector pj4_type3_unresolved = { + "<PJ4/K1ABC> FK52UD 37", + {-120, 36, 124, 105, -94, -26, -128, 0, 0, 0, 0}, + "<...> FK52UD 37", + "<...>" +}; + +static const struct wspr_vector pj4_type3_resolved = { + "<PJ4/K1ABC> FK52UD 37", + {-120, 36, 124, 105, -94, -26, -128, 0, 0, 0, 0}, + "<PJ4/K1ABC> FK52UD 37", + "<PJ4/K1ABC>" +}; + +static void test_standard_and_compound_messages(char *hashtab, char *loctab) +{ + decode_vector(&k1abc, hashtab, loctab); + expect_hash_entry("K1ABC", "FN42", hashtab, loctab); + + decode_vector(&n1d, hashtab, loctab); + expect_hash_entry("N1D", "FN42", hashtab, loctab); + + decode_vector(&five_n, hashtab, loctab); + expect_hash_entry("5N/6O0O", NULL, hashtab, loctab); + + decode_vector(&pj4, hashtab, loctab); + expect_hash_entry("PJ4/K1ABC", NULL, hashtab, loctab); + + decode_vector(&rover, hashtab, loctab); + expect_hash_entry("K1ABC/R", NULL, hashtab, loctab); +} + +static void test_type3_unresolved(char *hashtab, char *loctab) +{ + decode_vector(&k1abc_type3_unresolved, hashtab, loctab); + decode_vector(&pj4_type3_unresolved, hashtab, loctab); +} + +static void test_type3_resolved_k1abc(char *hashtab, char *loctab) +{ + decode_vector(&k1abc, hashtab, loctab); + decode_vector(&k1abc_type3_resolved, hashtab, loctab); +} + +static void test_type3_resolved_pj4(char *hashtab, char *loctab) +{ + decode_vector(&pj4, hashtab, loctab); + decode_vector(&pj4_type3_resolved, hashtab, loctab); +} + +static void test_hash_table_line_loading(char *hashtab, char *loctab) +{ + expect_int("load hash line with grid", + wsprd_load_hash_line(" 42 K1ABC FN42\n", hashtab, loctab), 1); + expect_hash_slot(42, "K1ABC", "FN42", hashtab, loctab); + + expect_int("load hash line without grid", + wsprd_load_hash_line("43 PJ4/K1ABC\n", hashtab, loctab), 1); + expect_hash_slot(43, "PJ4/K1ABC", "", hashtab, loctab); + + expect_int("load hash line with suffix call", + wsprd_load_hash_line("46 K1ABC/R\n", hashtab, loctab), 1); + expect_hash_slot(46, "K1ABC/R", "", hashtab, loctab); + + expect_int("load hash line with numeric suffix", + wsprd_load_hash_line("47 K1ABC/10\n", hashtab, loctab), 1); + expect_hash_slot(47, "K1ABC/10", "", hashtab, loctab); + + expect_int("load hash line with short prefix", + wsprd_load_hash_line("48 5N/6O0O\n", hashtab, loctab), 1); + expect_hash_slot(48, "5N/6O0O", "", hashtab, loctab); + + strcpy(loctab + 44 * WSPRD_GRID4_SIZE, "ABCD"); + expect_int("load hash line preserves missing grid", + wsprd_load_hash_line("44 K1ABC\n", hashtab, loctab), 1); + expect_hash_slot(44, "K1ABC", "ABCD", hashtab, loctab); + + strcpy(loctab + 49 * WSPRD_GRID4_SIZE, "ABCD"); + expect_int("load hash line preserves writer whitespace", + wsprd_load_hash_line(" 49\tPJ4/K1ABC \r\n", hashtab, loctab), 1); + expect_hash_slot(49, "PJ4/K1ABC", "ABCD", hashtab, loctab); + + expect_int("load hash line ignores trailing tokens", + wsprd_load_hash_line("45 K1ABC FN42 ignored\n", hashtab, loctab), 1); + expect_hash_slot(45, "K1ABC", "FN42", hashtab, loctab); + + expect_int("load max-size hash line", + wsprd_load_hash_line("32767 123456789012 ABCD\n", hashtab, loctab), 1); + expect_hash_slot(32767, "123456789012", "ABCD", hashtab, loctab); +} + +static void expect_rejected_hash_line(const char *line, + char *hashtab, char *loctab) +{ + const int slot = 7; + strcpy(hashtab + slot * WSPRD_CALLSIGN_SIZE, "KEEP"); + strcpy(loctab + slot * WSPRD_GRID4_SIZE, "ABCD"); + + expect_int(line, wsprd_load_hash_line(line, hashtab, loctab), 0); + expect_hash_slot(slot, "KEEP", "ABCD", hashtab, loctab); +} + +static void test_invalid_hash_table_lines(char *hashtab, char *loctab) +{ + expect_rejected_hash_line("", hashtab, loctab); + expect_rejected_hash_line("7\n", hashtab, loctab); + expect_rejected_hash_line("slot K1ABC FN42\n", hashtab, loctab); + expect_rejected_hash_line("-1 K1ABC FN42\n", hashtab, loctab); + expect_rejected_hash_line("32768 K1ABC FN42\n", hashtab, loctab); + expect_rejected_hash_line("7 1234567890123 FN42\n", hashtab, loctab); + expect_rejected_hash_line("7 K1ABC FN421\n", hashtab, loctab); +} + +int main(void) +{ + run_with_fresh_tables(test_standard_and_compound_messages); + run_with_fresh_tables(test_type3_unresolved); + run_with_fresh_tables(test_type3_resolved_k1abc); + run_with_fresh_tables(test_type3_resolved_pj4); + run_with_fresh_tables(test_hash_table_line_loading); + run_with_fresh_tables(test_invalid_hash_table_lines); + + return failures == 0 ? 0 : 1; +} |
