llmposter 0.4.8

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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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("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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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();
}

// DEFAULT_PORT is 2112.  Tests below use port == 2112 so the "port ignored"
// condition is FALSE — exercising the closing `}` of those if-blocks.

#[tokio::test]
async fn should_not_warn_when_port_matches_default_with_socket_addr_bind() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 2112, // equals DEFAULT_PORT — condition is false, no warning
        bind: "127.0.0.1:0".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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 2112 ignored"),
        "should NOT warn when port equals default, got: {}",
        output
    );
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn should_not_warn_when_port_matches_default_with_hostname_port() {
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 2112, // equals DEFAULT_PORT — condition is false, no warning
        bind: "localhost:0".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: 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 2112 ignored"),
        "should NOT warn when port equals default, got: {}",
        output
    );
    std::fs::remove_dir_all(&dir).ok();
}

// Writer that always fails — used to exercise the `)?;` error-propagation
// paths inside `writeln!` calls in run_with_output.
struct AlwaysFailWriter;
impl std::io::Write for AlwaysFailWriter {
    fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
        Err(std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "simulated write failure",
        ))
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

// Writer that succeeds for the first N complete `writeln!` calls (detected by
// newline bytes) then fails — used to exercise `)?;` error-propagation paths
// for writeln! calls that appear after the first output line.
struct FailAfterNNewlines {
    completed: usize,
    limit: usize,
}
impl std::io::Write for FailAfterNNewlines {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if self.completed >= self.limit {
            return Err(std::io::Error::new(
                std::io::ErrorKind::BrokenPipe,
                "simulated write failure",
            ));
        }
        // Count newlines to track completed writeln! calls.
        let newlines = buf.iter().filter(|&&b| b == b'\n').count();
        self.completed += newlines;
        Ok(buf.len())
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[tokio::test]
async fn should_propagate_write_error_on_empty_fixtures_warning() {
    // With an empty fixture dir the first writeln! is the "no fixtures loaded"
    // warning at line 141-145.  AlwaysFailWriter makes that write fail, so the
    // `)?;` error-propagation path (line 145) is exercised.
    let dir = unique_temp_dir("llmposter_cli_test_fail_write");
    std::fs::write(dir.join("empty.yaml"), "fixtures: []").unwrap();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: false,
    };
    let mut writer = AlwaysFailWriter;
    let result = run_with_output(&cli, &mut writer).await;
    assert!(result.is_err(), "expected Err from write failure");
    std::fs::remove_dir_all(&dir).ok();
}

#[cfg(unix)]
#[tokio::test]
async fn should_propagate_write_error_on_sighup_writeln() {
    // The output sequence for a non-watch server on unix is:
    //   1. "llmposter listening on ..."  ← first writeln (1 newline)
    //   2. "Send SIGHUP (kill -HUP ...) ← second writeln
    //   3. "Press Ctrl+C to stop"
    // FailAfterNNewlines(limit=1) lets the first writeln complete, then fails
    // at the start of the SIGHUP writeln, exercising the `)?;` path on line 178.
    let dir = fixtures_dir();
    let cli = Cli {
        fixtures: dir.clone(),
        validate: false,
        port: 0,
        bind: "127.0.0.1".to_string(),
        verbose: false,
        #[cfg(feature = "watch")]
        watch: false,
        capture_capacity: 1000,
        diagnostics: false,
        #[cfg(feature = "ui")]
        ui: false,
    };
    let mut writer = FailAfterNNewlines {
        completed: 0,
        limit: 1,
    };
    let result = run_with_output(&cli, &mut writer).await;
    assert!(result.is_err(), "expected Err from write failure");
    std::fs::remove_dir_all(&dir).ok();
}