Guides

Testing

Test serial code without hardware: fake ports, a fake AT modem, the plugin through IPC.

The serialplugin-testing crate has the fake devices the plugin's own tests use: an in-memory serial port, an AT modem with a 27.010 multiplexer, TCP and PTY peers. Nothing needs hardware, and no test depends on a delay.

[dev-dependencies]
serialplugin-testing = "0.2"  # features = ["tokio"] for TokioClock
# For the plugin through IPC:
tauri = { version = "2", features = ["test"] }
serde_json = "1"

Your Rust code

insert_port manages any serialport::SerialPort as if open had opened it, so the code under test runs on a fake device:

use serialplugin_core::SerialManager;
use serialplugin_testing::{FakeDevice, Modem};

let modem = Modem::new().reply("AT+CSQ", &["+CSQ: 17,99"]);
let log = modem.log();
let device = FakeDevice::with_modem(modem);
let serial = SerialManager::new();
serial.insert_port("modem".into(), Box::new(device.port())).unwrap();

let reply = serial.at("modem".into(), "AT+CSQ".into(), None).unwrap();
assert_eq!(reply.solicited_body, ["+CSQ: 17,99"]);
assert_eq!(log.commands()[0].line, "AT+CSQ");

serial.close("modem".into()).unwrap();
device.wait_closed();

(In a Tauri app the crate is tauri_plugin_serialplugin::serialplugin_core.)

The plugin through IPC

A mock Tauri app with the plugin, its commands called by name as the webview does. The fake port goes in through the plugin's managed SerialPort state. mock_context allows no plugin command, so the test allows the one it calls:

use serialplugin_testing::{FakeDevice, Modem};
use std::collections::BTreeMap;
use tauri::ipc::{CallbackFn, InvokeBody};
use tauri::test::{get_ipc_response, mock_builder, mock_context, noop_assets, INVOKE_KEY};
use tauri::utils::acl::resolved::{Resolved, ResolvedCommand};
use tauri::Manager;
use tauri_plugin_serialplugin::api::SerialPort;

let main_window = ResolvedCommand {
    windows: vec!["main".parse().unwrap()],
    ..Default::default()
};
let mut context = mock_context(noop_assets());
*context.runtime_authority_mut() = tauri::runtime_authority!(
    BTreeMap::new(),
    Resolved {
        allowed_commands: BTreeMap::from([("plugin:serialplugin|at".into(), vec![main_window])]),
        ..Default::default()
    }
);
let app = mock_builder()
    .plugin(tauri_plugin_serialplugin::init())
    .build(context)
    .unwrap();
let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
    .build()
    .unwrap();

let device = FakeDevice::with_modem(Modem::new());
app.state::<SerialPort<tauri::test::MockRuntime>>()
    .insert_port("modem".into(), Box::new(device.port()))
    .unwrap();

let url = if cfg!(windows) { "http://tauri.localhost" } else { "tauri://localhost" };
let request = tauri::webview::InvokeRequest {
    cmd: "plugin:serialplugin|at".into(),
    callback: CallbackFn(0),
    error: CallbackFn(1),
    url: url.parse().unwrap(),
    body: InvokeBody::Json(serde_json::json!({ "path": "modem", "command": "AT" })),
    headers: Default::default(),
    invoke_key: INVOKE_KEY.into(),
};
let reply = get_ipc_response(&webview, request)
    .unwrap()
    .deserialize::<serde_json::Value>()
    .unwrap();
assert_eq!(reply["status"], "ok");

To test with your app's own capabilities, build it with tauri::generate_context!() instead of mock_context (in the app's crate). The plugin's tests resolve the plugin's permission files.

Faults

To testUse
unplug, and plugging in againdevice.fail_reads(ErrorKind::BrokenPipe), device.eof(); device.recover()
a device that takes no bytesdevice.stall_writes(true), device.fail_writes(kind)
a call that must not blockdevice.hold_reads(true) / hold_writes(true), device.wait_held(1)
no answer, an errorModem::silent("AT…"), Modem::fails("AT…", "+CME ERROR: 10")
a URC, split readsdevice.send(b"…") in as many pieces as you like
a modem that does not answerdevice.faults(Faults::default().silent(true))
a burst of lines after every answerFaults::default().burst(b"\r\n+CREG: 1\r\n", 50)
answers cut into reads of N bytesFaults::default().chunk(N)
late answers, a line later onFaults::default().delay(d), device.send_after(d, b"…")
time that waits for nothingdevice.clock(Arc::new(ManualClock::new())) and advance; TokioClock (feature tokio) under #[tokio::test(start_paused = true)]
every write as an eventdevice.subscribe_writes() (subscribe_writes_async() with tokio)
modem lines and settingsdevice.set_lines(Lines::default().cts(false)), device.calls()
"the host has handled it"device.wait_handled() (read is not handled yet: wait_read)

Multiplexer

use serialplugin_core::events::{SerialEvent, WatchOptions};
use serialplugin_core::SerialManager;
use serialplugin_testing::{mux, FakeDevice, Modem, MuxOptions};
use std::sync::{mpsc, Arc};

let modem = Modem::new().mux(MuxOptions::default().refuse([2]));
let log = modem.log();
let device = FakeDevice::with_modem(modem);
let serial = SerialManager::new();
serial.insert_port("modem".into(), Box::new(device.port())).unwrap();

serial.enable_mux("modem".into(), "AT+CMUX=0".into(), 1000).unwrap();
let channel = serial.open_mux_channel("modem".into(), 1).unwrap();
serial.at(channel.clone(), "AT".into(), None).unwrap();
assert!(serial.open_mux_channel("modem".into(), 2).is_err());

// The modem closes the channel: its watch ends, and the host acknowledges.
let (tx, events) = mpsc::channel();
let sink = Arc::new(move |event| tx.send(event).is_ok());
serial.watch(channel.clone(), WatchOptions::default(), sink).unwrap();
device.send(&mux::frame(1, false, mux::DISC | mux::PF, &[]));
let Ok(SerialEvent::Disconnect { path, .. }) = events.recv() else {
    panic!("no Disconnect");
};
assert_eq!(path, channel);
log.wait_frame("the host's UA", |f| f.dlci == 1 && f.kind == mux::UA);
serial.close("modem".into()).unwrap();

The modem keeps the state of each channel: one that was not opened (or was refused, or closed) carries no data. MuxOptions also ignores channels (deaf), loses the first frames and leaves CLD unanswered, as real modems do.

A real file descriptor

peer::pty() (unix) and peer::tcp_listener() + peer::accept() give both ends of a PTY or a tcp:// bridge; peer::serve(io, modem) runs a Modem on the device end until its Server is dropped.