crates/edge/cli/tests/bench.rs 5.9 KiB 181 lines Raw
1 //! The bench times work and the command line refuses an empty run.2 3 use std::io::{BufRead, BufReader, Write};4 use std::os::unix::net::UnixListener;5 use std::path::{Path, PathBuf};6 use std::process::Command;7 use std::sync::atomic::{AtomicU64, Ordering};8 use std::thread;9 use std::time::Duration;10 11 use inf3r_cli::bench::{Bench, run};12 use inf3r_cli::cli::parse_args;13 use inf3r_cli::http::CliError;14 15 #[test]16 fn one_millisecond_work_gives_a_p50_in_range() {17     let mut work = || {18         std::thread::sleep(Duration::from_millis(1));19         Ok(())20     };21     let sample = run(Bench { runs: 5, warmup: 1 }, &mut work).expect("a sample");22     assert_eq!(sample.runs, 5);23     assert!(24         (1.0..50.0).contains(&sample.p50_ms),25         "p50 is {}",26         sample.p50_ms27     );28 }29 30 #[test]31 fn a_runs_count_of_zero_is_a_usage_error() {32     let why = parse_args(["bench", "chat", "--runs", "0", "--body", "{}"].map(String::from))33         .expect_err("no runs");34     assert!(matches!(why, CliError::Usage(_)), "{why}");35     assert_eq!(why.exit_code(), 2);36 }37 38 #[test]39 fn a_runs_count_above_the_ceiling_is_a_usage_error() {40     let why = parse_args(["bench", "chat", "--runs", "1001", "--body", "{}"].map(String::from))41         .expect_err("too many runs");42     assert!(matches!(why, CliError::Usage(_)), "{why}");43     assert_eq!(why.exit_code(), 2);44 }45 46 /// A unique path under the temporary directory.47 fn socket_path() -> PathBuf {48     static NEXT: AtomicU64 = AtomicU64::new(0);49     let n = NEXT.fetch_add(1, Ordering::Relaxed);50     std::env::temp_dir().join(format!("inf3r-bench-{}-{n}.sock", std::process::id()))51 }52 53 /// Starts a server that answers the table, then one canonical POST route.54 fn serve_once(body: String, capability: &'static str, route: &'static str) -> PathBuf {55     let path = socket_path();56     let listener = UnixListener::bind(&path).expect("bind a temporary socket");57     let served = path.clone();58     thread::spawn(move || {59         let (mut stream, _) = listener.accept().expect("accept the table request");60         let mut reader = BufReader::new(stream.try_clone().expect("a file"));61         let mut request = String::new();62         reader63             .read_line(&mut request)64             .expect("read the table request line");65         assert!(66             request.starts_with("GET /capabilities HTTP/1.1\r\n"),67             "{request}"68         );69         let table = format!(70             r#"{{"capabilities":[{{"name":"{capability}","route":"{route}","parts":[],"channels":[],"stream":true}}]}}"#71         );72         let reply = format!(73             "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{table}",74             table.len()75         );76         stream.write_all(reply.as_bytes()).expect("write the table");77         stream.flush().expect("flush the table");78         drop(reader);79         drop(stream);80 81         let (mut stream, _) = listener.accept().expect("accept the job request");82         let mut reader = BufReader::new(stream.try_clone().expect("a file"));83         let mut request = String::new();84         reader85             .read_line(&mut request)86             .expect("read the job request line");87         assert!(88             request.starts_with(&format!("POST {route} HTTP/1.1\r\n")),89             "{request}"90         );91         let reply = format!(92             "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\n\r\n{body}",93             body.len()94         );95         stream.write_all(reply.as_bytes()).expect("write the reply");96         stream.flush().expect("flush the reply");97         let _ = std::fs::remove_file(served);98     });99     path100 }101 102 /// The SSE body of one completed job with a usage map.103 fn done_frame(usage: &str) -> String {104     format!(105         "data: {{\"seq\":1,\"body\":{{\"t\":\"done\",\"outcome\":\"completed\",\"artifacts\":[],\"usage\":{usage}}}}}\n\ndata: [DONE]\n\n"106     )107 }108 109 /// The SSE body of one usage event with flat counts.110 fn usage_frame(usage: &str) -> String {111     format!("data: {{\"seq\":20,\"body\":{{\"t\":\"usage\",{usage}}}}}\n\ndata: [DONE]\n\n")112 }113 114 /// Runs the binary against one fake socket.115 fn bench_capability(path: &Path, capability: &str) -> String {116     let output = Command::new(env!("CARGO_BIN_EXE_inf3r"))117         .arg("--socket")118         .arg(path)119         .args(["bench", capability, "--runs", "1", "--body", "{}"])120         .output()121         .expect("the binary runs");122     assert!(123         output.status.success(),124         "{}",125         String::from_utf8_lossy(&output.stderr)126     );127     String::from_utf8(output.stdout).expect("the bench prints UTF-8")128 }129 130 fn bench(path: &Path) -> String {131     bench_capability(path, "chat")132 }133 134 #[test]135 fn a_done_frame_with_all_three_numbers_prints_the_usage_line() {136     let path = serve_once(137         done_frame(r#"{"tokens_out":12,"first_token_ms":34,"tokens_per_s":567}"#),138         "chat",139         "/chat",140     );141     let stdout = bench(&path);142     assert!(143         stdout144             .lines()145             .any(|line| line == "tokens_out=12 first_token_ms=34 tokens_per_s=5.67"),146         "{stdout}"147     );148 }149 150 #[test]151 fn a_usage_event_with_flat_counts_prints_the_usage_line() {152     let path = serve_once(153         usage_frame(r#""tokens_out":12,"first_token_ms":34,"tokens_per_s":567"#),154         "chat",155         "/chat",156     );157     let stdout = bench(&path);158     assert!(159         stdout160             .lines()161             .any(|line| line == "tokens_out=12 first_token_ms=34 tokens_per_s=5.67"),162         "{stdout}"163     );164 }165 166 #[test]167 fn a_done_frame_without_usage_prints_no_usage_line() {168     let path = serve_once(done_frame("{}"), "chat", "/chat");169     let stdout = bench(&path);170     assert!(171         !stdout.lines().any(|line| line.starts_with("tokens_out=")),172         "{stdout}"173     );174 }175 176 #[test]177 fn a_capability_key_is_resolved_through_the_capabilities_route() {178     let path = serve_once(done_frame("{}"), "image-gen", "/image/generate");179     let stdout = bench_capability(&path, "image-gen");180     assert!(stdout.contains("runs=1"), "{stdout}");181 }