libchat/crates/client/tests/alice_and_bob.rs
osmaczko 6db3363aad
wip
2026-03-26 21:34:09 +01:00

73 lines
2.7 KiB
Rust

use client::{ChatClient, ContentData, ConversationIdOwned, InMemoryDelivery};
use std::sync::Arc;
fn pop_and_receive(
sender: &mut ChatClient<InMemoryDelivery>,
receiver: &mut ChatClient<InMemoryDelivery>,
) -> Option<ContentData> {
let raw = sender.delivery_mut().inbox.pop_front().expect("expected envelope");
receiver.receive(&raw).expect("receive failed")
}
#[test]
fn alice_bob_message_exchange() {
let mut alice = ChatClient::new("alice", InMemoryDelivery::default());
let mut bob = ChatClient::new("bob", InMemoryDelivery::default());
// Exchange intro bundles out-of-band
let bob_bundle = bob.create_intro_bundle().unwrap();
// Alice initiates conversation with Bob
let alice_convo_id = alice
.create_conversation(&bob_bundle, b"hello bob")
.unwrap();
// Bob receives Alice's initial message
let content = pop_and_receive(&mut alice, &mut bob).expect("expected content");
assert_eq!(content.data, b"hello bob");
assert!(content.is_new_convo);
let bob_convo_id: ConversationIdOwned = Arc::from(content.conversation_id.as_str());
// Bob replies
bob.send_message(&bob_convo_id, b"hi alice").unwrap();
let content = pop_and_receive(&mut bob, &mut alice).expect("expected content");
assert_eq!(content.data, b"hi alice");
assert!(!content.is_new_convo);
// Multiple back-and-forth rounds
for i in 0u8..5 {
let msg = format!("msg {i}");
alice.send_message(&alice_convo_id, msg.as_bytes()).unwrap();
let content = pop_and_receive(&mut alice, &mut bob).expect("expected content");
assert_eq!(content.data, msg.as_bytes());
let reply = format!("reply {i}");
bob.send_message(&bob_convo_id, reply.as_bytes()).unwrap();
let content = pop_and_receive(&mut bob, &mut alice).expect("expected content");
assert_eq!(content.data, reply.as_bytes());
}
// Both sides have exactly one conversation
assert_eq!(alice.list_conversations().unwrap().len(), 1);
assert_eq!(bob.list_conversations().unwrap().len(), 1);
}
#[test]
fn open_persistent_client() {
use client::StorageConfig;
let dir = tempfile::tempdir().unwrap();
let db_path = dir.path().join("test.db").to_string_lossy().to_string();
let config = StorageConfig::File(db_path);
let client1 = ChatClient::open("alice", config.clone(), InMemoryDelivery::default()).unwrap();
let name1 = client1.installation_name().to_string();
drop(client1);
let client2 = ChatClient::open("alice", config, InMemoryDelivery::default()).unwrap();
let name2 = client2.installation_name().to_string();
assert_eq!(name1, name2, "installation name should persist across restarts");
}