A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(desktop-native): drop app-store, gateway and shared tests
Hampus2bc939e16ee6
diff --git a/fluxer_desktop/native/app-store/Cargo.lock b/fluxer_desktop/native/app-store/Cargo.lockindex e93aa3c49..271aabe79 100644--- a/fluxer_desktop/native/app-store/Cargo.lock+++ b/fluxer_desktop/native/app-store/Cargo.lock@@ -45,16 +45,6 @@ version = "1.0.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"-[[package]]-name = "errno"-version = "0.3.14"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"-dependencies = [- "libc",- "windows-sys",-]-[[package]]name = "fallible-iterator"version = "0.3.0"@@ -67,12 +57,6 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"-[[package]]-name = "fastrand"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"-[[package]]name = "find-msvc-tools"version = "0.1.14"@@ -89,7 +73,6 @@ dependencies = ["rusqlite","serde","serde_json",- "tempfile",][[package]]@@ -186,17 +169,6 @@ dependencies = ["slab",]-[[package]]-name = "getrandom"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"-dependencies = [- "cfg-if",- "libc",- "r-efi",-]-[[package]]name = "hashbrown"version = "0.16.1"@@ -267,12 +239,6 @@ dependencies = ["vcpkg",]-[[package]]-name = "linux-raw-sys"-version = "0.12.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"-[[package]]name = "memchr"version = "2.8.3"@@ -379,12 +345,6 @@ dependencies = ["proc-macro2",]-[[package]]-name = "r-efi"-version = "6.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"-[[package]]name = "rsqlite-vfs"version = "0.1.1"@@ -416,19 +376,6 @@ version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"-[[package]]-name = "rustix"-version = "1.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"-dependencies = [- "bitflags",- "errno",- "libc",- "linux-raw-sys",- "windows-sys",-]-[[package]]name = "rustversion"version = "1.0.23"@@ -536,19 +483,6 @@ dependencies = ["unicode-ident",]-[[package]]-name = "tempfile"-version = "3.27.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"-dependencies = [- "fastrand",- "getrandom",- "once_cell",- "rustix",- "windows-sys",-]-[[package]]name = "thiserror"version = "2.0.21"@@ -638,15 +572,6 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"-[[package]]-name = "windows-sys"-version = "0.61.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"-dependencies = [- "windows-link",-]-[[package]]name = "zmij"version = "1.0.23"diff --git a/fluxer_desktop/native/app-store/Cargo.toml b/fluxer_desktop/native/app-store/Cargo.tomlindex 35b7e3032..3ff688fa7 100644--- a/fluxer_desktop/native/app-store/Cargo.toml+++ b/fluxer_desktop/native/app-store/Cargo.toml@@ -20,6 +20,3 @@ serde_json = {version = "1.0", features = ["raw_value"]}[build-dependencies]napi-build = "2.4.3"--[dev-dependencies]-tempfile = "3.27"diff --git a/fluxer_desktop/native/app-store/src/accounts.rs b/fluxer_desktop/native/app-store/src/accounts.rsindex 92417ec89..d88857b3b 100644--- a/fluxer_desktop/native/app-store/src/accounts.rs+++ b/fluxer_desktop/native/app-store/src/accounts.rs@@ -307,279 +307,3 @@ fn stored_bytes() -> Result<Option<i64>, StoreError> {Ok(conn.query_row(sql, args, |row| row.get(0)).optional()?)}--#[cfg(test)]-mod tests {- use super::*;- use crate::model::{Store, temporary_store_path};- use crate::scoped_storage::{ScopedEntry, entry as scoped_entry, scope_entries, set_entry};-- fn entry(storage_key: &str, record: &str) -> AccountEntry {- AccountEntry {- storage_key: storage_key.to_owned(),- record: RawValue::from_string(record.to_owned()).expect("valid JSON"),- }- }-- #[test]- fn a_record_with_unknown_keys_round_trips_byte_exactly() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- let written = r#"{"userId":"1","instance":{"apiEndpoint":"https://a.example/api","futureKey":[1,2]},"unknownTopLevel":{"nested":true},"lastActive":7}"#;-- upsert_account(store.connection(), &entry("a.example::1", written))- .expect("the account is stored");- let read = account(store.connection(), "a.example::1")- .expect("the account is readable")- .expect("the account is present");-- assert_eq!(- read.record.get(),- written,- "a record written by a newer renderer must survive an older shell byte-exactly"- );- assert_eq!(read.storage_key, "a.example::1");- }-- #[test]- fn accounts_are_ordered_by_last_active_then_storage_key() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- for (key, last_active) in [("b::2", 5.0), ("a::1", 9.0), ("a::3", 5.0)] {- upsert_account(- store.connection(),- &entry(- key,- &format!(r#"{{"userId":"u","lastActive":{last_active}}}"#),- ),- )- .expect("the account is stored");- }-- let keys = all_accounts(store.connection())- .expect("the accounts are readable")- .into_iter()- .map(|account| account.storage_key)- .collect::<Vec<_>>();- assert_eq!(keys, vec!["a::1", "a::3", "b::2"]);- }-- #[test]- fn a_record_the_addon_cannot_use_is_still_stored() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- let deployed_shape =- r#"{"userId":"1","instance":{"gifProvider":"tenor","apiCodeVersion":9}}"#;-- upsert_account(store.connection(), &entry("legacy::1", deployed_shape))- .expect("a record with an unusable instance is still stored");- let mut budget = account_budget(store.connection());- let write = write_account(- store.connection(),- budget.as_mut().expect("the budget is readable"),- &entry("legacy::1", deployed_shape),- )- .expect("the write succeeds");- assert!(matches!(- write,- AccountWrite::Written {- instance_usable: false- }- ));- assert_eq!(- account(store.connection(), "legacy::1")- .expect("the account is readable")- .expect("the account is present")- .record- .get(),- deployed_shape- );- }-- #[test]- fn a_storage_key_crosses_the_boundary_opaquely() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- let opaque = "HTTPS://Mixed.Case.Example:8443/api::user::12345";-- upsert_account(store.connection(), &entry(opaque, r#"{"userId":"12345"}"#))- .expect("the account is stored");- assert!(- account(store.connection(), opaque)- .expect("the account is readable")- .is_some(),- "the addon must not normalise the storage key it was given"- );- }-- #[test]- fn a_record_that_is_not_a_json_object_is_refused_rather_than_stored() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- assert!(upsert_account(store.connection(), &entry("a::1", "[1,2,3]")).is_err());- assert!(- all_accounts(store.connection())- .expect("the accounts are readable")- .is_empty()- );- }-- #[test]- fn deleting_an_account_takes_its_scoped_storage_with_it() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- for key in ["a::1", "a::2"] {- upsert_account(store.connection(), &entry(key, r#"{"userId":"1"}"#))- .expect("the account is stored");- }- for scope in ["a::1", "a::2", "global"] {- set_entry(- store.connection(),- &ScopedEntry {- store: "app".to_owned(),- scope: scope.to_owned(),- key: "theme".to_owned(),- value: "\"dark\"".to_owned(),- updated_at: 1.0,- },- )- .expect("the entry is stored");- }-- delete_account(store.connection(), "a::1").expect("the account is deleted");-- assert!(- account(store.connection(), "a::1")- .expect("the account is readable")- .is_none()- );- assert!(- scope_entries(store.connection(), "app", "a::1")- .expect("entries are readable")- .is_empty(),- "a deleted account must not leave its scoped storage behind"- );- assert!(- scoped_entry(store.connection(), "app", "a::2", "theme")- .expect("the entry is readable")- .is_some()- );- assert!(- scoped_entry(store.connection(), "app", "global", "theme")- .expect("the entry is readable")- .is_some()- );- }-- #[test]- fn a_compare_and_swap_lands_once_and_refuses_the_stale_retry() {- let (_dir, path) = temporary_store_path();- let mut store = Store::open(path, None).expect("a fresh store opens");- let first = r#"{"userId":"1","token":"first"}"#;- let second = r#"{"userId":"1","token":"second"}"#;- let third = r#"{"userId":"1","token":"third"}"#;- upsert_account(store.connection(), &entry("a.example::1", first))- .expect("the account is stored");-- assert!(- compare_and_swap_account(- store.connection_mut(),- &AccountCompareAndSwap {- expected: entry("a.example::1", first),- replacement: entry("a.example::1", second),- },- )- .expect("the swap runs")- );- assert_eq!(- account(store.connection(), "a.example::1")- .expect("the account is readable")- .expect("the account is present")- .record- .get(),- second- );-- assert!(- !compare_and_swap_account(- store.connection_mut(),- &AccountCompareAndSwap {- expected: entry("a.example::1", first),- replacement: entry("a.example::1", third),- },- )- .expect("the swap runs"),- "a swap holding a record the store has already moved past must report that it did not land"- );- assert_eq!(- account(store.connection(), "a.example::1")- .expect("the account is readable")- .expect("the account is present")- .record- .get(),- second,- "a refused swap must leave the newer record untouched"- );- }-- #[test]- fn a_compare_and_swap_across_two_storage_keys_is_refused() {- let (_dir, path) = temporary_store_path();- let mut store = Store::open(path, None).expect("a fresh store opens");- let record = r#"{"userId":"1"}"#;- upsert_account(store.connection(), &entry("a.example::1", record))- .expect("the account is stored");-- let outcome = compare_and_swap_account(- store.connection_mut(),- &AccountCompareAndSwap {- expected: entry("a.example::1", record),- replacement: entry("a.example::2", record),- },- );-- assert!(matches!(outcome, Err(StoreError::Refused(_))));- assert!(- account(store.connection(), "a.example::2")- .expect("the accounts are readable")- .is_none()- );- }-- #[test]- fn known_instances_are_stored_opaquely_and_ordered_by_last_used() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- for (key, last_used) in [("beta.example", 1.0), ("alpha.example", 4.0)] {- upsert_known_instance(- store.connection(),- &KnownInstanceEntry {- key: key.to_owned(),- record: RawValue::from_string(format!(- r#"{{"lastUsed":{last_used},"displayName":"{key}"}}"#- ))- .expect("valid JSON"),- },- )- .expect("the known instance is stored");- }-- let stored = all_known_instances(store.connection()).expect("the instances are readable");- assert_eq!(- stored- .iter()- .map(|row| row.key.as_str())- .collect::<Vec<_>>(),- vec!["alpha.example", "beta.example"]- );-- delete_known_instance(store.connection(), "alpha.example")- .expect("the instance is deleted");- assert_eq!(- all_known_instances(store.connection())- .expect("the instances are readable")- .len(),- 1- );- }-}diff --git a/fluxer_desktop/native/app-store/src/import.rs b/fluxer_desktop/native/app-store/src/import.rsindex fa6b0c175..8b51b9afd 100644--- a/fluxer_desktop/native/app-store/src/import.rs+++ b/fluxer_desktop/native/app-store/src/import.rs@@ -173,307 +173,3 @@ fn refused(reason: &'static str) -> PruneReport {refused_reason: Some(reason),}}--#[cfg(test)]-mod tests {- use super::*;- use crate::accounts::{account, all_accounts};- use crate::model::{MAX_SCOPED_VALUE_BYTES, temporary_store_path};- use crate::scoped_storage::{entry, scope_entries};- use serde_json::value::RawValue;-- fn open() -> (tempfile::TempDir, Store) {- let (dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- (dir, store)- }-- fn account_entry(storage_key: &str, record: &str) -> AccountEntry {- AccountEntry {- storage_key: storage_key.to_owned(),- record: RawValue::from_string(record.to_owned()).expect("valid JSON"),- }- }-- fn scoped_entry(scope: &str, key: &str, value: &str) -> ScopedEntry {- ScopedEntry {- store: "app".to_owned(),- scope: scope.to_owned(),- key: key.to_owned(),- value: value.to_owned(),- updated_at: 1.0,- }- }-- #[test]- fn importing_accounts_commits_the_records_and_the_phase_marker_together() {- let (_dir, mut store) = open();- let request = AccountImport {- records: vec![- account_entry(- "a::1",- r#"{"userId":"1","lastActive":2,"instance":{"apiEndpoint":"https://a/api"}}"#,- ),- account_entry("a::2", r#"{"userId":"2","lastActive":1}"#),- ],- marker: Some(Marker {- key: "legacy_import.v1".to_owned(),- value: r#"{"phase":"entries"}"#.to_owned(),- }),- };-- let report = import_accounts(&mut store, request).expect("the import commits");- assert_eq!(report.imported, 2);- assert!(report.skipped.is_empty());- assert_eq!(report.unusable_instances, vec!["a::2".to_owned()]);- assert_eq!(- store- .metadata("legacy_import.v1")- .expect("metadata is readable"),- Some(r#"{"phase":"entries"}"#.to_owned())- );-- let again = import_accounts(- &mut store,- AccountImport {- records: vec![account_entry("a::1", r#"{"userId":"1","lastActive":9}"#)],- marker: None,- },- )- .expect("a repeated import commits");- assert_eq!(again.imported, 1);- assert_eq!(- all_accounts(store.connection())- .expect("the accounts are readable")- .len(),- 2,- "re-importing a record must replace it, never duplicate it"- );- }-- #[test]- fn importing_accounts_skips_and_reports_a_bad_record_without_losing_the_batch() {- let (_dir, mut store) = open();- let report = import_accounts(- &mut store,- AccountImport {- records: vec![- account_entry("a::1", r#"{"userId":"1"}"#),- account_entry("", r#"{"userId":"2"}"#),- account_entry("a::3", r#""not-an-object""#),- account_entry("a::4", r#"{"userId":"4"}"#),- ],- marker: None,- },- )- .expect("the import commits");-- assert_eq!(report.imported, 2);- assert_eq!(- report- .skipped- .iter()- .map(|skipped| skipped.key.as_str())- .collect::<Vec<_>>(),- vec!["", "a::3"]- );- assert!(- account(store.connection(), "a::4")- .expect("the account is readable")- .is_some()- );- }-- #[test]- fn importing_entries_skips_and_reports_a_bad_record_and_commits_the_rest() {- let (_dir, mut store) = open();- let oversized = "x".repeat(MAX_SCOPED_VALUE_BYTES + 1);- let report = import_entries(- &mut store,- EntryImport {- entries: vec![- scoped_entry("a::1", "theme", "dark"),- scoped_entry("a::1", "", "no key"),- scoped_entry("a::1", "huge", &oversized),- scoped_entry("a::1", "zoom", "1.25"),- ],- marker: Some(Marker {- key: "legacy_import.v1".to_owned(),- value: r#"{"phase":"session"}"#.to_owned(),- }),- },- )- .expect("the import commits");-- assert_eq!(report.imported, 2);- assert_eq!(report.skipped.len(), 2);- assert!(report.skipped[0].reason.contains("key is unusable"));- assert!(report.skipped[1].reason.contains("too large"));- assert_eq!(- scope_entries(store.connection(), "app", "a::1")- .expect("entries are readable")- .len(),- 2,- "one oversized entry must not abort the batch"- );- assert_eq!(- store- .metadata("legacy_import.v1")- .expect("metadata is readable"),- Some(r#"{"phase":"session"}"#.to_owned())- );- }-- #[test]- fn a_failure_inside_a_phase_rolls_back_the_data_and_the_marker_together() {- let (_dir, mut store) = open();- store- .set_metadata("legacy_import.v1", r#"{"phase":"accounts"}"#)- .expect("metadata is writable");- store- .connection()- .execute_batch("DROP TABLE accounts")- .expect("the table is dropped");-- let failure = import_accounts(- &mut store,- AccountImport {- records: vec![account_entry("a::1", r#"{"userId":"1"}"#)],- marker: Some(Marker {- key: "legacy_import.v1".to_owned(),- value: r#"{"phase":"entries"}"#.to_owned(),- }),- },- );-- assert!(failure.is_err());- assert_eq!(- store- .metadata("legacy_import.v1")- .expect("metadata is readable"),- Some(r#"{"phase":"accounts"}"#.to_owned()),- "an interrupted phase must re-run rather than be marked complete"- );- }-- #[test]- fn pruning_refuses_a_non_authoritative_or_transiently_empty_list() {- let (_dir, mut store) = open();- import_accounts(- &mut store,- AccountImport {- records: vec![account_entry("a::1", r#"{"userId":"1"}"#)],- marker: None,- },- )- .expect("the import commits");-- let not_authoritative = prune(- &mut store,- PruneRequest {- known_storage_keys: vec!["a::1".to_owned()],- list_is_authoritative: false,- },- )- .expect("prune completes");- assert_eq!(- not_authoritative.refused_reason,- Some("the known account list was not authoritative")- );-- let transiently_empty = prune(- &mut store,- PruneRequest {- known_storage_keys: Vec::new(),- list_is_authoritative: true,- },- )- .expect("prune completes");- assert_eq!(- transiently_empty.refused_reason,- Some("the known account list was empty while the store holds accounts")- );- assert_eq!(- all_accounts(store.connection())- .expect("the accounts are readable")- .len(),- 1,- "a refused prune must delete nothing"- );- }-- #[test]- fn pruning_an_authoritative_list_removes_orphans_and_their_scoped_rows() {- let (_dir, mut store) = open();- import_accounts(- &mut store,- AccountImport {- records: vec![- account_entry("a::1", r#"{"userId":"1"}"#),- account_entry("a::2", r#"{"userId":"2"}"#),- ],- marker: None,- },- )- .expect("the import commits");- import_entries(- &mut store,- EntryImport {- entries: vec![- scoped_entry("a::1", "theme", "dark"),- scoped_entry("a::2", "theme", "light"),- scoped_entry("global", "theme", "system"),- ],- marker: None,- },- )- .expect("the import commits");-- let report = prune(- &mut store,- PruneRequest {- known_storage_keys: vec!["a::1".to_owned()],- list_is_authoritative: true,- },- )- .expect("prune completes");-- assert_eq!(report.pruned, vec!["a::2".to_owned()]);- assert_eq!(report.refused_reason, None);- assert!(- account(store.connection(), "a::2")- .expect("the account is readable")- .is_none()- );- assert!(- scope_entries(store.connection(), "app", "a::2")- .expect("entries are readable")- .is_empty()- );- assert!(- entry(store.connection(), "app", "global", "theme")- .expect("the entry is readable")- .is_some()- );- assert!(- entry(store.connection(), "app", "a::1", "theme")- .expect("the entry is readable")- .is_some()- );- }-- #[test]- fn pruning_an_empty_store_against_an_empty_list_is_allowed() {- let (_dir, mut store) = open();- let report = prune(- &mut store,- PruneRequest {- known_storage_keys: Vec::new(),- list_is_authoritative: true,- },- )- .expect("prune completes");- assert_eq!(report.refused_reason, None);- assert!(report.pruned.is_empty());- }-}diff --git a/fluxer_desktop/native/app-store/src/model.rs b/fluxer_desktop/native/app-store/src/model.rsindex 957a878ee..9018bd17a 100644--- a/fluxer_desktop/native/app-store/src/model.rs+++ b/fluxer_desktop/native/app-store/src/model.rs@@ -680,484 +680,3 @@ pub fn require_lookup_key(value: &str, what: &'static str) -> Result<(), StoreErNone => Ok(()),}}--#[cfg(test)]-pub(crate) fn temporary_store_path() -> (tempfile::TempDir, PathBuf) {- let dir = tempfile::TempDir::new().expect("a temporary directory");- let path = dir.path().join("desktop-app-store.sqlite3");- (dir, path)-}--#[cfg(test)]-mod tests {- use super::*;-- fn store_dir() -> (tempfile::TempDir, PathBuf) {- temporary_store_path()- }-- fn table_exists(conn: &Connection, name: &str) -> bool {- conn.query_row(- "SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?1",- params![name],- |row| row.get::<_, i64>(0),- )- .optional()- .expect("the schema is readable")- .is_some()- }-- fn user_version(conn: &Connection) -> i32 {- conn.pragma_query_value(None, "user_version", |row| row.get(0))- .expect("user_version is readable")- }-- #[test]- fn a_fresh_store_applies_the_baseline_and_reopens_unchanged() {- let (_dir, path) = store_dir();- let store = Store::open(path.clone(), None).expect("a fresh store opens");- assert_eq!(store.outcome().schema_version, SCHEMA_VERSION);- assert_eq!(store.outcome().previous_schema_version, 0);- assert_eq!(store.outcome().applied_migrations, 0);- assert!(store.outcome().quarantined_path.is_none());- assert_eq!(- store- .metadata(METADATA_SCHEMA_VERSION)- .expect("metadata is readable")- .as_deref(),- Some("1")- );- for table in TABLES {- assert!(- table_exists(store.connection(), table.name),- "{}",- table.name- );- }- let journal: String = store- .connection()- .query_row("PRAGMA journal_mode", [], |row| row.get(0))- .expect("the journal mode is readable");- assert_eq!(journal, "delete", "the store must not use WAL");- let foreign_keys: i64 = store- .connection()- .query_row("PRAGMA foreign_keys", [], |row| row.get(0))- .expect("the foreign key pragma is readable");- assert_eq!(foreign_keys, 1);- drop(store);-- let reopened = Store::open(path, None).expect("the store reopens");- assert_eq!(reopened.outcome().previous_schema_version, SCHEMA_VERSION);- assert_eq!(reopened.outcome().applied_migrations, 0);- assert!(reopened.outcome().quarantined_path.is_none());- }-- #[test]- fn the_ladder_runs_one_step_at_a_time_and_bumps_the_version_per_step() {- let (_dir, path) = store_dir();- drop(Store::open(path.clone(), None).expect("a fresh store opens"));- let mut conn = Connection::open(&path).expect("the store reopens directly");-- const LADDER: &[Migration] = &[- Migration {- from: 1,- to: 2,- statements: &["CREATE TABLE step_two (id INTEGER PRIMARY KEY)"],- },- Migration {- from: 2,- to: 3,- statements: &["CREATE TABLE step_three (id INTEGER PRIMARY KEY)"],- },- ];- assert_eq!(- run_ladder(&mut conn, 1, LADDER, 2).expect("the first step applies"),- 1- );- assert_eq!(user_version(&conn), 2);- assert!(table_exists(&conn, "step_two"));- assert!(!table_exists(&conn, "step_three"));-- assert_eq!(- run_ladder(&mut conn, 2, LADDER, 3).expect("the second step applies"),- 1- );- assert_eq!(user_version(&conn), 3);- assert!(table_exists(&conn, "step_three"));-- const BROKEN: &[Migration] = &[Migration {- from: 3,- to: 4,- statements: &[- "CREATE TABLE step_four (id INTEGER PRIMARY KEY)",- "CREATE TABLE step_two (id INTEGER PRIMARY KEY)",- ],- }];- assert!(run_ladder(&mut conn, 3, BROKEN, 4).is_err());- assert_eq!(user_version(&conn), 3, "a failed step rolls back");- assert!(!table_exists(&conn, "step_four"));-- assert!(- run_ladder(&mut conn, 3, &[], 4).is_err(),- "a missing step is refused rather than skipped"- );- }-- #[test]- fn a_store_from_a_newer_release_is_quarantined_and_survives_under_its_new_name() {- let (_dir, path) = store_dir();- {- let store = Store::open(path.clone(), None).expect("a fresh store opens");- store- .set_metadata("canary", "keep-me")- .expect("metadata is writable");- store- .connection()- .pragma_update(None, "user_version", SCHEMA_VERSION + 1)- .expect("user_version is writable");- }-- let store = Store::open(path.clone(), None).expect("a replacement store opens");- assert_eq!(store.outcome().quarantine_reason, Some("newer"));- let quarantined = store- .outcome()- .quarantined_path- .clone()- .expect("the downgrade is quarantined");- assert!(path.exists(), "a fresh store replaces the quarantined one");- assert!(- Path::new(&quarantined).exists(),- "the source file must still exist under its new name"- );- assert_eq!(- store.metadata("canary").expect("metadata is readable"),- None- );-- let recovered = Connection::open(&quarantined).expect("the quarantined file opens");- let canary: String = recovered- .query_row(- "SELECT value FROM store_metadata WHERE key = 'canary'",- [],- |row| row.get(0),- )- .expect("the quarantined rows are intact");- assert_eq!(canary, "keep-me");- }-- #[test]- fn quarantine_renames_every_sidecar_and_unlinks_nothing() {- let (_dir, path) = store_dir();- fs::write(&path, b"main").expect("the main file is writable");- for suffix in ["-journal", "-wal", "-shm"] {- fs::write(sidecar_path(&path, suffix), suffix.as_bytes())- .expect("the sidecar is writable");- }-- let moved = quarantine(&path, QuarantineReason::Corrupt).expect("quarantine succeeds");- assert!(moved.contains(".corrupt-"));- assert!(!path.exists());- assert_eq!(- fs::read(&moved).expect("the moved file is readable"),- b"main"- );- for suffix in ["-journal", "-wal", "-shm"] {- assert_eq!(- fs::read(sidecar_path(Path::new(&moved), suffix))- .expect("the moved sidecar is readable"),- suffix.as_bytes()- );- }- }-- #[test]- fn a_file_that_is_not_a_database_is_quarantined_rather_than_deleted() {- let (_dir, path) = store_dir();- fs::write(&path, b"this is a note, not a database").expect("the file is writable");-- let store = Store::open(path.clone(), None).expect("a replacement store opens");- assert_eq!(store.outcome().quarantine_reason, Some("corrupt"));- let quarantined = store- .outcome()- .quarantined_path- .clone()- .expect("the unreadable file is quarantined");- assert_eq!(- fs::read(&quarantined).expect("the quarantined bytes are readable"),- b"this is a note, not a database"- );- }-- #[test]- fn a_vacuum_into_copy_still_verifies_as_compatible() {- let (dir, path) = store_dir();- let copy = dir.path().join("desktop-app-store.copy.sqlite3");- {- let store = Store::open(path, None).expect("a fresh store opens");- store- .set_metadata("canary", "keep-me")- .expect("metadata is writable");- store- .connection()- .execute("VACUUM INTO ?1", params![copy.to_string_lossy()])- .expect("the copy is written");- }-- let copied = Store::open(copy, None).expect("the copy opens");- assert!(- copied.outcome().quarantined_path.is_none(),- "a vacuumed copy is compatible, not quarantined"- );- assert_eq!(copied.outcome().previous_schema_version, SCHEMA_VERSION);- assert_eq!(- copied.metadata("canary").expect("metadata is readable"),- Some("keep-me".to_owned())- );- }-- #[test]- fn a_schema_whose_ddl_text_differs_but_whose_columns_match_is_kept() {- let (_dir, path) = store_dir();- drop(Store::open(path.clone(), None).expect("a fresh store opens"));- {- let conn = Connection::open(&path).expect("the store reopens directly");- conn.execute_batch(- "DROP TABLE accounts;- CREATE TABLE accounts (- storage_key TEXT PRIMARY KEY NOT NULL,- user_id text not null,- last_active REAL NOT NULL,- record_json TEXT NOT NULL- );- INSERT INTO accounts VALUES ('a::1', '1', 1.0, '{}');",- )- .expect("the table is rebuilt with different DDL text");- }-- let store = Store::open(path, None).expect("the rebuilt store opens");- assert!(- store.outcome().quarantined_path.is_none(),- "DDL text differences must not quarantine a compatible store"- );- let rows: i64 = store- .connection()- .query_row("SELECT COUNT(*) FROM accounts", [], |row| row.get(0))- .expect("the accounts survive");- assert_eq!(rows, 1);- }-- #[test]- fn a_missing_index_is_recreated_and_a_missing_table_is_quarantined() {- let (_dir, path) = store_dir();- drop(Store::open(path.clone(), None).expect("a fresh store opens"));- {- let conn = Connection::open(&path).expect("the store reopens directly");- conn.execute_batch("DROP INDEX accounts_last_active_idx")- .expect("the index is dropped");- }-- let store = Store::open(path.clone(), None).expect("the store opens");- assert!(store.outcome().quarantined_path.is_none());- let index: Option<i64> = store- .connection()- .query_row(- "SELECT 1 FROM sqlite_schema WHERE type = 'index' AND name = 'accounts_last_active_idx'",- [],- |row| row.get(0),- )- .optional()- .expect("the schema is readable");- assert!(index.is_some(), "a derivable index is repaired in place");- drop(store);-- {- let conn = Connection::open(&path).expect("the store reopens directly");- conn.execute_batch("DROP TABLE known_instances")- .expect("the table is dropped");- }- let store = Store::open(path, None).expect("a replacement store opens");- assert_eq!(store.outcome().quarantine_reason, Some("schema"));- assert!(store.outcome().quarantined_path.is_some());- }-- #[test]- fn a_changed_derivation_version_quarantines_rather_than_orphaning_rows() {- let (_dir, path) = store_dir();- {- let store = Store::open(path.clone(), Some("v1")).expect("a fresh store opens");- store- .set_metadata("canary", "keep-me")- .expect("metadata is writable");- }-- let same = Store::open(path.clone(), Some("v1")).expect("the store reopens");- assert!(same.outcome().quarantined_path.is_none());- drop(same);-- let changed = Store::open(path, Some("v2")).expect("a replacement store opens");- assert_eq!(changed.outcome().quarantine_reason, Some("derivation"));- assert_eq!(- changed- .metadata(METADATA_DERIVATION_VERSION)- .expect("metadata is readable"),- Some("v2".to_owned())- );- assert_eq!(- changed.metadata("canary").expect("metadata is readable"),- None- );- }-- #[test]- fn an_empty_ladder_is_contiguous_only_at_the_baseline_version() {- assert!(ladder_is_contiguous(&[], 1));- assert!(!ladder_is_contiguous(&[], 2));- }-- #[test]- fn a_contiguous_ladder_ending_at_the_target_is_accepted() {- const LADDER: &[Migration] = &[- Migration {- from: 1,- to: 2,- statements: &[],- },- Migration {- from: 2,- to: 3,- statements: &[],- },- ];- assert!(ladder_is_contiguous(LADDER, 3));- assert!(!ladder_is_contiguous(LADDER, 4));- }-- #[test]- fn a_ladder_with_a_gap_or_a_multi_step_edge_is_rejected() {- const GAP: &[Migration] = &[- Migration {- from: 1,- to: 2,- statements: &[],- },- Migration {- from: 3,- to: 4,- statements: &[],- },- ];- const MULTI_STEP: &[Migration] = &[Migration {- from: 1,- to: 3,- statements: &[],- }];- const LATE_START: &[Migration] = &[Migration {- from: 2,- to: 3,- statements: &[],- }];- assert!(!ladder_is_contiguous(GAP, 4));- assert!(!ladder_is_contiguous(MULTI_STEP, 3));- assert!(!ladder_is_contiguous(LATE_START, 3));- }-- #[test]- fn a_capacity_budget_admits_replacements_without_growing_the_entry_count() {- let mut budget = CapacityBudget {- resource: "test",- max_entries: 2,- max_bytes: 100,- entries: 2,- bytes: 50,- };- budget.check(Some(20), 30).expect("a replacement fits");- budget.commit(Some(20), 30);- assert_eq!(budget.entries, 2);- assert_eq!(budget.bytes, 60);- assert_eq!(- budget.check(None, 1).unwrap_err().unit,- "entries",- "a third entry must not be admitted"- );- assert_eq!(budget.check(Some(0), 41).unwrap_err().unit, "bytes");- assert_eq!(budget.bytes, 60, "a refused write must not consume budget");- }-- #[test]- fn store_metadata_refuses_unusable_keys_and_writes_past_its_caps() {- let (_dir, path) = store_dir();- let store = Store::open(path, None).expect("a fresh store opens");- let existing: i64 = store- .connection()- .query_row("SELECT COUNT(*) FROM store_metadata", [], |row| row.get(0))- .expect("the metadata rows are countable");- store- .connection()- .execute_batch("BEGIN IMMEDIATE")- .expect("the fill transaction begins");- for index in existing..MAX_METADATA_ROWS {- store- .set_metadata(&format!("marker.{index}"), "1")- .expect("a marker below the caps is written");- }- store- .connection()- .execute_batch("COMMIT")- .expect("the fill transaction commits");-- assert!(- matches!(- store.set_metadata("marker.new", "1"),- Err(StoreError::Capacity(refusal)) if refusal.unit == "entries"- ),- "a new marker key past the row cap must be refused"- );- let occupied = format!("marker.{existing}");- store- .set_metadata(&occupied, "updated")- .expect("replacing an existing marker still fits");- assert!(- matches!(- store.set_metadata(&occupied, &"v".repeat(MAX_METADATA_BYTES as usize + 1)),- Err(StoreError::Capacity(refusal)) if refusal.unit == "bytes"- ),- "a marker value past the byte cap must be refused"- );- let derivation_before = store- .metadata(METADATA_DERIVATION_VERSION)- .expect("reading the derivation stamp must succeed");- for reserved in [- METADATA_SCHEMA_VERSION,- METADATA_SCHEMA_APPLIED_AT,- METADATA_DERIVATION_VERSION,- ] {- assert!(- matches!(- store.set_metadata(reserved, "tampered"),- Err(StoreError::Refused(_))- ),- "the public path must refuse the reserved key {reserved}"- );- }- assert_eq!(- store- .metadata(METADATA_DERIVATION_VERSION)- .expect("reading the derivation stamp must succeed"),- derivation_before,- "a refused write must leave the derivation stamp untouched"- );- assert!(matches!(- store.set_metadata("", "1"),- Err(StoreError::Refused(_))- ));- assert!(matches!(- store.set_metadata("marker.\u{0}", "1"),- Err(StoreError::Refused(_))- ));- let rows: i64 = store- .connection()- .query_row("SELECT COUNT(*) FROM store_metadata", [], |row| row.get(0))- .expect("the metadata rows are countable");- assert_eq!(rows, MAX_METADATA_ROWS);- }-}diff --git a/fluxer_desktop/native/app-store/src/scoped_storage.rs b/fluxer_desktop/native/app-store/src/scoped_storage.rsindex 38592d809..188a285dd 100644--- a/fluxer_desktop/native/app-store/src/scoped_storage.rs+++ b/fluxer_desktop/native/app-store/src/scoped_storage.rs@@ -221,152 +221,3 @@ pub fn clear_store_except()?;Ok(())}--#[cfg(test)]-mod tests {- use super::*;- use crate::model::{Store, temporary_store_path};-- fn entry(store: &str, scope: &str, key: &str, value: &str) -> ScopedEntry {- ScopedEntry {- store: store.to_owned(),- scope: scope.to_owned(),- key: key.to_owned(),- value: value.to_owned(),- updated_at: 1.0,- }- }-- #[test]- fn entries_round_trip_and_are_ordered_by_key() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- for key in ["zeta", "alpha", "mu"] {- set_entry(store.connection(), &entry("app", "a::1", key, key))- .expect("the entry is stored");- }-- let stored =- scope_entries(store.connection(), "app", "a::1").expect("entries are readable");- assert_eq!(- stored- .iter()- .map(|row| row.key.as_str())- .collect::<Vec<_>>(),- vec!["alpha", "mu", "zeta"]- );- assert_eq!(- entry_value(store.connection(), "app", "a::1", "mu"),- Some("mu".to_owned())- );-- set_entry(store.connection(), &entry("app", "a::1", "mu", "updated"))- .expect("the entry is replaced");- assert_eq!(- entry_value(store.connection(), "app", "a::1", "mu"),- Some("updated".to_owned())- );- assert_eq!(- scope_entries(store.connection(), "app", "a::1")- .expect("entries are readable")- .len(),- 3,- "a replacement must not grow the scope"- );-- delete_entry(store.connection(), "app", "a::1", "mu").expect("the entry is deleted");- assert_eq!(entry_value(store.connection(), "app", "a::1", "mu"), None);- }-- #[test]- fn clearing_a_scope_leaves_every_other_scope_alone() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- set_entry(store.connection(), &entry("app", "a::1", "k", "mine"))- .expect("the entry is stored");- set_entry(store.connection(), &entry("voice", "a::1", "k", "mine"))- .expect("the entry is stored");- set_entry(store.connection(), &entry("app", "global", "k", "shared"))- .expect("the entry is stored");-- clear_scope(store.connection(), "a::1").expect("the scope is cleared");- assert!(- scope_entries(store.connection(), "app", "a::1")- .expect("entries are readable")- .is_empty()- );- assert!(- scope_entries(store.connection(), "voice", "a::1")- .expect("entries are readable")- .is_empty()- );- assert_eq!(- entry_value(store.connection(), "app", "global", "k"),- Some("shared".to_owned())- );- }-- #[test]- fn clearing_a_store_except_some_keys_spans_every_scope() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- for (scope, key) in [("a::1", "keep"), ("a::1", "drop"), ("global", "drop")] {- set_entry(store.connection(), &entry("app", scope, key, "v"))- .expect("the entry is stored");- }- set_entry(store.connection(), &entry("voice", "a::1", "drop", "v"))- .expect("the entry is stored");-- clear_store_except(store.connection(), "app", &["keep".to_owned()])- .expect("the store is cleared");- assert_eq!(- entry_value(store.connection(), "app", "a::1", "keep"),- Some("v".to_owned())- );- assert_eq!(entry_value(store.connection(), "app", "a::1", "drop"), None);- assert_eq!(- entry_value(store.connection(), "app", "global", "drop"),- None- );- assert_eq!(- entry_value(store.connection(), "voice", "a::1", "drop"),- Some("v".to_owned()),- "another store must be untouched"- );-- clear_store_except(store.connection(), "voice", &[]).expect("the store is cleared");- assert_eq!(- entry_value(store.connection(), "voice", "a::1", "drop"),- None- );- }-- #[test]- fn an_oversized_value_is_refused_before_it_is_inserted() {- let (_dir, path) = temporary_store_path();- let store = Store::open(path, None).expect("a fresh store opens");- let oversized = "x".repeat(MAX_SCOPED_VALUE_BYTES + 1);-- let mut budgets = EntryBudgets::read(store.connection()).expect("budgets are readable");- let refusal = write_entry(- store.connection(),- &mut budgets,- &entry("app", "a::1", "big", &oversized),- )- .expect("the write completes")- .expect("the write is refused");- assert!(refusal.to_string().contains("too large"));- assert!(- scope_entries(store.connection(), "app", "a::1")- .expect("entries are readable")- .is_empty(),- "a refused entry must never reach the table"- );- }-- fn entry_value(conn: &Connection, store: &str, scope: &str, key: &str) -> Option<String> {- super::entry(conn, store, scope, key)- .expect("the entry is readable")- .map(|row| row.value)- }-}diff --git a/fluxer_desktop/native/gateway-socket/src/lib.rs b/fluxer_desktop/native/gateway-socket/src/lib.rsindex 054e1eb96..c313b3b83 100644--- a/fluxer_desktop/native/gateway-socket/src/lib.rs+++ b/fluxer_desktop/native/gateway-socket/src/lib.rs@@ -663,7 +663,7 @@ fn trust_roots(roots}-#[cfg(any(windows, test))]+#[cfg(windows)]fn der_element(input: &[u8]) -> Option<(u8, &[u8], &[u8])> {let (&tag, rest) = input.split_first()?;let (&first, rest) = rest.split_first()?;@@ -689,7 +689,7 @@ fn der_element(input: &[u8]) -> Option<(u8, &[u8], &[u8])> {Some((tag, content, rest))}-#[cfg(any(windows, test))]+#[cfg(windows)]fn is_self_issued(certificate: &[u8]) -> bool {let Some((0x30, certificate, [])) = der_element(certificate) else {return false;@@ -1216,671 +1216,3 @@ pub fn connect(Arc::new(NapiEventDelivery { regular, terminal }),)}--#[cfg(test)]-mod tests {- use std::{future::Future, time::Instant};-- use tokio::net::TcpListener;- use tokio_tungstenite::accept_async;-- use super::*;-- const EVENT_WAIT_TIMEOUT: Duration = Duration::from_secs(10);- const STALLED_CONSUMER_SETTLE: Duration = Duration::from_millis(500);-- struct RecordingDelivery {- events: mpsc::UnboundedSender<TransportEvent>,- }-- impl EventDelivery for RecordingDelivery {- fn deliver(&self, event: QueuedTransportEvent) -> bool {- let QueuedTransportEvent { event, reservation } = event;- drop(reservation);- self.events.send(event).is_ok()- }-- fn deliver_terminal(&self, event: TransportEvent) {- let _ = self.events.send(event);- }- }-- struct StallingDelivery {- events: mpsc::UnboundedSender<TransportEvent>,- held: Mutex<Option<Vec<QueueReservation>>>,- }-- impl StallingDelivery {- fn resume(&self) {- self.held.lock().expect("stalled reservations").take();- }- }-- impl EventDelivery for StallingDelivery {- fn deliver(&self, event: QueuedTransportEvent) -> bool {- let QueuedTransportEvent { event, reservation } = event;- match self.held.lock().expect("stalled reservations").as_mut() {- Some(held) => held.push(reservation),- None => drop(reservation),- }- self.events.send(event).is_ok()- }-- fn deliver_terminal(&self, event: TransportEvent) {- let _ = self.events.send(event);- }- }-- fn spawn_server<Handler, Served>(handler: Handler) -> SocketAddr- where- Handler: FnOnce(WebSocketStream<TcpStream>) -> Served + Send + 'static,- Served: Future<Output = ()> + Send,- {- let runtime = transport_runtime().expect("transport runtime");- let listener = runtime- .block_on(TcpListener::bind("127.0.0.1:0"))- .expect("bind test listener");- let address = listener.local_addr().expect("listener address");- runtime.spawn(async move {- let (stream, _) = listener.accept().await.expect("accept test connection");- let socket = accept_async(stream).await.expect("accept websocket");- handler(socket).await;- });- address- }-- fn spawn_echo_server() -> SocketAddr {- spawn_server(|mut socket| async move {- while let Some(Ok(message)) = socket.next().await {- match message {- Message::Text(_) | Message::Binary(_) => {- if socket.send(message).await.is_err() {- return;- }- }- Message::Close(_) => return,- _ => {}- }- }- })- }-- fn test_connection(- address: SocketAddr,- pinned_address: Option<&str>,- mode: TransportMode,- ) -> (- NativeGatewayConnection,- mpsc::UnboundedReceiver<TransportEvent>,- ) {- let (events, receiver) = mpsc::unbounded_channel();- let target = parse_websocket_connection_target(- &format!("ws://127.0.0.1:{}/", address.port()),- pinned_address,- )- .expect("connection target");- let connection =- NativeGatewayConnection::start(target, mode, Arc::new(RecordingDelivery { events }))- .expect("start connection");- (connection, receiver)- }-- fn block_recv<T>(receiver: &mut mpsc::UnboundedReceiver<T>) -> T {- let runtime = transport_runtime().expect("transport runtime");- runtime.block_on(async {- tokio::time::timeout(EVENT_WAIT_TIMEOUT, receiver.recv())- .await- .expect("timed out waiting for a value")- .expect("value channel closed")- })- }-- fn next_event(events: &mut mpsc::UnboundedReceiver<TransportEvent>) -> TransportEvent {- block_recv(events)- }-- fn expect_open(events: &mut mpsc::UnboundedReceiver<TransportEvent>) {- let event = next_event(events);- assert_eq!(event.kind, EVENT_KIND_OPEN, "{:?}", event.message);- }-- const TLS_FIXTURE_HOST: &str = "ca.example";- const TLS_FIXTURE_LEAF: &[u8] =- include_bytes!("../../../src/main/fixtures/desktop-tls/leaf.pem");- const TLS_FIXTURE_LEAF_KEY: &[u8] =- include_bytes!("../../../src/main/fixtures/desktop-tls/leaf.key");- const TLS_FIXTURE_TRUSTED_CA: &[u8] =- include_bytes!("../../../src/main/fixtures/desktop-tls/trusted-ca.pem");- const TLS_FIXTURE_UNTRUSTED_CA: &[u8] =- include_bytes!("../../../src/main/fixtures/desktop-tls/untrusted-ca.pem");-- fn fixture_certificate(pem: &[u8]) -> rustls::pki_types::CertificateDer<'static> {- use rustls::pki_types::pem::PemObject;- rustls::pki_types::CertificateDer::from_pem_slice(pem).expect("fixture certificate")- }-- fn fixture_server_config() -> Arc<rustls::ServerConfig> {- use rustls::pki_types::pem::PemObject;- ensure_rustls_crypto_provider();- Arc::new(- rustls::ServerConfig::builder()- .with_no_client_auth()- .with_single_cert(- vec![fixture_certificate(TLS_FIXTURE_LEAF)],- rustls::pki_types::PrivateKeyDer::from_pem_slice(TLS_FIXTURE_LEAF_KEY)- .expect("fixture key"),- )- .expect("fixture server config"),- )- }-- fn pump(- from: &mut rustls::Connection,- to: &mut rustls::Connection,- ) -> std::result::Result<(), rustls::Error> {- let mut bytes = Vec::new();- while from.wants_write() {- from.write_tls(&mut bytes).expect("write tls");- }- let mut cursor = bytes.as_slice();- while !cursor.is_empty() {- to.read_tls(&mut cursor).expect("read tls");- to.process_new_packets()?;- }- Ok(())- }-- fn handshake(roots: rustls::RootCertStore) -> std::result::Result<(), rustls::Error> {- ensure_rustls_crypto_provider();- let client_config = rustls::ClientConfig::builder()- .with_root_certificates(roots)- .with_no_client_auth();- let mut client = rustls::Connection::Client(- rustls::ClientConnection::new(- Arc::new(client_config),- rustls::pki_types::ServerName::try_from(TLS_FIXTURE_HOST).expect("server name"),- )- .expect("client connection"),- );- let mut server = rustls::Connection::Server(- rustls::ServerConnection::new(fixture_server_config()).expect("server connection"),- );- while client.is_handshaking() || server.is_handshaking() {- pump(&mut client, &mut server).expect("server accepts the client flight");- pump(&mut server, &mut client)?;- }- Ok(())- }-- #[test]- fn trust_roots_add_extra_anchors_to_the_native_store() {- let unknown_issuer = Err(rustls::Error::InvalidCertificate(- rustls::CertificateError::UnknownIssuer,- ));- assert_eq!(handshake(trust_roots(Vec::new(), &[])), unknown_issuer);- assert_eq!(- handshake(trust_roots(- vec![fixture_certificate(TLS_FIXTURE_UNTRUSTED_CA)],- &[]- )),- unknown_issuer- );- assert_eq!(- handshake(trust_roots(- vec![fixture_certificate(TLS_FIXTURE_UNTRUSTED_CA)],- &[fixture_certificate(TLS_FIXTURE_TRUSTED_CA)]- )),- Ok(())- );- assert_eq!(- handshake(trust_roots(- vec![fixture_certificate(TLS_FIXTURE_TRUSTED_CA)],- &[]- )),- Ok(())- );- }-- #[test]- fn only_self_issued_certificates_count_as_intermediate_store_roots() {- assert!(is_self_issued(&fixture_certificate(TLS_FIXTURE_TRUSTED_CA)));- assert!(is_self_issued(&fixture_certificate(- TLS_FIXTURE_UNTRUSTED_CA- )));- let leaf = fixture_certificate(TLS_FIXTURE_LEAF);- assert!(!is_self_issued(&leaf));- let root = fixture_certificate(TLS_FIXTURE_TRUSTED_CA);- assert!(!is_self_issued(&root[..root.len() - 1]));- let mut trailing = root.to_vec();- trailing.push(0);- assert!(!is_self_issued(&trailing));- assert!(!is_self_issued(&[]));- assert!(!is_self_issued(&[0x30, 0x84, 0xff, 0xff, 0xff, 0xff]));- #[cfg(not(windows))]- assert!(windows_intermediate_store_roots().is_empty());- }-- #[test]- fn connection_targets_reject_unusable_urls() {- for url in [- "",- "http://gateway.example/",- "https://gateway.example/",- " wss://gateway.example/",- "wss://user:[email protected]/",- "wss://[email protected]/",- "wss://gateway.example/#fragment",- "wss://gateway.example/\u{7}",- "not-a-url",- ] {- assert!(- parse_websocket_connection_target(url, None).is_err(),- "expected {url} to be rejected"- );- }- let long_url = format!(- "wss://gateway.example/{}",- "a".repeat(ENDPOINT_URL_MAX_BYTES)- );- assert!(parse_websocket_connection_target(&long_url, None).is_err());- }-- #[test]- fn connection_targets_reject_unusable_pinned_addresses() {- for address in ["", "gateway.example", "127.0.0.1 ", "1.2.3.4\u{7}"] {- assert!(- parse_websocket_connection_target("wss://gateway.example/", Some(address)).is_err(),- "expected {address} to be rejected"- );- }- let long_address = "a".repeat(PINNED_ADDRESS_MAX_BYTES + 1);- assert!(- parse_websocket_connection_target("wss://gateway.example/", Some(&long_address))- .is_err()- );- }-- #[test]- fn connection_targets_resolve_hosts_ports_and_optional_pins() {- let plain = parse_websocket_connection_target("ws://gateway.example/socket", None).unwrap();- assert_eq!(plain.host, "gateway.example");- assert_eq!(plain.port, 80);- assert!(plain.pinned_address.is_none());- assert!(!plain.tls);-- let secure =- parse_websocket_connection_target("wss://gateway.example/socket?v=9", None).unwrap();- assert_eq!(secure.port, 443);- assert!(secure.tls);-- let pinned =- parse_websocket_connection_target("wss://gateway.example:8443/", Some("203.0.113.7"))- .unwrap();- assert_eq!(pinned.port, 8443);- assert_eq!(- pinned.pinned_address,- Some("203.0.113.7".parse::<IpAddr>().unwrap())- );-- let literal = parse_websocket_connection_target("ws://[::1]:9000/", None).unwrap();- assert_eq!(literal.host, "::1");- assert_eq!(literal.port, 9000);- }-- #[test]- fn the_queue_budget_rejects_past_its_entry_and_byte_caps() {- static GLOBAL_BYTES: AtomicUsize = AtomicUsize::new(0);- static GLOBAL_RELEASED: Notify = Notify::const_new();- let budget = Arc::new(QueueBudget::new(- 2,- 1_024,- &GLOBAL_BYTES,- 1 << 20,- &GLOBAL_RELEASED,- ));-- let first = budget.reserve(16).unwrap();- let second = budget.reserve(16).unwrap();- assert!(budget.reserve(16).is_err());-- drop(second);- assert!(budget.reserve(2_048).is_err());- assert_eq!(budget.queued_entries.load(Ordering::Acquire), 1);- assert_eq!(budget.queued_bytes.load(Ordering::Acquire), 16);-- drop(first);- assert_eq!(budget.queued_entries.load(Ordering::Acquire), 0);- assert_eq!(budget.queued_bytes.load(Ordering::Acquire), 0);- assert_eq!(GLOBAL_BYTES.load(Ordering::Acquire), 0);- }-- #[tokio::test]- async fn releasing_one_connection_wakes_another_parked_on_the_process_wide_cap() {- static GLOBAL_BYTES: AtomicUsize = AtomicUsize::new(0);- static GLOBAL_RELEASED: Notify = Notify::const_new();- let saturated = Arc::new(QueueBudget::new(- 8,- 1_024,- &GLOBAL_BYTES,- 1_024,- &GLOBAL_RELEASED,- ));- let parked = Arc::new(QueueBudget::new(- 8,- 1_024,- &GLOBAL_BYTES,- 1_024,- &GLOBAL_RELEASED,- ));-- let held = saturated.reserve(1_024).unwrap();- assert!(parked.reserve(512).is_err());- assert_eq!(parked.queued_bytes.load(Ordering::Acquire), 0);-- let waiter = {- let parked = parked.clone();- tokio::spawn(async move {- let released = parked.global_released.notified();- tokio::pin!(released);- released.as_mut().enable();- released.await;- parked.reserve(512).is_ok()- })- };- tokio::task::yield_now().await;- drop(held);-- let reserved = tokio::time::timeout(Duration::from_secs(2), waiter)- .await- .expect("a connection parked on the global cap must be woken when another releases")- .expect("the waiting task must not panic");- assert!(reserved, "the woken connection must be able to reserve");- }-- #[test]- fn the_queue_budget_rejects_past_the_process_wide_byte_cap() {- static GLOBAL_BYTES: AtomicUsize = AtomicUsize::new(0);- static GLOBAL_RELEASED: Notify = Notify::const_new();- let first = Arc::new(QueueBudget::new(- 8,- 1_024,- &GLOBAL_BYTES,- 1_024,- &GLOBAL_RELEASED,- ));- let second = Arc::new(QueueBudget::new(- 8,- 1_024,- &GLOBAL_BYTES,- 1_024,- &GLOBAL_RELEASED,- ));-- let held = first.reserve(768).unwrap();- assert!(second.reserve(512).is_err());- let fitting = second.reserve(256).unwrap();- assert_eq!(GLOBAL_BYTES.load(Ordering::Acquire), 1_024);-- drop(held);- drop(fitting);- assert_eq!(GLOBAL_BYTES.load(Ordering::Acquire), 0);- }-- #[test]- fn a_burst_past_the_event_queue_limit_waits_for_the_consumer_instead_of_closing() {- const BURST: usize = EVENT_QUEUE_LIMIT * 2;-- let address = spawn_server(|mut socket| async move {- for index in 0..BURST {- if socket- .send(Message::Text(Utf8Bytes::from(format!("event-{index}"))))- .await- .is_err()- {- return;- }- }- while let Some(Ok(message)) = socket.next().await {- if matches!(message, Message::Close(_)) {- return;- }- }- });- let (events, mut receiver) = mpsc::unbounded_channel();- let delivery = Arc::new(StallingDelivery {- events,- held: Mutex::new(Some(Vec::new())),- });- let target =- parse_websocket_connection_target(&format!("ws://127.0.0.1:{}/", address.port()), None)- .expect("connection target");- let _connection =- NativeGatewayConnection::start(target, TransportMode::Gateway, delivery.clone())- .expect("start connection");-- expect_open(&mut receiver);- for index in 0..EVENT_QUEUE_LIMIT - 1 {- let event = next_event(&mut receiver);- assert_eq!(event.kind, EVENT_KIND_MESSAGE, "{:?}", event.reason);- assert_eq!(event.data, Some(format!("event-{index}")));- }-- let stalled = transport_runtime()- .expect("transport runtime")- .block_on(async {- tokio::time::timeout(STALLED_CONSUMER_SETTLE, receiver.recv()).await- });- if let Ok(event) = stalled {- panic!(- "a full event queue must stall the reader, not deliver {:?}",- event.map(|event| (event.kind, event.code, event.reason))- );- }-- delivery.resume();- for index in EVENT_QUEUE_LIMIT - 1..BURST {- let event = next_event(&mut receiver);- assert_eq!(event.kind, EVENT_KIND_MESSAGE, "{:?}", event.reason);- assert_eq!(event.data, Some(format!("event-{index}")));- }- }-- #[test]- fn disposing_while_the_event_queue_is_full_still_closes_the_socket() {- const BURST: usize = EVENT_QUEUE_LIMIT * 2;-- let (peer_closed, mut peer_closed_events) = mpsc::unbounded_channel();- let address = spawn_server(move |mut socket| async move {- for index in 0..BURST {- if socket- .send(Message::Text(Utf8Bytes::from(format!("event-{index}"))))- .await- .is_err()- {- break;- }- }- while let Some(Ok(message)) = socket.next().await {- if matches!(message, Message::Close(_)) {- break;- }- }- let _ = peer_closed.send(Instant::now());- });- let (events, mut receiver) = mpsc::unbounded_channel();- let delivery = Arc::new(StallingDelivery {- events,- held: Mutex::new(Some(Vec::new())),- });- let target =- parse_websocket_connection_target(&format!("ws://127.0.0.1:{}/", address.port()), None)- .expect("connection target");- let connection =- NativeGatewayConnection::start(target, TransportMode::Gateway, delivery.clone())- .expect("start connection");-- expect_open(&mut receiver);- for _ in 0..EVENT_QUEUE_LIMIT - 1 {- let event = next_event(&mut receiver);- assert_eq!(event.kind, EVENT_KIND_MESSAGE, "{:?}", event.reason);- }-- drop(connection);- block_recv(&mut peer_closed_events);- }-- #[test]- fn the_echo_server_round_trips_text_and_binary_byte_for_byte() {- let address = spawn_echo_server();- let (connection, mut events) =- test_connection(address, Some("127.0.0.1"), TransportMode::Gateway);- expect_open(&mut events);-- let text = "héllo \u{1f600} {\"op\":1,\"d\":null}";- connection.send_text(text.to_owned()).unwrap();- let event = next_event(&mut events);- assert_eq!(event.kind, EVENT_KIND_MESSAGE);- assert_eq!(event.data.as_deref(), Some(text));- assert!(event.binary.is_none());-- let payload: Vec<u8> = (0..=255u8).chain(0..=255u8).collect();- connection- .send_frame(Message::Binary(payload.clone().into()))- .unwrap();- let event = next_event(&mut events);- assert_eq!(event.kind, EVENT_KIND_BINARY);- assert_eq!(event.binary.as_deref(), Some(payload.as_slice()));- assert!(event.data.is_none());- }-- #[test]- fn closing_reports_a_clean_close_to_both_ends() {- let (peer_close, mut peer_close_events) = mpsc::unbounded_channel();- let address = spawn_server(move |mut socket| async move {- while let Some(Ok(message)) = socket.next().await {- if let Message::Close(frame) = message {- let _ = peer_close- .send(frame.map(|frame| {- (u16::from(frame.code), frame.reason.as_str().to_owned())- }));- return;- }- }- });- let (connection, mut events) = test_connection(address, None, TransportMode::Gateway);- expect_open(&mut events);-- connection- .close(4000, "Switching accounts".to_owned())- .unwrap();- let event = next_event(&mut events);- assert_eq!(event.kind, EVENT_KIND_CLOSE);- assert_eq!(event.code, Some(4000));- assert_eq!(event.reason.as_deref(), Some("Switching accounts"));- assert_eq!(event.was_clean, Some(true));- assert_eq!(- block_recv(&mut peer_close_events),- Some((4000, "Switching accounts".to_owned()))- );- }-- #[test]- fn an_over_size_gateway_frame_reports_an_error_and_closes_with_1009() {- let (peer_close, mut peer_close_events) = mpsc::unbounded_channel();- let address = spawn_server(move |mut socket| async move {- let payload = vec![7u8; GATEWAY_FRAME_MAX_BYTES + 1];- if socket.send(Message::Binary(payload.into())).await.is_err() {- return;- }- while let Some(Ok(message)) = socket.next().await {- if let Message::Close(frame) = message {- let _ = peer_close.send(frame.map(|frame| u16::from(frame.code)));- return;- }- }- });- let (_connection, mut events) = test_connection(address, None, TransportMode::Gateway);- expect_open(&mut events);-- let error = next_event(&mut events);- assert_eq!(error.kind, EVENT_KIND_ERROR);- assert!(error.message.is_some());- let close = next_event(&mut events);- assert_eq!(close.kind, EVENT_KIND_CLOSE);- assert_eq!(close.code, Some(1009));- assert_eq!(close.was_clean, Some(false));- assert_eq!(block_recv(&mut peer_close_events), Some(1009));- }-- #[test]- fn dropping_the_connection_closes_the_socket_within_the_dispose_timeout() {- let (peer_closed, mut peer_closed_events) = mpsc::unbounded_channel();- let address = spawn_server(move |mut socket| async move {- while let Some(Ok(message)) = socket.next().await {- if matches!(message, Message::Close(_)) {- break;- }- }- let _ = peer_closed.send(Instant::now());- });- let (connection, mut events) = test_connection(address, None, TransportMode::Gateway);- expect_open(&mut events);-- let dropped_at = Instant::now();- drop(connection);- let closed_at = block_recv(&mut peer_closed_events);- assert!(closed_at.duration_since(dropped_at) < DISPOSE_CLOSE_TIMEOUT);- }-- #[test]- fn a_disposed_connection_refuses_further_commands() {- let address = spawn_echo_server();- let (connection, mut events) = test_connection(address, None, TransportMode::Gateway);- expect_open(&mut events);-- connection.dispose().unwrap();- connection.dispose().unwrap();- assert!(connection.send_text("late".to_owned()).is_err());- assert!(connection.close(1000, String::new()).is_err());- }-- #[test]- fn frames_beyond_the_transport_mode_maximum_are_refused_before_the_queue() {- let address = spawn_echo_server();- let (connection, mut events) = test_connection(address, None, TransportMode::Voice);- expect_open(&mut events);-- let error = connection- .send_text("a".repeat(VOICE_FRAME_MAX_BYTES + 1))- .unwrap_err();- assert_eq!(error.status, Status::InvalidArg);- assert!(- connection- .send_frame(Message::Binary(vec![0u8; VOICE_FRAME_MAX_BYTES + 1].into()))- .is_err()- );- assert!(- connection- .send_text("a".repeat(VOICE_FRAME_MAX_BYTES))- .is_ok()- );- }-- #[test]- fn an_unreachable_endpoint_reports_an_error_and_an_unclean_close() {- let runtime = transport_runtime().expect("transport runtime");- let listener = runtime- .block_on(TcpListener::bind("127.0.0.1:0"))- .expect("bind test listener");- let address = listener.local_addr().expect("listener address");- drop(listener);-- let (_connection, mut events) = test_connection(address, None, TransportMode::Gateway);- let error = next_event(&mut events);- assert_eq!(error.kind, EVENT_KIND_ERROR);- let close = next_event(&mut events);- assert_eq!(close.kind, EVENT_KIND_CLOSE);- assert_eq!(close.code, Some(1006));- assert_eq!(close.was_clean, Some(false));- }-}diff --git a/fluxer_desktop/native/hardware-encoder/src/lib.rs b/fluxer_desktop/native/hardware-encoder/src/lib.rsindex ea9461965..c5aefc19a 100644--- a/fluxer_desktop/native/hardware-encoder/src/lib.rs+++ b/fluxer_desktop/native/hardware-encoder/src/lib.rs@@ -1,5 +1,4 @@// SPDX-License-Identifier: AGPL-3.0-or-later-#![allow(dead_code)]use napi_derive::napi;@@ -322,10 +321,6 @@ impl VideoToolboxRuntimeProbe {#[napi]pub fn get_hardware_encoder_capability() -> HardwareEncoderCapability {- hardware_encoder_capability()-}--pub fn hardware_encoder_capability() -> HardwareEncoderCapability {if cfg!(target_os = "macos") {return describe_videotoolbox_capability(probe_macos_videotoolbox_runtime());}@@ -965,92 +960,3 @@ fn probe_macos_videotoolbox_runtime() -> Option<VideoToolboxRuntimeProbe> {fn probe_macos_videotoolbox_runtime() -> Option<VideoToolboxRuntimeProbe> {None}--#[cfg(test)]-mod tests {- use super::*;-- fn runtime_ready() -> NvencRuntimeProbe {- NvencRuntimeProbe {- libcuda: true,- libnvidia_encode: true,- get_max_supported_version: true,- driver_version_compatible: true,- create_instance: true,- cuda_init: true,- cuda_device_count: Some(1),- cuda_device: true,- cuda_context: true,- checked_cuda_devices: 1,- supported_cuda_devices: 1,- open_encode_session: true,- query_encode_guids: true,- supports_h264: true,- supports_h265: true,- last_open_encode_session_status: Some(0),- }- }-- fn videotoolbox_ready() -> VideoToolboxRuntimeProbe {- VideoToolboxRuntimeProbe {- h264_create_status: Some(0),- h264_prepare_status: Some(0),- h265_create_status: Some(0),- h265_prepare_status: Some(0),- }- }-- #[test]- fn reports_h264_only_when_hevc_guid_is_absent() {- let capability = describe_capability(- CapabilityPlatform::Linux,- true,- Some(NvencRuntimeProbe {- supports_h265: false,- ..runtime_ready()- }),- );-- assert!(capability.available);- assert_eq!(capability.codecs, vec!["h264"]);- assert!(capability.zero_copy);- }-- #[test]- fn reports_no_supported_codecs_when_guid_query_finds_no_fluxer_codecs() {- let capability = describe_capability(- CapabilityPlatform::Linux,- true,- Some(NvencRuntimeProbe {- supports_h264: false,- supports_h265: false,- ..runtime_ready()- }),- );-- assert!(!capability.available);- assert_eq!(capability.reason.as_deref(), Some("no_supported_codecs"));- assert_eq!(capability.codecs, Vec::<String>::new());- assert!(- capability- .detail- .as_deref()- .unwrap_or_default()- .contains("NVENC H264/H265 encode GUID")- );- }-- #[test]- fn reports_videotoolbox_h264_only_when_hevc_session_is_unavailable() {- let capability = describe_videotoolbox_capability(Some(VideoToolboxRuntimeProbe {- h265_create_status: Some(-12909),- h265_prepare_status: None,- ..videotoolbox_ready()- }));-- assert!(capability.available);- assert_eq!(capability.backend, "videotoolbox");- assert_eq!(capability.codecs, vec!["h264"]);- assert_eq!(capability.reason, None);- }-}diff --git a/fluxer_desktop/native/platform-info/src/probe_helpers.rs b/fluxer_desktop/native/platform-info/src/probe_helpers.rsindex fd4a96fb6..02b76fafd 100644--- a/fluxer_desktop/native/platform-info/src/probe_helpers.rs+++ b/fluxer_desktop/native/platform-info/src/probe_helpers.rs@@ -16,7 +16,7 @@ pub fn vendor_name(vendor_id: u32) -> Option<&'static str> {}}-#[cfg(any(target_os = "macos", test))]+#[cfg(target_os = "macos")]pub fn vendor_id_from_name(name: &str) -> u32 {let lower = name.to_ascii_lowercase();if lower.contains("apple") {@@ -42,14 +42,14 @@ pub fn write_hex_u64(value: u64) -> String {format!("0x{value:x}")}-#[cfg(any(target_os = "linux", test))]+#[cfg(target_os = "linux")]#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ParseHexIdError {InvalidHexId,InvalidDigit,}-#[cfg(any(target_os = "linux", test))]+#[cfg(target_os = "linux")]pub fn parse_hex_id(raw: &str) -> Result<u32, ParseHexIdError> {let mut trimmed = raw.trim();if let Some(rest) = trimmed@@ -64,7 +64,7 @@ pub fn parse_hex_id(raw: &str) -> Result<u32, ParseHexIdError> {u32::from_str_radix(trimmed, 16).map_err(|_| ParseHexIdError::InvalidDigit)}-#[cfg(any(target_os = "linux", test))]+#[cfg(target_os = "linux")]pub fn is_drm_card_name(name: &str) -> bool {let Some(rest) = name.strip_prefix("card") else {return false;@@ -76,30 +76,3 @@ pub fn is_drm_card_name(name: &str) -> bool {pub fn basename(path: &str) -> &str {path.rsplit_once('/').map_or(path, |(_, base)| base)}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn parse_hex_id_accepts_sysfs_hex_ids() {- assert_eq!(0x8086, parse_hex_id("0x8086\n").unwrap());- assert_eq!(0x10de, parse_hex_id("10DE").unwrap());- assert_eq!(Err(ParseHexIdError::InvalidHexId), parse_hex_id("0x"));- }-- #[test]- fn is_drm_card_name_accepts_cards_but_rejects_connectors_render_nodes() {- assert!(is_drm_card_name("card0"));- assert!(is_drm_card_name("card12"));- assert!(!is_drm_card_name("card0-DP-1"));- assert!(!is_drm_card_name("renderD128"));- }-- #[test]- fn vendor_id_helpers() {- assert_eq!(0x106b, vendor_id_from_name("Apple M3 GPU"));- assert_eq!(Some("NVIDIA"), vendor_name(0x10de));- assert_eq!(None, vendor_name(0xffff));- }-}diff --git a/fluxer_desktop/native/sample-pool/src/lib.rs b/fluxer_desktop/native/sample-pool/src/lib.rsindex 7ac43bd12..e0637c1a9 100644--- a/fluxer_desktop/native/sample-pool/src/lib.rs+++ b/fluxer_desktop/native/sample-pool/src/lib.rs@@ -290,14 +290,6 @@ impl<T: Copy + Default + Send + Sync, const CHECK_INVARIANTS: bool>self.filled_len = len;}- pub fn data_slice(&self) -> &[T] {- pool_assert!(self.slot_index < self.pool.capacity as usize);- pool_assert!(self.filled_len <= self.pool.samples_per_slot as usize);- let cell = &self.pool.slots[self.slot_index];- let buf: &[T] = unsafe { &*cell.inner.get() };- &buf[..self.filled_len]- }-pub fn filled_len(&self) -> usize {pool_assert!(self.slot_index < self.pool.capacity as usize);pool_assert!(self.filled_len <= self.pool.samples_per_slot as usize);@@ -347,193 +339,3 @@ impl<T: Copy + Default + Send + Sync, const CHECK_INVARIANTS: bool> Dropdrop(free);}}--#[cfg(test)]-mod tests {- use super::*;- use std::thread;-- const PCM_POOL_CAP: usize = 16;- type SamplePool = super::SamplePool<f32>;- const SLOT_SAMPLES: usize = 2_048;-- fn default_pool() -> SamplePool {- SamplePool::new(PCM_POOL_CAP, SLOT_SAMPLES).expect("default pool builds")- }-- #[test]- fn acquire_release_cycle_increments_counters() {- let pool = SamplePool::new(4, SLOT_SAMPLES).expect("pool");- {- let _slot = pool.try_acquire().expect("slot");- let stats_held = pool.stats();- assert_eq!(stats_held.acquired, 1);- assert_eq!(stats_held.in_flight, 1);- }- let stats_after = pool.stats();- assert_eq!(stats_after.acquired, 1);- assert_eq!(stats_after.released, 1);- assert_eq!(stats_after.in_flight, 0);- }-- #[test]- fn pool_exhausts_at_cap_and_counts_drop() {- let pool = default_pool();- let mut held = Vec::with_capacity(PCM_POOL_CAP);- for _ in 0..PCM_POOL_CAP {- held.push(pool.try_acquire().expect("slot in capacity"));- }- assert!(pool.try_acquire().is_none());- let stats = pool.stats();- assert_eq!(stats.dropped, 1);- assert_eq!(stats.acquired as usize, PCM_POOL_CAP);- assert_eq!(stats.in_flight as usize, PCM_POOL_CAP);- }-- #[test]- fn write_then_data_slice_matches_payload() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- let payload = [0.25_f32; 32];- slot.write(&payload).expect("payload fits");- assert_eq!(slot.data_slice(), &payload[..]);- assert_eq!(slot.filled_len(), 32);- }-- #[test]- fn write_rejects_payload_larger_than_slot() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- let big = [0.0_f32; 128];- let err = slot.write(&big).unwrap_err();- assert!(matches!(err, PcmPoolError::PayloadTooLarge { .. }));- }-- #[test]- fn unfilled_mut_then_set_filled_len_matches_data_slice() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- {- let buf = slot.unfilled_mut();- assert_eq!(buf.len(), 64);- buf[0] = 0.5;- buf[1] = -0.5;- buf[2] = 1.0;- }- slot.set_filled_len(3);- assert_eq!(slot.filled_len(), 3);- assert_eq!(slot.data_slice(), &[0.5, -0.5, 1.0]);- }-- #[test]- #[should_panic]- fn set_filled_len_rejects_overflow() {- let pool = SamplePool::new(1, 32).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- slot.set_filled_len(33);- }-- #[test]- fn into_external_parts_exposes_filled_pointer_and_length() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- let payload = [1.5_f32; 16];- slot.write(&payload).expect("write fits");- let (ptr, len, owned) = slot.into_external_parts();- assert!(!ptr.is_null());- assert_eq!(len, 16);- let observed = unsafe { core::slice::from_raw_parts(ptr, len) };- assert_eq!(observed, &payload[..]);- assert_eq!(pool.stats().in_flight, 1);- drop(owned);- assert_eq!(pool.stats().in_flight, 0);- }-- #[test]- fn into_external_parts_drop_returns_slot_to_pool() {- let pool = SamplePool::new(1, 32).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- slot.write(&[0.75_f32; 8]).expect("write");- let (_ptr, _len, owned) = slot.into_external_parts();- assert!(pool.try_acquire().is_none());- drop(owned);- let revived = pool.try_acquire().expect("revived");- assert_eq!(revived.filled_len(), 0);- drop(revived);- assert_eq!(pool.stats().in_flight, 0);- }-- #[test]- fn pooled_frame_survives_send_across_threads() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- slot.write(&[0.5_f32; 32]).expect("write");- let handle = thread::spawn(move || {- assert_eq!(slot.filled_len(), 32);- assert_eq!(slot.data_slice()[0], 0.5);- drop(slot);- });- handle.join().expect("worker");- assert_eq!(pool.stats().in_flight, 0);- assert_eq!(pool.stats().released, 1);- }-- #[test]- fn write_with_fills_exactly_sample_count_samples() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- slot.write_with(8, |out| {- assert_eq!(out.len(), 8);- for (index, sample) in out.iter_mut().enumerate() {- *sample = index as f32;- }- })- .expect("payload fits");- assert_eq!(slot.filled_len(), 8);- assert_eq!(slot.data_slice(), &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]);- }-- #[test]- fn write_with_rejects_sample_count_larger_than_slot() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- let err = slot.write_with(128, |_| {}).unwrap_err();- assert!(matches!(err, PcmPoolError::PayloadTooLarge { .. }));- assert_eq!(slot.filled_len(), 0);- }-- #[test]- fn full_acquire_drop_cycle_keeps_accounting_consistent() {- let pool = default_pool();- for _ in 0..4 {- let mut held = Vec::with_capacity(PCM_POOL_CAP);- for _ in 0..PCM_POOL_CAP {- held.push(pool.try_acquire().expect("slot in capacity"));- }- assert!(pool.try_acquire().is_none());- drop(held);- let stats = pool.stats();- assert_eq!(stats.in_flight, 0);- assert_eq!(stats.released, stats.acquired);- }- let stats = pool.stats();- assert_eq!(stats.acquired as usize, PCM_POOL_CAP * 4);- assert_eq!(stats.released as usize, PCM_POOL_CAP * 4);- assert_eq!(stats.in_flight, 0);- }-- #[test]- fn external_parts_release_does_not_abort_accounting() {- let pool = SamplePool::new(2, 64).expect("pool");- let mut slot = pool.try_acquire().expect("slot");- slot.write(&[0.25_f32; 16]).expect("write");- let (ptr, len, owned) = slot.into_external_parts();- assert!(!ptr.is_null());- assert_eq!(len, 16);- drop(owned);- let stats = pool.stats();- assert_eq!(stats.in_flight, 0);- assert_eq!(stats.released, 1);- assert_eq!(stats.acquired, 1);- }-}diff --git a/fluxer_desktop/native/system-hunspell/Cargo.lock b/fluxer_desktop/native/system-hunspell/Cargo.lockindex c6c3624bd..6491206a6 100644--- a/fluxer_desktop/native/system-hunspell/Cargo.lock+++ b/fluxer_desktop/native/system-hunspell/Cargo.lock@@ -112,12 +112,6 @@ dependencies = ["windows-sys 0.61.2",]-[[package]]-name = "fastrand"-version = "2.5.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"-[[package]]name = "find-msvc-tools"version = "0.1.12"@@ -132,7 +126,6 @@ dependencies = ["napi","napi-build","napi-derive",- "tempfile",][[package]]@@ -223,17 +216,6 @@ dependencies = ["slab",]-[[package]]-name = "getrandom"-version = "0.4.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"-dependencies = [- "cfg-if",- "libc",- "r-efi",-]-[[package]]name = "glob"version = "0.3.4"@@ -304,12 +286,6 @@ version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"-[[package]]-name = "linux-raw-sys"-version = "0.12.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"-[[package]]name = "log"version = "0.4.34"@@ -444,12 +420,6 @@ dependencies = ["proc-macro2",]-[[package]]-name = "r-efi"-version = "6.0.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"-[[package]]name = "regex"version = "1.13.1"@@ -500,23 +470,10 @@ dependencies = ["bitflags 2.13.2","errno","libc",- "linux-raw-sys 0.4.15",+ "linux-raw-sys","windows-sys 0.59.0",]-[[package]]-name = "rustix"-version = "1.1.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"-dependencies = [- "bitflags 2.13.2",- "errno",- "libc",- "linux-raw-sys 0.12.1",- "windows-sys 0.61.2",-]-[[package]]name = "semver"version = "1.0.28"@@ -574,19 +531,6 @@ dependencies = ["unicode-ident",]-[[package]]-name = "tempfile"-version = "3.27.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"-dependencies = [- "fastrand",- "getrandom",- "once_cell",- "rustix 1.1.5",- "windows-sys 0.61.2",-]-[[package]]name = "unicode-ident"version = "1.0.26"@@ -608,7 +552,7 @@ dependencies = ["either","home","once_cell",- "rustix 0.38.44",+ "rustix",][[package]]diff --git a/fluxer_desktop/native/system-hunspell/Cargo.toml b/fluxer_desktop/native/system-hunspell/Cargo.tomlindex 07362a98f..7ffd644cc 100644--- a/fluxer_desktop/native/system-hunspell/Cargo.toml+++ b/fluxer_desktop/native/system-hunspell/Cargo.toml@@ -18,6 +18,3 @@ napi-derive = "3.6.7"[build-dependencies]napi-build = "2.4.3"--[dev-dependencies]-tempfile = "3.27"diff --git a/fluxer_desktop/native/system-hunspell/src/lib.rs b/fluxer_desktop/native/system-hunspell/src/lib.rsindex 6cb34cfc2..139c2b5e1 100644--- a/fluxer_desktop/native/system-hunspell/src/lib.rs+++ b/fluxer_desktop/native/system-hunspell/src/lib.rs@@ -274,42 +274,3 @@ fn hunspell_load_error(reason: &str) -> Error {format!("Hunspell load failed: {reason}"),)}--#[cfg(test)]-mod tests {- use super::Dictionary;-- #[test]- fn dictionary_fixture_spells_and_accepts_runtime_words() {- let (dir, aff_path, dic_path) = write_fixture_dictionary("UTF-8");- let mut dict =- Dictionary::load(&aff_path, &dic_path).expect("fixture dictionary should load");-- assert!(dict.spell("cat").unwrap());- assert!(dict.spell("cats").unwrap());- assert!(!dict.spell("Fluxer").unwrap());- dict.add("Fluxer").unwrap();- assert!(dict.spell("Fluxer").unwrap());- dict.remove("Fluxer").unwrap();- assert!(!dict.spell("Fluxer").unwrap());-- drop(dir);- }-- fn write_fixture_dictionary(encoding: &str) -> (tempfile::TempDir, String, String) {- let dir = tempfile::tempdir().unwrap();- let aff_path = dir.path().join("fixture.aff");- let dic_path = dir.path().join("fixture.dic");- std::fs::write(- &aff_path,- format!("SET {encoding}\n\nSFX S Y 1\nSFX S 0 s [^sxzhy]\n"),- )- .unwrap();- std::fs::write(&dic_path, "2\ncat/S\nprogram/S\n").unwrap();- (- dir,- aff_path.display().to_string(),- dic_path.display().to_string(),- )- }-}diff --git a/fluxer_desktop/native/webauthn/src/common.rs b/fluxer_desktop/native/webauthn/src/common.rsindex 242e98f53..d2fa3873c 100644--- a/fluxer_desktop/native/webauthn/src/common.rs+++ b/fluxer_desktop/native/webauthn/src/common.rs@@ -162,98 +162,3 @@ pub fn build_attestation_object(append_cbor_bytes(&mut out, auth_data);Ok(out)}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn attachment_from_transport_matches_legacy() {- assert_eq!(- Some("platform"),- attachment_from_transport(TRANSPORT_INTERNAL)- );- assert_eq!(- Some("platform"),- attachment_from_transport(TRANSPORT_INTERNAL | TRANSPORT_USB)- );- assert_eq!(- Some("cross-platform"),- attachment_from_transport(TRANSPORT_USB)- );- assert_eq!(Some("cross-platform"), attachment_from_transport(0x2));- assert_eq!(Some("cross-platform"), attachment_from_transport(0x4));- assert_eq!(None, attachment_from_transport(0));- }-- #[test]- fn cbor_len_small() {- let mut out = Vec::new();- append_cbor_len(&mut out, 5, 3);- assert_eq!(out, vec![(5 << 5) | 3]);- }-- #[test]- fn cbor_text_encodes_short_string() {- let mut out = Vec::new();- append_cbor_text(&mut out, "fmt");-- assert_eq!(out, vec![0x63, b'f', b'm', b't']);- }-- #[test]- fn cbor_bytes_one_byte_length() {- let payload = vec![0xab; 24];- let mut out = Vec::new();- append_cbor_bytes(&mut out, &payload);- assert_eq!(out[0], (2 << 5) | 24);- assert_eq!(out[1], 24);- assert_eq!(&out[2..], &payload[..]);- }-- #[test]- fn cbor_len_two_byte_form() {- let mut out = Vec::new();- append_cbor_len(&mut out, 2, 0x0123);- assert_eq!(out, vec![(2 << 5) | 25, 0x01, 0x23]);- }-- #[test]- fn cbor_len_four_byte_form() {- let mut out = Vec::new();- append_cbor_len(&mut out, 2, 0x0001_0203);- assert_eq!(out, vec![(2 << 5) | 26, 0x00, 0x01, 0x02, 0x03]);- }-- #[test]- fn build_attestation_object_empty_att_stmt() {- let auth_data = [0x01u8, 0x02, 0x03];- let bytes = build_attestation_object("none", &auth_data, &[]).unwrap();-- let expected: Vec<u8> = vec![- 0xa3, 0x63, b'f', b'm', b't', 0x64, b'n', b'o', b'n', b'e', 0x67, b'a', b't', b't',- b'S', b't', b'm', b't', 0xa0, 0x68, b'a', b'u', b't', b'h', b'D', b'a', b't', b'a',- 0x43, 0x01, 0x02, 0x03,- ];- assert_eq!(bytes, expected);- }-- #[test]- fn build_attestation_object_passes_through_packed_att_stmt() {- let att_stmt = [- 0xa2u8, 0x63, b'a', b'l', b'g', 0x26, 0x63, b's', b'i', b'g', 0x41, 0x00,- ];- let auth_data = [0xaau8; 4];- let bytes = build_attestation_object("packed", &auth_data, &att_stmt).unwrap();-- let needle = att_stmt.as_slice();- let position = bytes- .windows(needle.len())- .position(|w| w == needle)- .expect("att_stmt must be spliced unmodified");-- assert!(position >= 8);- let header = &bytes[position - 8..position];- assert_eq!(header, b"\x67attStmt");- }-}