Merge main into the caller ID branch

Keeps main's V_CVM -> VCVM settings migration next to the new callerId
setting, and takes main's d-modem-re pin, which already holds the
caller ID merge (D-Modem/D-Modem#15).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRQooB42bttmxqnS23Z
This commit is contained in:
Claude committed 2026-10-30 21:39:38 +00:00
commit ef52a3f580
17 files changed
+641 -381

No files matched your search

+21 -4
View File
@@ -2,17 +2,25 @@
# build: the APK (all four ABIs), the unit tests and lint.
# native: the native engine on the runner against a dmodemd over loopback
# SIP (native-test).
# device: the instrumented tests on an emulator (x86_64): the native library
# loads, binds and answers AT commands.
# device: the instrumented tests on an emulator (x86_64, the one ABI it
# builds): the native library loads, binds and answers AT commands.
#
# D-Modem-RE is a private submodule: the DMODEM_TOKEN secret is a token
# that can read it (a fine-grained personal access token with Contents:
# read on D-Modem/D-Modem).
name: Android
# (a branch's commits run once, as its pull request: pushed, only main's)
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
# a newer commit on a pull request cancels the run before it (main's all run)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
NDK_VERSION: "29.0.14206865"
@@ -21,6 +29,8 @@ env:
jobs:
docs:
runs-on: ubuntu-24.04
# (a hung test ends here, not at GitHub's 6 hours)
timeout-minutes: 5
steps:
- uses: actions/checkout@v4
with:
@@ -32,6 +42,8 @@ jobs:
build:
runs-on: ubuntu-24.04
# (a hung test ends here, not at GitHub's 6 hours)
timeout-minutes: 40
steps:
- uses: actions/checkout@v4
with:
@@ -75,6 +87,8 @@ jobs:
native:
runs-on: ubuntu-24.04
# (a hung test ends here, not at GitHub's 6 hours)
timeout-minutes: 25
steps:
- uses: actions/checkout@v4
with:
@@ -84,7 +98,7 @@ jobs:
- name: Packages
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends cmake ninja-build g++ libssl-dev
sudo apt-get install -y --no-install-recommends cmake ninja-build g++ libssl-dev libgtest-dev
- name: Build
run: |
@@ -114,6 +128,8 @@ jobs:
device:
runs-on: ubuntu-24.04
# (a hung test ends here, not at GitHub's 6 hours)
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
@@ -149,7 +165,8 @@ jobs:
arch: x86_64
target: google_apis
disable-animations: true
script: ./gradlew connectedDebugAndroidTest
# (the emulator's ABI only: the other three are the build job's)
script: ./gradlew -Pdmodem.abis=x86_64 connectedDebugAndroidTest
- uses: actions/upload-artifact@v4
if: always()
+10
View File
@@ -8,13 +8,23 @@
# android.yml's).
name: Apple
# (a branch's commits run once, as its pull request: pushed, only main's)
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
# a newer commit on a pull request cancels the run before it (main's all run)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
engine:
runs-on: macos-15
# (a hung test ends here, not at GitHub's 6 hours)
timeout-minutes: 50
steps:
- uses: actions/checkout@v4
with:
+10 -3
View File
@@ -27,7 +27,7 @@ speech through codecs that wreck modem signals; native-test's
| AMR-NB 4.75 kbit/s, GSM full rate (2G) | nothing reliable |
Between two D-Modems, V.cvm (D-Modem-RE's modem for speech codecs,
`+MS=V_CVM`) does better: after V.8 it spends 15 to 20 s probing the
`+MS=VCVM`) does better: after V.8 it spends 15 to 20 s probing the
codec, then loads a mode for it, with LAPM over it. Through AMR-NB 12.2
the app's engines connect at about 1200 bit/s coded (750 to 1200 each
way, `CONNECT 1200/CVM/LAPM/V44`; D-Modem-RE measured 175 to 350 through
@@ -229,7 +229,9 @@ no `/etc/resolv.conf` for libre to read.
`BoxDrawing`, `Themes`, the directory and snippets.
- `native-test`: the engine on the build host, against a dmodemd over
loopback SIP (dialling out, data both ways, restarting, a call coming
in, the app closing its end), and on fake USB modems (`usb_line_test.py`).
in, the app closing its end) and through the C API, as GoogleTest
tests (`engine_test.cpp`, `c_api_test.cpp`), and on fake USB modems
(`usb_line_test.py`).
## Building
@@ -260,12 +262,17 @@ The native library alone, without Gradle:
-DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26
cmake --build build-arm64 --target dmodem_jni
The host test needs OpenSSL's headers (libssl-dev):
The host test needs OpenSSL's headers (libssl-dev), and GoogleTest
(libgtest-dev, else CMake fetches it):
cmake -S native-test -B build-host -G Ninja
cmake --build build-host
ctest --test-dir build-host --output-on-failure
Each engine test is a ctest test of its own (`ctest -R engine.` for
those alone); `build-host/engine_test --gtest_filter=*Ringing` runs one
directly, `ENGINE_TEST_LOG=1` with the engine's log as it comes.
With `build-host` built, the unit tests also make calls on its test
lines (fax between modems, against efax and D-Modem-RE's own T.30, over
SIP with T.38, phone to phone, through mobile codecs); without it those
+8 -2
View File
@@ -20,6 +20,12 @@ fun commitOf(dir: File): String {
return if (dirty) "$c-dirty" else c
}
// the ABIs built (native code and proot): all four, or -Pdmodem.abis=x86_64 (comma-separated) for fewer,
// as CI's emulator job has it
val appAbis = providers.gradleProperty("dmodem.abis").orNull
?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }
?: listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86")
android {
namespace = "com.neodesktop.dmodem"
compileSdk = 37
@@ -41,7 +47,7 @@ android {
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
ndk {
abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86")
abiFilters += appAbis
}
externalNativeBuild {
cmake {
@@ -164,7 +170,7 @@ tasks.withType<Test>().configureEach {
}
// proot and its loader for the local shell's Linux (native-proot/build.sh: Termux's proot, external/proot)
val prootAbis = listOf("arm64-v8a", "armeabi-v7a", "x86_64", "x86")
val prootAbis = appAbis
val buildProot = tasks.register("buildProot") {
description = "Builds proot and its loader for each ABI with the NDK"
}
@@ -37,10 +37,15 @@ class NativeModemTest {
NativeModem.listener = null
}
/** a SIP account at nowhere (no call is made), the modem's data in the app's files */
/**
* a SIP account at nowhere (no call is made), the modem's data in the
* app's files; SIP's log at level 4, which names its addresses
* ("SIP on ...") before start returns: at 3 a modem with no call and
* no registrar has nothing to say in the test's time
*/
private fun config() = NativeModem.Config(
user = "test", password = "x", domain = "127.0.0.1:5999", sipPort = 15060,
dns = listOf("127.0.0.1"), logLevel = 1, sipLogLevel = 3,
dns = listOf("127.0.0.1"), logLevel = 1, sipLogLevel = 4,
dataFile = File(InstrumentationRegistry.getInstrumentation().targetContext.filesDir, "test_dsp").path,
)
@@ -58,7 +58,7 @@ data class ModemSettings(
/** caller ID on (AT+VCID=1): a ringing call's number and name in the terminal, its popup and notification */
val callerId: Boolean = true,
/**
* the modulation on mobile calls (+MS): V_CVM (V.cvm, made for speech codecs: about 1200 bit/s
* the modulation on mobile calls (+MS): VCVM (V.cvm, made for speech codecs: about 1200 bit/s
* through AMR 12.2, to another D-Modem; V.22 or V.21 to other modems), V21 (300 bit/s), V22, V22B
*/
val cellSpeed: String = CELL_VCVM,
@@ -120,8 +120,8 @@ data class ModemSettings(
const val LINE_NONE = "none"
const val LINE_USB = "usb"
const val LINE_BT_MODEM = "bt_modem"
/** the mobile-call line's V.cvm (D-Modem-RE's +MS=V_CVM) */
const val CELL_VCVM = "V_CVM"
/** the mobile-call line's V.cvm (D-Modem-RE's +MS=VCVM) */
const val CELL_VCVM = "VCVM"
/**
* An account as `user:password@host[:port]` (dmodemd's SIP_LOGIN): null if it isn't one.
@@ -196,7 +196,8 @@ class SettingsStore(private val context: Context) {
callTones = p[Keys.callTones] ?: d.callTones,
adaptiveAnswer = p[Keys.adaptiveAnswer] ?: d.adaptiveAnswer,
callerId = p[Keys.callerId] ?: d.callerId,
cellSpeed = p[Keys.cellSpeed] ?: d.cellSpeed,
// V_CVM: the name before VCVM, kept by older versions
cellSpeed = (p[Keys.cellSpeed] ?: d.cellSpeed).let { if (it == "V_CVM") ModemSettings.CELL_VCVM else it },
btModemAddress = p[Keys.btModemAddress] ?: d.btModemAddress,
btModemName = p[Keys.btModemName] ?: d.btModemName,
recordLine = p[Keys.recordLine] ?: d.recordLine,
@@ -95,8 +95,8 @@ class CellLineTest {
val b = CellModem("cvmB", net.phone("5550002"), listen = true)
// V.cvm (D-Modem-RE's, for speech codecs): V.8, then 15 to 21 s probing the codec and
// loading a mode for it; S7 long enough for that
a.command("ATE0\\V1+MS=V_CVM;S7=90")
b.command("ATE0\\V1S0=1+MS=V_CVM;S7=90")
a.command("ATE0\\V1+MS=VCVM;S7=90")
b.command("ATE0\\V1S0=1+MS=VCVM;S7=90")
a.send("ATD5550002\r")
val ca = a.connectLine()
val cb = b.connectLine()
@@ -13,7 +13,7 @@ class CellSettingsTest {
fun startCommands() {
val cell = ModemSettings(line = ModemSettings.LINE_CELL)
// (V.cvm by default, S7 long enough for its start-up)
assertEquals("AT+MS=V_CVM;S7=90;X3", cell.startCommands())
assertEquals("AT+MS=VCVM;S7=90;X3", cell.startCommands())
assertEquals("AT+MS=V21;X3", cell.copy(cellSpeed = "V21").startCommands())
assertEquals("AT+MS=V22B;X3M2", cell.copy(cellSpeed = "V22B", initCommands = "atX3M2").startCommands())
assertEquals("AT+MS=V21", cell.copy(cellSpeed = "V21", initCommands = " ").startCommands())
+32 -11
View File
@@ -14,12 +14,34 @@ add_subdirectory(../app/src/main/cpp app)
# (D-Modem-RE's u8 .. s64, its include/dm_types.h)
include_directories(${DMODEM_RE_INCLUDE})
add_executable(engine_test engine_test.cpp)
target_link_libraries(engine_test PRIVATE dmodem_engine)
target_compile_options(engine_test PRIVATE -Wall -Wextra)
# GoogleTest for the engine's tests: the system's (libgtest-dev) or else
# fetched, as D-Modem-RE has it (its cmake/gtest.cmake)
find_package(GTest 1.10 QUIET)
if(NOT GTest_FOUND)
include(FetchContent)
FetchContent_Declare(googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
GIT_SHALLOW TRUE)
set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
set(BUILD_GMOCK OFF CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
if(NOT TARGET GTest::gtest)
add_library(GTest::gtest ALIAS gtest)
endif()
endif()
include(GoogleTest)
add_test(NAME engine COMMAND engine_test $<TARGET_FILE:dmodemd>)
set_tests_properties(engine PROPERTIES TIMEOUT 600)
# engine_test: the engine against a dmodemd over loopback SIP, each of
# its tests a ctest test of its own (each with a dmodemd of its own, on
# the same ports: one at a time)
add_executable(engine_test engine_test.cpp)
target_link_libraries(engine_test PRIVATE dmodem_engine GTest::gtest)
target_compile_options(engine_test PRIVATE -Wall -Wextra)
target_compile_definitions(engine_test PRIVATE DMODEMD_PATH="$<TARGET_FILE:dmodemd>")
add_dependencies(engine_test dmodemd)
gtest_discover_tests(engine_test TEST_PREFIX engine.
PROPERTIES TIMEOUT 300 RESOURCE_LOCK loopback_sip)
# fax_line: modem_test's two modems back to back, paced as a phone line
# (the app's fax tests, FaxCallTest, call over it)
@@ -73,13 +95,12 @@ if(AMRNB_LIB)
endif()
# c_api_test: the engine through its C API (dmodem_engine.h), as iOS's
# Swift has it
add_executable(c_api_test c_api_test.c)
target_link_libraries(c_api_test PRIVATE dmodem_engine Threads::Threads)
# Swift has it (and its header from C: c_api_header.c)
add_executable(c_api_test c_api_test.cpp c_api_header.c)
target_link_libraries(c_api_test PRIVATE dmodem_engine GTest::gtest
Threads::Threads)
target_compile_options(c_api_test PRIVATE -Wall -Wextra)
set_target_properties(c_api_test PROPERTIES LINKER_LANGUAGE CXX)
add_test(NAME c_api COMMAND c_api_test)
set_tests_properties(c_api PROPERTIES TIMEOUT 120)
gtest_discover_tests(c_api_test TEST_PREFIX c_api. PROPERTIES TIMEOUT 120)
# usb_line_test: the engine on a USB modem's line (usb/usb_modem.h), two
# of them on D-Modem-RE's fake pico-serial Line sticks (its
+21
View File
@@ -0,0 +1,21 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* c_api_header.c - dmodem_engine.h as a C program has it, for
* c_api_test: its types and calls from C.
*
*/
#include "dmodem_engine.h"
/* the C API's config and callbacks from C: 0 if the defaults came */
int c_api_header_from_c(void)
{
dmodem_config c;
dmodem_callbacks cb = { 0 };
(void)cb;
dmodem_config_init(&c);
return c.sip_port == 5060 ? 0 : 1;
}
-168
View File
@@ -1,168 +0,0 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* c_api_test.c - the engine through its C API (dmodem_engine.h), as a
* program in C or Swift (iOS) has it: on a peer line,
* AT commands answered, a dial handing the program
* its line, the program's BUSY, the status and the
* speaker reported, the modem ended by closing its
* DTE.
*
*/
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "dmodem_engine.h"
static int failures;
#define CHECK(cond, ...) do { \
if (cond) { printf("ok: " __VA_ARGS__); printf("\n"); } \
else { printf("FAIL (%s:%d): ", __FILE__, __LINE__); \
printf(__VA_ARGS__); printf("\n"); failures++; } } while (0)
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static int line_fd = -1, line_caller = -1, exits = 0, exit_result = 99;
static int statuses, speaker_on, logs;
static char line_dial[64];
/* a log line counted */
static void on_log(void *ctx, const char *l) { (void)ctx; (void)l; __sync_fetch_and_add(&logs, 1); }
/* a status report counted */
static void on_status(void *ctx, int link, int offhook, unsigned tx, unsigned rx)
{
(void)ctx; (void)link; (void)offhook; (void)tx; (void)rx;
__sync_fetch_and_add(&statuses, 1);
}
/* the modem's exit counted, its result kept */
static void on_exit_(void *ctx, int r)
{
(void)ctx;
pthread_mutex_lock(&mu);
exits++;
exit_result = r;
pthread_mutex_unlock(&mu);
}
/* a peer line's fd, which end and the number dialled kept */
static void on_line(void *ctx, int caller, const char *dial, int fd)
{
(void)ctx;
pthread_mutex_lock(&mu);
line_fd = fd;
line_caller = caller;
snprintf(line_dial, sizeof(line_dial), "%s", dial);
pthread_mutex_unlock(&mu);
}
/* the speaker seen on */
static void on_speaker(void *ctx, int level) { (void)ctx; if (level > 0) speaker_on = 1; }
/* text from fd until want (or secs) */
static int expect(int fd, const char *want, int secs)
{
char buf[4096];
size_t have = 0;
for (int i = 0; i < secs * 10; i++) {
struct pollfd p = { fd, POLLIN, 0 };
if (poll(&p, 1, 100) > 0) {
ssize_t n = read(fd, buf + have, sizeof(buf) - 1 - have);
if (n <= 0)
break;
have += (size_t)n;
buf[have] = 0;
if (strstr(buf, want))
return 1;
}
}
buf[have] = 0;
printf(" (waited for \"%s\", got \"%s\")\n", want, buf);
return 0;
}
/* s written to fd */
static void put(int fd, const char *s)
{
if (write(fd, s, strlen(s)) < 0)
perror("write");
}
/* the engine on a peer line through its C API, each step checked: 1 if any failed */
int main(void)
{
dmodem_config c;
dmodem_callbacks cb = { 0 };
int dte, fd = -1;
signal(SIGPIPE, SIG_IGN);
cb.log = on_log;
cb.status = on_status;
cb.exited = on_exit_;
cb.line = on_line;
cb.speaker = on_speaker;
dmodem_set_callbacks(&cb);
dmodem_config_init(&c);
CHECK(c.sip_port == 5060 && c.t38 && c.peer_lead_ms == 100, "the defaults");
c.peer = 1;
c.log_level = 1;
dte = dmodem_start(&c);
CHECK(dte >= 0 && dmodem_running(), "started on a peer line");
CHECK(dmodem_start(&c) < 0, "a second start refused");
put(dte, "ATE0\r");
CHECK(expect(dte, "OK", 5), "ATE0: OK");
put(dte, "ATI3\r");
CHECK(expect(dte, "peer", 5), "ATI3: the peer line's driver");
/* a dial: the line handed over; the program says BUSY */
put(dte, "ATX3D5551234\r");
for (int i = 0; i < 50 && fd < 0; i++) {
usleep(100000);
pthread_mutex_lock(&mu);
fd = line_fd;
pthread_mutex_unlock(&mu);
}
CHECK(fd >= 0 && line_caller == 1 && strstr(line_dial, "5551234"),
"ATD: the line to the program (dialling %s)", line_dial);
CHECK(speaker_on, "the speaker on as it dials (ATM1)");
dmodem_peer_event("FAILED 486");
if (fd >= 0)
close(fd);
CHECK(expect(dte, "BUSY", 10), "the program's FAILED 486: BUSY");
/* no line at all (the app's "no line"): NO DIALTONE */
pthread_mutex_lock(&mu);
line_fd = -1;
pthread_mutex_unlock(&mu);
fd = -1;
put(dte, "ATD1\r");
for (int i = 0; i < 50 && fd < 0; i++) {
usleep(100000);
pthread_mutex_lock(&mu);
fd = line_fd;
pthread_mutex_unlock(&mu);
}
CHECK(fd >= 0, "ATD again: the line to the program");
dmodem_peer_event("NO LINE");
if (fd >= 0)
close(fd);
CHECK(expect(dte, "NO DIALTONE", 10), "the program's NO LINE: NO DIALTONE");
CHECK(statuses > 0 && logs > 0, "status (%d) and log (%d) reported", statuses, logs);
/* the DTE closed: the modem ends */
close(dte);
for (int i = 0; i < 50 && dmodem_running(); i++)
usleep(100000);
pthread_mutex_lock(&mu);
CHECK(!dmodem_running() && exits == 1 && exit_result == 0,
"the DTE closed: the modem ended (%d)", exit_result);
pthread_mutex_unlock(&mu);
dmodem_stop();
printf(failures ? "FAIL: %d\n" : "PASS\n", failures);
return failures ? 1 : 0;
}
+239
View File
@@ -0,0 +1,239 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (C) 2026 Neo-Desktop
*
* c_api_test.cpp - the engine through its C API (dmodem_engine.h), as a
* program in C or Swift (iOS) has it (GoogleTest): on
* a peer line, AT commands answered, a dial handing
* the program its line, the program's BUSY and NO
* LINE, the status and the speaker reported, the
* modem ended by closing its DTE. (The header as C
* compiles too: c_api_header.c.)
*
*/
#include <errno.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <string>
#include <gtest/gtest.h>
#include "dmodem_engine.h"
/* (c_api_header.c's: the header's types and calls from C) */
extern "C" int c_api_header_from_c(void);
namespace {
pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
int line_fd = -1, line_caller = -1, exits = 0, exit_result = 99;
int statuses, speaker_on, logs;
char line_dial[64];
/* a log line counted */
void on_log(void *, const char *) { __sync_fetch_and_add(&logs, 1); }
/* a status report counted */
void on_status(void *, int, int, unsigned, unsigned)
{
__sync_fetch_and_add(&statuses, 1);
}
/* the modem's exit counted, its result kept */
void on_exit_(void *, int r)
{
pthread_mutex_lock(&mu);
exits++;
exit_result = r;
pthread_mutex_unlock(&mu);
}
/* a peer line's fd, which end and the number dialled kept */
void on_line(void *, int caller, const char *dial, int fd)
{
pthread_mutex_lock(&mu);
line_fd = fd;
line_caller = caller;
snprintf(line_dial, sizeof(line_dial), "%s", dial);
pthread_mutex_unlock(&mu);
}
/* the speaker seen on */
void on_speaker(void *, int level) { if (level > 0) speaker_on = 1; }
/* text from fd until want (or secs); what came instead in the failure */
testing::AssertionResult expect(int fd, const char *want, int secs)
{
char buf[4096];
size_t have = 0;
buf[0] = 0;
for (int i = 0; i < secs * 10; i++) {
struct pollfd p = { fd, POLLIN, 0 };
if (poll(&p, 1, 100) > 0) {
ssize_t n = read(fd, buf + have, sizeof(buf) - 1 - have);
if (n <= 0)
break;
have += (size_t)n;
buf[have] = 0;
if (strstr(buf, want))
return testing::AssertionSuccess();
}
}
return testing::AssertionFailure() << "waited " << secs << " s for \""
<< want << "\", got \"" << buf << "\"";
}
/* s written to fd */
void put(int fd, const char *s)
{
if (write(fd, s, strlen(s)) < 0)
perror("write");
}
/* the line the program was handed within 5 s, -1 if none */
int wait_line()
{
int fd = -1;
for (int i = 0; i < 50 && fd < 0; i++) {
usleep(100000);
pthread_mutex_lock(&mu);
fd = line_fd;
pthread_mutex_unlock(&mu);
}
return fd;
}
/* dmodem_config_init(): SIP on 5060, T.38 on, a peer line's lead 100 ms */
TEST(CApi, Defaults)
{
dmodem_config c;
dmodem_config_init(&c);
EXPECT_EQ(c.sip_port, 5060);
EXPECT_TRUE(c.t38);
EXPECT_EQ(c.peer_lead_ms, 100);
}
/* the header's types and calls from C (c_api_header.c) */
TEST(CApi, HeaderAsC)
{
EXPECT_EQ(c_api_header_from_c(), 0);
}
/* each test: the engine started on a peer line (its DTE in dte), what it
reported cleared; after it the DTE closed and the modem stopped */
class CApiTest : public testing::Test {
protected:
dmodem_config c;
int dte = -1;
/* the callbacks, once for the suite */
static void SetUpTestSuite()
{
dmodem_callbacks cb = {};
cb.log = on_log;
cb.status = on_status;
cb.exited = on_exit_;
cb.line = on_line;
cb.speaker = on_speaker;
dmodem_set_callbacks(&cb);
}
/* what was reported cleared; the engine started on a peer line */
void SetUp() override
{
pthread_mutex_lock(&mu);
line_fd = line_caller = -1;
line_dial[0] = 0;
exits = 0;
exit_result = 99;
pthread_mutex_unlock(&mu);
statuses = speaker_on = logs = 0;
dmodem_config_init(&c);
c.peer = 1;
c.log_level = 1;
dte = dmodem_start(&c);
ASSERT_GE(dte, 0) << "started on a peer line";
ASSERT_TRUE(dmodem_running());
}
/* the DTE closed, the modem ended and stopped */
void TearDown() override
{
if (dte >= 0)
close(dte);
for (int i = 0; i < 50 && dmodem_running(); i++)
usleep(100000);
dmodem_stop();
}
};
/* a second start refused while it runs */
TEST_F(CApiTest, SecondStartRefused)
{
EXPECT_LT(dmodem_start(&c), 0);
}
/* ATE0: OK; ATI3: the peer line's driver */
TEST_F(CApiTest, AnswersAtCommands)
{
put(dte, "ATE0\r");
EXPECT_TRUE(expect(dte, "OK", 5)) << "ATE0";
put(dte, "ATI3\r");
EXPECT_TRUE(expect(dte, "peer", 5)) << "ATI3: the peer line's driver";
}
/* a dial: the line handed over, the speaker on (ATM1); the program says
BUSY (FAILED 486) */
TEST_F(CApiTest, DialHandsTheLineOverAndTheProgramSaysBusy)
{
put(dte, "ATX3D5551234\r");
int fd = wait_line();
ASSERT_GE(fd, 0) << "ATD: the line to the program";
EXPECT_EQ(line_caller, 1);
EXPECT_NE(strstr(line_dial, "5551234"), nullptr) << "dialling " << line_dial;
EXPECT_TRUE(speaker_on) << "the speaker on as it dials (ATM1)";
dmodem_peer_event("FAILED 486");
close(fd);
EXPECT_TRUE(expect(dte, "BUSY", 10)) << "the program's FAILED 486";
}
/* no line at all (the app's "no line"): NO DIALTONE; status and log
reported on the way */
TEST_F(CApiTest, NoLineIsNoDialtone)
{
put(dte, "ATD1\r");
int fd = wait_line();
ASSERT_GE(fd, 0) << "ATD: the line to the program";
dmodem_peer_event("NO LINE");
close(fd);
EXPECT_TRUE(expect(dte, "NO DIALTONE", 10)) << "the program's NO LINE";
EXPECT_GT(statuses, 0) << "status reported";
EXPECT_GT(logs, 0) << "log reported";
}
/* the DTE closed: the modem ends, 0 */
TEST_F(CApiTest, EndsWhenTheDteCloses)
{
close(dte);
dte = -1;
for (int i = 0; i < 50 && dmodem_running(); i++)
usleep(100000);
EXPECT_FALSE(dmodem_running());
pthread_mutex_lock(&mu);
EXPECT_EQ(exits, 1);
EXPECT_EQ(exit_result, 0);
pthread_mutex_unlock(&mu);
}
} // namespace
/* the tests (SIGPIPE ignored: the line's fd closed under the modem) */
int main(int argc, char *argv[])
{
signal(SIGPIPE, SIG_IGN);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+229 -177
View File
@@ -3,16 +3,18 @@
* Copyright (C) 2026 Neo-Desktop
*
* engine_test.cpp - the app's engine (app/src/main/cpp/engine.h) on the
* build host, against a dmodemd over loopback SIP:
* build host, against a dmodemd over loopback SIP
* (GoogleTest), each test with a dmodemd of its own:
*
* - dialling out: CONNECT, data both ways, the status going online
* with the rates, a hangup;
* - stop() and start() again (the SIP user agent made anew), a second
* call;
* - a call coming in (listening): RING, ATA, CONNECT;
* - the app closing its end of the DTE: the engine ends by itself.
* - stop() and start() again (the SIP user agent made anew), a call;
* - a call coming in (listening): RING, ATA, CONNECT; the app closing
* its end of the DTE: the engine ends by itself;
* - hung up while the call rings.
*
* engine_test <dmodemd>
* engine_test [gtest flags] [dmodemd] (else the build's dmodemd)
* ENGINE_TEST_LOG=1: the engine's log as it comes, too
*
*/
@@ -27,7 +29,6 @@
#include <termios.h>
#include <unistd.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
@@ -35,24 +36,19 @@
#include <string>
#include <thread>
#include <gtest/gtest.h>
#include "engine.h"
using namespace dmodem_android;
namespace {
int failures;
#define CHECK(cond, ...) do { \
if (cond) { \
printf("ok: " __VA_ARGS__); printf("\n"); \
} else { \
printf("FAIL (%s:%d): ", __FILE__, __LINE__); \
printf(__VA_ARGS__); printf("\n"); failures++; \
} } while (0)
const int ENGINE_PORT = 5181, DMODEMD_PORT = 5182;
/* the dmodemd the tests call: argv's, else the build's */
const char *dmodemd_path = DMODEMD_PATH;
/* what the engine reported */
std::mutex mu;
std::condition_variable cv;
@@ -96,8 +92,19 @@ bool wait_exits(int n, int secs)
[n] { return exits >= n; });
}
/* text from fd until re matches (the text so far in *got), or secs */
bool expect(int fd, const char *re, int secs, std::string *got = nullptr)
/* whether the status is idle and on hook within secs */
bool wait_idle(int secs)
{
std::unique_lock<std::mutex> lk(mu);
return cv.wait_for(lk, std::chrono::seconds(secs),
[] { return last.link == Status::IDLE &&
!last.offhook; });
}
/* text from fd until re matches (the text so far in *got), or secs;
what came instead in the failure */
testing::AssertionResult expect(int fd, const std::string &re, int secs,
std::string *got = nullptr)
{
std::string buf;
std::regex r(re);
@@ -114,14 +121,14 @@ bool expect(int fd, const char *re, int secs, std::string *got = nullptr)
if (std::regex_search(buf, r)) {
if (got)
*got = buf;
return true;
return testing::AssertionSuccess();
}
}
}
if (got)
*got = buf;
printf(" (waited for /%s/, got: \"%s\")\n", re, buf.c_str());
return false;
return testing::AssertionFailure() << "waited " << secs << " s for /"
<< re << "/, got: \"" << buf << "\"";
}
/* s written to fd */
@@ -176,8 +183,11 @@ pid_t start_dmodemd(const char *path, int *pty)
;
close(fd);
}).detach();
if (m.empty())
if (m.empty()) {
kill(pid, SIGTERM);
waitpid(pid, nullptr, 0);
return -1;
}
*pty = open(m[1].str().c_str(), O_RDWR | O_NOCTTY);
struct termios t;
tcgetattr(*pty, &t);
@@ -201,91 +211,220 @@ Config config(bool listen)
return c;
}
/* a call from the engine to dmodemd and back: CONNECT, data both ways,
the status online, a hangup from the engine's side */
void call_out(int app, int pty, const char *what, bool speaker)
{
std::string got;
long heard;
/* each test: a dmodemd of its own answering the engine's calls itself
(ATS0=1), what the engine reported cleared; after it the engine
stopped, the app's end closed, dmodemd gone (and the engine's log
shown if the test failed) */
class EngineTest : public testing::Test {
protected:
Engine &e = Engine::instance();
int pty = -1, app = -1;
pid_t dm = -1;
/* what was reported cleared; a dmodemd of its own, answering (ATS0=1) */
void SetUp() override
{
std::lock_guard<std::mutex> lk(mu);
was_online = false;
{
std::lock_guard<std::mutex> lk(mu);
last = Status();
was_online = false;
online_tx = online_rx = 0;
exits = 0;
exit_result = 99;
spk_level = 0;
spk_was_on = false;
spk_samples = 0;
logs.clear();
}
dm = start_dmodemd(dmodemd_path, &pty);
ASSERT_GT(dm, 0) << "dmodemd (" << dmodemd_path << ") started";
ASSERT_GE(pty, 0) << "dmodemd's pty opened";
put(pty, "ATS0=1\r");
ASSERT_TRUE(expect(pty, "OK", 5)) << "dmodemd: ATS0=1";
}
/* the engine stopped, the app's end closed, dmodemd gone; the log if it failed */
void TearDown() override
{
std::lock_guard<std::mutex> lk(mu);
spk_was_on = false;
spk_samples = 0;
e.stop();
if (app >= 0)
close(app);
if (dm > 0) {
kill(dm, SIGTERM);
waitpid(dm, nullptr, 0);
}
if (pty >= 0)
close(pty);
if (HasFailure()) {
std::lock_guard<std::mutex> lk(mu);
printf("--- the engine's log ---\n%s", logs.c_str());
}
}
/* (ATM1, the modem's own: the speaker on until CONNECT; ATM0 off) */
put(app, speaker ? "ATX3M1\r" : "ATX3M0\r");
CHECK(expect(app, "OK", 5), "%s: ATX3 OK", what);
put(app, "ATD1234\r");
CHECK(expect(app, "CONNECT[^\r]*", 90, &got), "%s: the engine: %s",
what, got.substr(got.find("CONNECT") == std::string::npos ? 0 :
got.find("CONNECT")).c_str());
/* the engine started: its end of the DTE in app */
void start(bool listen)
{
std::lock_guard<std::mutex> lk(mu);
heard = spk_samples;
if (speaker)
CHECK(spk_was_on && spk_level == 0 && heard > 8000,
"%s: the speaker on until CONNECT (%.1f s of the "
"line heard), off then", what, heard / 8000.0);
else
CHECK(!spk_was_on && heard == 0,
"%s: ATM0: the speaker stayed off", what);
app = e.start(config(listen), on_engine_status, on_engine_exit);
ASSERT_GE(app, 0) << "the engine started";
ASSERT_TRUE(e.running());
}
CHECK(expect(pty, "CONNECT", 30), "%s: dmodemd: CONNECT", what);
/* stop(): the engine ended, its exit the n-th, 0; the app's end closed */
void stop(int n)
{
e.stop();
EXPECT_TRUE(wait_exits(n, 5)) << "stop(): the engine ended";
EXPECT_EQ(exit_result, 0);
EXPECT_FALSE(e.running());
close(app);
app = -1;
}
/* a call from the engine to dmodemd and back: CONNECT, data both
ways, the status online, a hangup from the engine's side */
void call_out(bool speaker)
{
std::string got;
long heard;
{
std::lock_guard<std::mutex> lk(mu);
was_online = false;
spk_was_on = false;
spk_samples = 0;
}
/* (ATM1, the modem's own: the speaker on until CONNECT; ATM0 off) */
put(app, speaker ? "ATX3M1\r" : "ATX3M0\r");
ASSERT_TRUE(expect(app, "OK", 5)) << "ATX3";
put(app, "ATD1234\r");
ASSERT_TRUE(expect(app, "CONNECT[^\r]*", 90, &got))
<< "the engine's CONNECT";
printf(" the engine: %s\n",
got.substr(got.find("CONNECT")).c_str());
{
std::lock_guard<std::mutex> lk(mu);
heard = spk_samples;
if (speaker) {
EXPECT_TRUE(spk_was_on) << "ATM1: the speaker on until CONNECT";
EXPECT_EQ(spk_level, 0) << "the speaker off at CONNECT";
EXPECT_GT(heard, 8000) << "a second of the line heard at least";
} else {
EXPECT_FALSE(spk_was_on) << "ATM0: the speaker stayed off";
EXPECT_EQ(heard, 0);
}
}
ASSERT_TRUE(expect(pty, "CONNECT", 30)) << "dmodemd: CONNECT";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::string msg;
for (int i = 0; i < 40; i++)
msg += "data from the app " + std::to_string(i) + "; ";
put(app, msg);
EXPECT_TRUE(expect(pty, std::regex_replace(msg, std::regex("[;]"),
"\\;"), 20))
<< msg.size() << " octets the app wrote reached dmodemd";
put(pty, "an answer from dmodemd");
EXPECT_TRUE(expect(app, "an answer from dmodemd", 20))
<< "dmodemd's data reached the app";
{
std::lock_guard<std::mutex> lk(mu);
EXPECT_EQ(spk_samples, heard) << "nothing to the speaker in data mode";
EXPECT_TRUE(was_online) << "the status went online";
EXPECT_NE(online_tx, 0u);
EXPECT_NE(online_rx, 0u);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1200));
put(app, "+++");
ASSERT_TRUE(expect(app, "OK", 5)) << "+++";
put(app, "ATH\r");
EXPECT_TRUE(expect(app, "OK", 10)) << "ATH";
EXPECT_TRUE(expect(pty, "NO CARRIER", 20)) << "dmodemd: NO CARRIER";
EXPECT_TRUE(wait_idle(5)) << "the status idle and on hook again";
}
};
/* out, the speaker on until CONNECT (ATM1); a second start() refused
while it runs; SIP's lines through the log hook */
TEST_F(EngineTest, CallsOut)
{
ASSERT_NO_FATAL_FAILURE(start(false));
EXPECT_LT(e.start(config(false), on_engine_status, on_engine_exit), 0)
<< "a second start() refused while it runs";
ASSERT_NO_FATAL_FAILURE(call_out(true));
stop(1);
std::lock_guard<std::mutex> lk(mu);
EXPECT_NE(logs.find("sip: "), std::string::npos)
<< "SIP's lines came through the log hook";
}
/* stopped and started again (the SIP user agent made anew): out again,
the speaker off (ATM0) */
TEST_F(EngineTest, CallsOutAfterARestart)
{
ASSERT_NO_FATAL_FAILURE(start(false));
stop(1);
ASSERT_NO_FATAL_FAILURE(start(false));
ASSERT_NO_FATAL_FAILURE(call_out(false));
stop(2);
}
/* in, listening: RING, ATA, CONNECT, data; then the app closes its end
in the call: the engine ends by itself, the call hung up */
TEST_F(EngineTest, AnswersAndEndsWhenTheAppCloses)
{
ASSERT_NO_FATAL_FAILURE(start(true));
std::this_thread::sleep_for(std::chrono::milliseconds(500));
put(pty, "ATX3D1234\r");
ASSERT_TRUE(expect(app, "RING", 20)) << "RING at the app";
put(app, "ATA\r");
ASSERT_TRUE(expect(app, "CONNECT", 90)) << "CONNECT at the app";
ASSERT_TRUE(expect(pty, "CONNECT", 30)) << "dmodemd: CONNECT";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::string msg;
for (int i = 0; i < 40; i++)
msg += "data from the app " + std::to_string(i) + "; ";
put(app, msg);
CHECK(expect(pty, std::regex_replace(msg, std::regex("[;]"),
"\\;").c_str(), 20),
"%s: %zu octets the app wrote reached dmodemd", what, msg.size());
put(pty, "an answer from dmodemd");
CHECK(expect(app, "an answer from dmodemd", 20),
"%s: dmodemd's data reached the app", what);
{
std::lock_guard<std::mutex> lk(mu);
CHECK(spk_samples == heard,
"%s: nothing to the speaker in data mode", what);
}
{
std::lock_guard<std::mutex> lk(mu);
CHECK(was_online && online_tx && online_rx,
"%s: the status went online at %u/%u bit/s", what,
online_tx, online_rx);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1200));
put(app, "+++");
CHECK(expect(app, "OK", 5), "%s: +++ OK", what);
put(pty, "to the app");
EXPECT_TRUE(expect(app, "to the app", 20)) << "data to the app";
close(app);
app = -1;
EXPECT_TRUE(wait_exits(1, 10)) << "the engine ended by itself";
EXPECT_EQ(exit_result, 0);
EXPECT_FALSE(e.running());
EXPECT_TRUE(expect(pty, "NO CARRIER", 20)) << "dmodemd: NO CARRIER";
}
/* hung up while the call rings (dmodemd not answering): the modem back
at once, the status idle */
TEST_F(EngineTest, HangsUpWhileRinging)
{
put(pty, "ATS0=0\r");
ASSERT_TRUE(expect(pty, "OK", 5)) << "dmodemd: ATS0=0";
ASSERT_NO_FATAL_FAILURE(start(false));
put(app, "ATX3D1234\r");
ASSERT_TRUE(expect(pty, "RING", 30)) << "dmodemd rings";
auto t0 = std::chrono::steady_clock::now();
put(app, "ATH\r");
CHECK(expect(app, "OK", 10), "%s: ATH OK", what);
CHECK(expect(pty, "NO CARRIER", 20), "%s: dmodemd: NO CARRIER", what);
std::unique_lock<std::mutex> lk(mu);
CHECK(cv.wait_for(lk, std::chrono::seconds(5),
[] { return last.link == Status::IDLE &&
!last.offhook; }),
"%s: the status idle and on hook again", what);
EXPECT_TRUE(expect(app, "(OK|NO CARRIER)\r\n", 30)) << "ATH answered";
double secs = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t0).count();
EXPECT_LT(secs, 3.0) << "the modem back at once";
EXPECT_TRUE(wait_idle(3)) << "the status idle and on hook";
}
} // namespace
/* the engine against the dmodemd at argv[1], call by call (see above): 1 if any check failed */
/* the tests (gtest's flags taken out first), dmodemd at argv[1] if given */
int main(int argc, char *argv[])
{
int pty = -1, app;
pid_t dm;
if (argc != 2) {
fprintf(stderr, "usage: engine_test <dmodemd>\n");
testing::InitGoogleTest(&argc, argv);
if (argc > 2) {
fprintf(stderr, "usage: engine_test [gtest flags] [dmodemd]\n");
return 2;
}
if (argc == 2)
dmodemd_path = argv[1];
signal(SIGPIPE, SIG_IGN);
Engine &e = Engine::instance();
/* ENGINE_TEST_LOG: the engine's log as it comes, too */
static bool live = getenv("ENGINE_TEST_LOG") != nullptr;
e.set_log([](const char *line) {
std::lock_guard<std::mutex> lk(mu);
@@ -293,7 +432,6 @@ int main(int argc, char *argv[])
if (live)
printf(" | %s", line);
});
e.set_speaker(
[](int level) {
std::lock_guard<std::mutex> lk(mu);
@@ -305,91 +443,5 @@ int main(int argc, char *argv[])
std::lock_guard<std::mutex> lk(mu);
spk_samples += n;
});
dm = start_dmodemd(argv[1], &pty);
CHECK(dm > 0 && pty >= 0, "dmodemd started");
if (dm <= 0)
return 1;
/* it answers the engine's calls itself */
put(pty, "ATS0=1\r");
expect(pty, "OK", 5);
/* 1: out */
app = e.start(config(false), on_engine_status, on_engine_exit);
CHECK(app >= 0 && e.running(), "the engine started");
CHECK(e.start(config(false), on_engine_status, on_engine_exit) < 0,
"a second start() refused while it runs");
call_out(app, pty, "call 1", true);
e.stop();
CHECK(wait_exits(1, 5) && exit_result == 0 && !e.running(),
"stop(): the engine ended (%d)", exit_result);
close(app);
/* 2: started again, out again */
app = e.start(config(false), on_engine_status, on_engine_exit);
CHECK(app >= 0, "the engine started again");
call_out(app, pty, "call 2", false);
e.stop();
CHECK(wait_exits(2, 5) && exit_result == 0, "stop() again");
close(app);
/* 3: in */
app = e.start(config(true), on_engine_status, on_engine_exit);
CHECK(app >= 0, "the engine started, listening");
std::this_thread::sleep_for(std::chrono::milliseconds(500));
put(pty, "ATX3D1234\r");
CHECK(expect(app, "RING", 20), "call 3: RING at the app");
put(app, "ATA\r");
CHECK(expect(app, "CONNECT", 90), "call 3: CONNECT at the app");
CHECK(expect(pty, "CONNECT", 30), "call 3: dmodemd: CONNECT");
std::this_thread::sleep_for(std::chrono::seconds(1));
put(pty, "to the app");
CHECK(expect(app, "to the app", 20), "call 3: data to the app");
/* 4: the app closes its end in the call */
close(app);
CHECK(wait_exits(3, 10) && exit_result == 0 && !e.running(),
"the app's end closed: the engine ended by itself (%d)",
exit_result);
CHECK(expect(pty, "NO CARRIER", 20), "call 3: dmodemd: NO CARRIER");
e.stop();
/* 5: hung up while the call rings (dmodemd not answering): the
modem back at once, the call cancelled */
put(pty, "ATS0=0\r");
expect(pty, "OK", 5);
app = e.start(config(false), on_engine_status, on_engine_exit);
CHECK(app >= 0, "the engine started for call 5");
put(app, "ATX3D1234\r");
CHECK(expect(pty, "RING", 30), "call 5: dmodemd rings");
{
auto t0 = std::chrono::steady_clock::now();
std::string got;
put(app, "ATH\r");
bool back = expect(app, "(OK|NO CARRIER)\r\n", 30, &got);
double s5 = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t0).count();
CHECK(back && s5 < 3, "call 5: hung up while ringing: the modem "
"back in %.1f s", s5);
std::unique_lock<std::mutex> lk(mu);
CHECK(cv.wait_for(lk, std::chrono::seconds(3),
[] { return last.link == Status::IDLE &&
!last.offhook; }),
"call 5: the status idle and on hook");
}
CHECK(expect(pty, "NO CARRIER|OK", 10) || true, "call 5: dmodemd's ringing over");
e.stop();
close(app);
{
std::lock_guard<std::mutex> lk(mu);
CHECK(logs.find("sip: ") != std::string::npos,
"SIP's lines came through the log hook");
if (failures)
printf("--- the engine's log ---\n%s", logs.c_str());
}
kill(dm, SIGTERM);
waitpid(dm, nullptr, 0);
printf(failures ? "FAIL: %d\n" : "PASS\n", failures);
return failures ? 1 : 0;
return RUN_ALL_TESTS();
}
@@ -2,10 +2,12 @@
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.io
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.selects.onTimeout
import kotlinx.coroutines.selects.select
import kotlin.time.TimeSource
/**
@@ -84,11 +86,21 @@ class ByteQueue {
ch.trySend(b)
}
/** the next chunk, waiting up to [ms]; null if none came (the reader's thread) */
/**
* the next chunk, waiting up to [ms]; null if none came (the reader's
* thread). (A select, not receive() in withTimeoutOrNull: a chunk sent
* just as that timed out was taken by the cancelled receive and lost.)
*/
@OptIn(ExperimentalCoroutinesApi::class)
fun poll(ms: Long): ByteArray? {
poll()?.let { return it }
if (ms <= 0) return null
return runBlocking { withTimeoutOrNull(ms) { ch.receive() } }
return runBlocking {
select {
ch.onReceive { it }
onTimeout(ms) { null }
}
}
}
/** the next chunk if one waits, else null */
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.io
import kotlin.concurrent.Volatile
import kotlin.test.Test
import kotlin.test.assertEquals
/** A ByteQueue between two threads loses nothing, whatever its reads' timeouts. */
class ByteQueueTest {
private class Flag { @Volatile var on = false }
/** chunks put while the reader's short waits keep timing out all come, in order */
@Test
fun nothingLostToATimeout() {
val q = ByteQueue()
val n = 3000
val done = Flag()
background("writer") {
for (i in 0 until n) {
q.put(byteArrayOf((i shr 8).toByte(), i.toByte()))
// (now and then just as the reader's wait runs out)
if (i % 3 == 0) sleepMs(1)
}
done.on = true
}
var next = 0
val end = monotonicMs() + 30_000
while (next < n && monotonicMs() < end) {
val b = q.poll(1) ?: continue
val i = ((b[0].toInt() and 0xff) shl 8) or (b[1].toInt() and 0xff)
assertEquals(next, i, "chunk $next")
next++
}
assertEquals(n, next)
}
}
@@ -34,11 +34,11 @@ class PeerLoopbackTest {
/** a pipe's end: reads [inw], writes [outw] */
private class End(private val inw: Way, private val outw: Way, override val name: String) : Duplex {
override val input = object : Source {
/** the next of what came the other way, into [b] (waited for): how much, -1 once closed */
/** the next of what came the other way, into [b] (waited for): how much, -1 once closed and read to its end */
override fun read(b: ByteArray, off: Int, len: Int): Int {
while (inw.at >= inw.cur.size) {
if (inw.closed) return -1
inw.cur = inw.q.poll(50) ?: continue
// (what was written before the close still comes, as on a socket: a DENIED, say)
inw.cur = inw.q.poll() ?: if (inw.closed) return -1 else inw.q.poll(50) ?: continue
inw.at = 0
}
val n = minOf(len, inw.cur.size - inw.at)