mod common;
use std::io::Write;
use std::process::{Command, Output, Stdio};
use common::{Answer, Home, daemon};
use second_brain_sync::protocol::{Hello, RefusedLine, SyncHeader};
const MISMATCH: &str = "machine-a holds a different sync identity; pair it with `sb pair`";
fn identity_refusal(path: &str) -> (u16, String) {
if path == "/v1/sync/version" {
return (200, serde_json::to_string(&SyncHeader::local()).unwrap());
}
(
409,
serde_json::json!({"error": MISMATCH, "identity": true}).to_string(),
)
}
fn sb(home: &Home, api: &str, args: &[&str], stdin: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_sb"))
.args(args)
.env("HOME", home.path())
.env("SECOND_BRAIN_API", api)
.env("SECOND_BRAIN_BIND", "127.0.0.1:9")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(stdin.as_bytes())
.unwrap();
child.wait_with_output().unwrap()
}
fn expected_line() -> String {
format!(
"{}\n",
RefusedLine {
error: MISMATCH.to_string(),
identity: true,
}
.to_line()
)
}
#[test]
fn an_export_the_daemon_refuses_for_identity_writes_the_refused_line_and_fails() {
let home = Home::new();
let api = daemon(Answer::Routed(identity_refusal));
let output = sb(&home, &api.base, &["sync-export", "--after-seq", "0"], "");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "{stderr}");
assert!(stderr.contains("sb pair"), "{stderr}");
assert_eq!(String::from_utf8_lossy(&output.stdout), expected_line());
}
#[test]
fn an_import_whose_hello_the_daemon_refuses_for_identity_answers_with_the_refused_line() {
let home = Home::new();
let api = daemon(Answer::Routed(identity_refusal));
let header = SyncHeader {
hello: Some(Hello {
machine_id: "machine-a".to_string(),
wall_micros: 0,
synced: false,
cursor: None,
held_origin_seq: None,
keys: None,
peer_in: None,
log_floor: 0,
head: 0,
applied: None,
merging: None,
}),
..SyncHeader::local()
};
let output = sb(
&home,
&api.base,
&["sync-import"],
&format!("{}\n", header.to_line()),
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!output.status.success(), "{stderr}");
assert!(stderr.contains("sb pair"), "{stderr}");
assert_eq!(String::from_utf8_lossy(&output.stdout), expected_line());
assert!(
api.requests()
.iter()
.all(|r| !r.target.contains("/v1/sync/import")),
"a refused hello imports nothing"
);
}