llmposter 0.4.4

Drop-in mock server for OpenAI, Anthropic & Gemini APIs — library or standalone CLI. SSE streaming, tool calling, OAuth2, failure injection, streaming chaos, stateful scenarios, request capture, hot-reload, response templating. Test LLM apps without burning tokens.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use llmposter::cli::{run, run_with_output, Cli};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};

fn unique_temp_dir(prefix: &str) -> PathBuf {
    static NEXT_ID: AtomicUsize = AtomicUsize::new(0);
    let dir = std::env::temp_dir().join(format!(
        "{}_{}_{}",
        prefix,
        std::process::id(),
        NEXT_ID.fetch_add(1, Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn fixtures_dir() -> PathBuf {
    let dir = unique_temp_dir("llmposter_cli_test");
    std::fs::write(
        dir.join("test.yaml"),
        "fixtures:\n  - match:\n      user_message: hello\n    response:\n      content: world",
    )
    .unwrap();
    dir
}

fn empty_dir() -> PathBuf {
    unique_temp_dir("llmposter_cli_test_empty")
}

#[tokio::test]
async fn should_validate_good_fixtures() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: true,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_none()); // validate returns None (no server)
}

#[tokio::test]
async fn should_fail_validate_empty_dir() {
    let cli = Cli {
        fixtures: empty_dir(),
        validate: true,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_err());
    assert!(result
        .unwrap_err()
        .to_string()
        .contains("No fixtures found"));
}

#[tokio::test]
async fn should_fail_nonexistent_path() {
    let cli = Cli {
        fixtures: unique_temp_dir("llmposter_cli_test_missing").join("fixtures.yaml"),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn should_start_server_and_respond() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_ok());
    let server = result.unwrap().expect("should return server");

    let client = reqwest::Client::new();
    let resp = client
        .post(format!("{}/v1/chat/completions", server.url()))
        .json(&serde_json::json!({
            "model": "test",
            "messages": [{"role": "user", "content": "hello"}]
        }))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["choices"][0]["message"]["content"], "world");
}

#[cfg(feature = "watch")]
#[tokio::test]
async fn should_start_server_with_watch_flag() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        watch: true,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    assert!(result.is_ok());
    let text = String::from_utf8(output).unwrap();
    assert!(
        text.contains("Watching"),
        "expected 'Watching' line in output, got: {}",
        text
    );
}

#[cfg(unix)]
#[tokio::test]
async fn should_advertise_sighup_hint_in_cli_output() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    assert!(result.is_ok());
    let text = String::from_utf8(output).unwrap();
    assert!(
        text.contains("SIGHUP"),
        "expected SIGHUP hint, got: {}",
        text
    );
}

#[tokio::test]
async fn should_start_server_with_verbose() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: true,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_some());
}

#[tokio::test]
async fn should_validate_single_file() {
    let dir = fixtures_dir();
    let file = dir.join("test.yaml");
    let cli = Cli {
        fixtures: file,
        validate: true,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let result = run(&cli).await;
    assert!(result.is_ok());
}

// ===========================================================================
// Output capture tests using run_with_output
// ===========================================================================

#[tokio::test]
async fn should_output_validated_message() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: true,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    assert!(result.is_ok());

    let text = String::from_utf8(output).unwrap();
    assert!(
        text.contains("Validated 1 fixtures successfully"),
        "expected validation message, got: {}",
        text
    );
}

#[tokio::test]
async fn should_output_listening_message() {
    let cli = Cli {
        fixtures: fixtures_dir(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    assert!(result.is_ok());

    let text = String::from_utf8(output).unwrap();
    assert!(
        text.contains("llmposter listening on"),
        "expected listening message, got: {}",
        text
    );
    assert!(
        text.contains("Press Ctrl+C to stop"),
        "expected Ctrl+C hint, got: {}",
        text
    );
}

#[tokio::test]
async fn should_output_empty_fixtures_warning() {
    // Create a dir with a valid YAML that has no fixtures
    let dir = unique_temp_dir("llmposter_cli_test_warn");
    std::fs::write(dir.join("empty.yaml"), "fixtures: []").unwrap();

    let cli = Cli {
        fixtures: dir,
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    assert!(result.is_ok());

    let text = String::from_utf8(output).unwrap();
    assert!(
        text.contains("Warning: no fixtures loaded"),
        "expected warning, got: {}",
        text
    );
    std::fs::remove_dir_all(&cli.fixtures).ok();
}

#[tokio::test]
async fn should_bind_to_ipv6_address() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0, // random port
        bind: "::1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut output = Vec::new();
    let result = run_with_output(&cli, &mut output).await;
    // Skip gracefully if IPv6 is not available on this host (e.g. Docker, some CI),
    // but fail hard on bind-address formatting bugs (regression guard).
    if let Err(ref e) = result {
        let msg = e.to_string();
        assert!(
            !msg.contains("invalid") && !msg.contains("malformed"),
            "IPv6 bind address was malformed (not a host issue): {msg}"
        );
        eprintln!("skipping: IPv6 not available on this host: {msg}");
        std::fs::remove_dir_all(&dir).ok();
        return;
    }
    let server = result.unwrap().unwrap();
    let url = server.url();
    // IPv6 URL should contain [::1]
    assert!(url.contains("[::1]"), "expected IPv6 URL, got: {}", url);
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_warn_on_empty_fixtures_dir() {
    let dir = unique_temp_dir("llmposter_cli_empty");
    // Empty dir — no YAML files
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    let result = run_with_output(&cli, &mut buf).await;
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("Warning: no fixtures loaded"),
        "expected empty-dir warning, got: {}",
        output
    );
    // Server still starts (just with no fixtures)
    assert!(result.is_ok());
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_accept_non_ip_bind_address() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0,
        bind: "localhost".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    let result = run_with_output(&cli, &mut buf).await;
    // "localhost" is not parseable as IpAddr, so hits the fallback format path
    assert!(result.is_ok());
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_accept_socket_address_with_embedded_port() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 9999, // should be ignored when bind is a full socket address
        bind: "127.0.0.1:0".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    let result = run_with_output(&cli, &mut buf).await;
    assert!(result.is_ok());
    let output = String::from_utf8_lossy(&buf);
    // Port should NOT be 9999 — the embedded :0 means OS-assigned
    assert!(
        !output.contains(":9999"),
        "embedded port should take precedence over --port"
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_warn_when_port_ignored_for_socket_addr_bind() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 5150, // non-default, should trigger warning
        bind: "127.0.0.1:0".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    let result = run_with_output(&cli, &mut buf).await;
    assert!(result.is_ok());
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("--port 5150 ignored"),
        "expected port-ignored warning, got: {}",
        output
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_accept_hostname_with_port() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 5150, // non-default, should trigger warning
        bind: "localhost:0".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    let result = run_with_output(&cli, &mut buf).await;
    assert!(result.is_ok());
    let output = String::from_utf8_lossy(&buf);
    assert!(
        output.contains("--port 5150 ignored"),
        "expected port-ignored warning for hostname:port, got: {}",
        output
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_fallback_for_invalid_hostname_port() {
    let dir = fixtures_dir();
    // ":notaport" — rsplit gives host="" which fails the !host.is_empty() check
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0,
        bind: ":notaport".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
    };
    let mut buf = Vec::new();
    // This will likely fail to bind (":notaport:0" is invalid), but the
    // bind_addr construction path is exercised either way.
    let _ = run_with_output(&cli, &mut buf).await;
    std::fs::remove_dir_all(&dir).ok();
}