zpinger 0.7.0

Async, protocol-agnostic latency probe library: TCP / UDP / HTTP(S) / WebSocket / DNS / MQTT / gRPC / HLS / TLS / NTP / STUN / TURN / RTSP / RTMP / QUIC
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
use std::net::TcpListener;
use std::sync::Arc;
use std::time::Duration;

use zpinger::Pinger;

fn closed_tcp_addr() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    drop(listener);
    addr.to_string()
}

#[tokio::test]
async fn resolve_returns_at_least_one_address() {
    let addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    let resolved = zpinger::resolve(&addr.to_string()).await;
    assert!(!resolved.is_empty());
}

#[tokio::test]
async fn resolve_returns_empty_on_unresolvable_input() {
    // No DNS, no panic — empty Vec lets the CLI keep going so the
    // real pinger can surface the actual error.
    let resolved = zpinger::resolve("definitely-not-a-real-host.invalid:1").await;
    assert!(resolved.is_empty());
}

#[tokio::test]
async fn tcp_pinger_struct_succeeds() {
    let addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    zpinger::TcpPinger::new(addr.to_string())
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn tcp_pinger_via_timed_helper() {
    let addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    let p = zpinger::TcpPinger::new(addr.to_string());
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn tcp_pinger_with_custom_timeout() {
    let addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    let p = zpinger::TcpPinger::new(addr.to_string()).with_timeout(Duration::from_secs(1));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn udp_pinger_struct_succeeds() {
    let addr = testserver::start_udp_echo("127.0.0.1:0").unwrap();
    zpinger::UdpPinger::new(addr.to_string())
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn level4_pingers_usable_as_trait_objects() {
    let tcp_addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    let udp_addr = testserver::start_udp_echo("127.0.0.1:0").unwrap();
    let pingers: Vec<Box<dyn Pinger>> = vec![
        Box::new(zpinger::TcpPinger::new(tcp_addr.to_string())),
        Box::new(zpinger::UdpPinger::new(udp_addr.to_string())),
    ];
    for p in &pingers {
        p.ping().await.unwrap();
    }
}

#[tokio::test]
async fn tcp_pinger_struct_fails_on_closed_port() {
    let p = zpinger::TcpPinger::new(closed_tcp_addr());
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn http_pinger_struct_succeeds() {
    let addr = testserver::start_http_ok("127.0.0.1:0").unwrap();
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, format!("{}/x", addr));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn http_pinger_all_methods_via_struct() {
    let addr = testserver::start_http_ok("127.0.0.1:0").unwrap();
    let target = format!("{}/x", addr);
    for method in [
        zpinger::HttpMethod::Connect,
        zpinger::HttpMethod::Get,
        zpinger::HttpMethod::Post,
        zpinger::HttpMethod::Put,
        zpinger::HttpMethod::Delete,
        zpinger::HttpMethod::Patch,
    ] {
        zpinger::HttpPinger::new(method, target.clone())
            .ping()
            .await
            .unwrap_or_else(|e| panic!("{:?} failed: {}", method, e));
    }
}

#[tokio::test]
async fn http_pinger_via_timed_helper() {
    let addr = testserver::start_http_ok("127.0.0.1:0").unwrap();
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, format!("{}/x", addr));
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn http_pinger_rejects_unknown_scheme() {
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, "ftp://example.com:21/foo");
    let err = p
        .ping()
        .await
        .expect_err("non-http scheme must be rejected");
    let msg = err.to_string();
    assert!(msg.contains("ftp"), "unexpected error message: {msg}");
}

#[tokio::test]
async fn http_pinger_https_succeeds_with_trusted_cert() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("https://localhost:{}/anything", server.addr.port());
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, target)
        .with_tls_config(server.client_config);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn http_pinger_https_all_methods_via_struct() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("https://localhost:{}/x", server.addr.port());
    for method in [
        zpinger::HttpMethod::Connect,
        zpinger::HttpMethod::Get,
        zpinger::HttpMethod::Post,
        zpinger::HttpMethod::Put,
        zpinger::HttpMethod::Delete,
        zpinger::HttpMethod::Patch,
    ] {
        zpinger::HttpPinger::new(method, target.clone())
            .with_tls_config(Arc::clone(&server.client_config))
            .ping()
            .await
            .unwrap_or_else(|e| panic!("{method:?} failed: {e}"));
    }
}

#[tokio::test]
async fn http_pinger_succeeds_without_explicit_port_on_localhost_default() {
    // Run an HTTP server on the platform's HTTP default port (80) is
    // not portable in tests, so instead we verify the URI parser +
    // pinger handle the implicit-port path: when the URL has no
    // ":port" segment, the pinger must apply the scheme default and
    // not crash. Use a closed default port — the test asserts that
    // we get a connect-level error (port refused) rather than a
    // "missing host" or parser error.
    let target = "http://127.0.0.1/anything";
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, target);
    let err = p
        .ping()
        .await
        .expect_err("port 80 should be refused on this host");
    let msg = err.to_string().to_lowercase();
    assert!(
        !msg.contains("missing host") && !msg.contains("invalid"),
        "unexpected error type for implicit-port path: {msg}"
    );
}

#[tokio::test]
async fn http_pinger_https_fails_without_trust_anchor() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("https://localhost:{}/anything", server.addr.port());
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, target);
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn http_pinger_rejects_non_http_response() {
    let addr = testserver::start_tcp_echo("127.0.0.1:0").unwrap();
    let p = zpinger::HttpPinger::new(zpinger::HttpMethod::Get, format!("{}/x", addr));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn ws_pinger_succeeds_on_ws_server() {
    let addr = testserver::start_ws_ok("127.0.0.1:0").unwrap();
    let target = format!("ws://{addr}/");
    zpinger::WebSocketPinger::new(target).ping().await.unwrap();
}

#[tokio::test]
async fn ws_pinger_via_timed_helper() {
    let addr = testserver::start_ws_ok("127.0.0.1:0").unwrap();
    let target = format!("ws://{addr}/");
    let p = zpinger::WebSocketPinger::new(target);
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn ws_pinger_fails_on_closed_port() {
    let target = format!("ws://{}/", closed_tcp_addr());
    let p = zpinger::WebSocketPinger::new(target);
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn ws_pinger_rejects_non_ws_scheme() {
    let p = zpinger::WebSocketPinger::new("http://example.com:80/");
    let err = p.ping().await.expect_err("non-ws scheme must be rejected");
    let msg = err.to_string();
    assert!(msg.contains("http"), "unexpected error message: {msg}");
}

#[tokio::test]
async fn wss_pinger_succeeds_with_trusted_cert() {
    let server = testserver::start_wss_ok("127.0.0.1:0").unwrap();
    let target = format!("wss://localhost:{}/", server.addr.port());
    let p = zpinger::WebSocketPinger::new(target).with_tls_config(server.client_config);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn wss_pinger_fails_without_trust_anchor() {
    let server = testserver::start_wss_ok("127.0.0.1:0").unwrap();
    let target = format!("wss://localhost:{}/", server.addr.port());
    let p = zpinger::WebSocketPinger::new(target);
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn ws_pinger_usable_as_trait_object() {
    let addr = testserver::start_ws_ok("127.0.0.1:0").unwrap();
    let target = format!("ws://{addr}/");
    let p: Box<dyn Pinger> = Box::new(zpinger::WebSocketPinger::new(target));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn dns_pinger_succeeds_on_test_server() {
    let addr = testserver::start_dns_ok("127.0.0.1:0").unwrap();
    let p = zpinger::DnsPinger::new(addr.to_string(), "example.com");
    p.ping().await.unwrap();
}

#[tokio::test]
async fn dns_pinger_via_timed_helper() {
    let addr = testserver::start_dns_ok("127.0.0.1:0").unwrap();
    let p = zpinger::DnsPinger::new(addr.to_string(), "example.com");
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn dns_pinger_with_record_type() {
    let addr = testserver::start_dns_ok("127.0.0.1:0").unwrap();
    let p = zpinger::DnsPinger::new(addr.to_string(), "example.com")
        .with_record_type(zpinger::RecordType::Aaaa);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn dns_pinger_rejects_empty_query() {
    let addr = testserver::start_dns_ok("127.0.0.1:0").unwrap();
    let p = zpinger::DnsPinger::new(addr.to_string(), "");
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn dns_pinger_times_out_on_silent_port() {
    // UDP has no "connection refused" — bind a port that never responds
    // and confirm DnsPinger surfaces the timeout instead of hanging.
    let silent = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = silent.local_addr().unwrap();
    let p = zpinger::DnsPinger::new(addr.to_string(), "example.com")
        .with_timeout(Duration::from_millis(150));
    assert!(p.ping().await.is_err());
    drop(silent);
}

#[tokio::test]
async fn dns_pinger_usable_as_trait_object() {
    let addr = testserver::start_dns_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::DnsPinger::new(addr.to_string(), "example.com"));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtt_pinger_succeeds_against_test_broker() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtt://{addr}"));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtt_pinger_via_timed_helper() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtt://{addr}"));
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn mqtt_pinger_with_custom_client_id() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtt://{addr}")).with_client_id("custom-test");
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtt_pinger_schemeless_uses_plain_path() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(addr.to_string());
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtt_pinger_rejects_unknown_scheme() {
    let p = zpinger::MqttPinger::new("ftp://example.com:21");
    let err = p
        .ping()
        .await
        .expect_err("non-mqtt scheme must be rejected up front");
    assert!(
        err.to_string().contains("ftp"),
        "unexpected error message: {err}"
    );
}

#[tokio::test]
async fn mqtt_pinger_fails_on_closed_port() {
    let p = zpinger::MqttPinger::new(format!("mqtt://{}", closed_tcp_addr()))
        .with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn mqtt_pinger_v5_succeeds_against_test_broker() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p =
        zpinger::MqttPinger::new(format!("mqtt://{addr}")).with_version(zpinger::MqttVersion::V5);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtts_pinger_v5_succeeds_with_trusted_cert() {
    let server = testserver::start_mqtts_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtts://localhost:{}", server.addr.port()))
        .with_version(zpinger::MqttVersion::V5)
        .with_tls_config(server.client_config);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtt_pinger_usable_as_trait_object() {
    let addr = testserver::start_mqtt_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::MqttPinger::new(format!("mqtt://{addr}")));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtts_pinger_succeeds_with_trusted_cert() {
    let server = testserver::start_mqtts_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtts://localhost:{}", server.addr.port()))
        .with_tls_config(server.client_config);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn mqtts_pinger_fails_without_trust_anchor() {
    let server = testserver::start_mqtts_ok("127.0.0.1:0").unwrap();
    let p = zpinger::MqttPinger::new(format!("mqtts://localhost:{}", server.addr.port()))
        .with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn grpc_pinger_succeeds_against_test_server() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcPinger::new(format!("grpc://localhost:{}", addr.port()));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn grpc_pinger_via_timed_helper() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcPinger::new(format!("grpc://localhost:{}", addr.port()));
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn grpc_pinger_with_service_name() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    // testserver only marks the overall ("") service as SERVING. A
    // specific service name should come back NOT_SERVING (or
    // unknown), so the ping should fail — proving with_service
    // actually reaches the wire.
    let p = zpinger::GrpcPinger::new(format!("grpc://localhost:{}", addr.port()))
        .with_service("nonexistent.Service");
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn grpc_pinger_fails_on_closed_port() {
    let p = zpinger::GrpcPinger::new(format!("grpc://{}", closed_tcp_addr()))
        .with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn grpc_pinger_usable_as_trait_object() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::GrpcPinger::new(format!(
        "grpc://localhost:{}",
        addr.port()
    )));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn grpcs_pinger_succeeds_with_trusted_cert() {
    let server = testserver::start_grpcs_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcPinger::new(format!("grpcs://localhost:{}", server.addr.port()))
        .with_ca_cert(server.ca_pem);
    p.ping().await.unwrap();
}

#[tokio::test]
async fn grpcs_pinger_fails_without_trust_anchor() {
    let server = testserver::start_grpcs_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcPinger::new(format!("grpcs://localhost:{}", server.addr.port()))
        .with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn grpc_stream_pinger_succeeds_against_test_server() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcStreamPinger::new(format!("grpc://localhost:{}", addr.port()));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn grpc_stream_pinger_via_timed_helper() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p = zpinger::GrpcStreamPinger::new(format!("grpc://localhost:{}", addr.port()));
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn grpc_stream_pinger_fails_on_closed_port() {
    let p = zpinger::GrpcStreamPinger::new(format!("grpc://{}", closed_tcp_addr()))
        .with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn grpc_stream_pinger_usable_as_trait_object() {
    let addr = testserver::start_grpc_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::GrpcStreamPinger::new(format!(
        "grpc://localhost:{}",
        addr.port()
    )));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn hls_pinger_succeeds_on_media_playlist() {
    let addr = testserver::start_hls_ok("127.0.0.1:0").unwrap();
    let url = format!("http://localhost:{}/playlist.m3u8", addr.port());
    zpinger::HlsPinger::new(url).ping().await.unwrap();
}

#[tokio::test]
async fn hls_pinger_succeeds_on_master_playlist() {
    // Master playlist points at media playlist via STREAM-INF; the
    // pinger should follow the variant before fetching the segment.
    let addr = testserver::start_hls_ok("127.0.0.1:0").unwrap();
    let url = format!("http://localhost:{}/master.m3u8", addr.port());
    zpinger::HlsPinger::new(url).ping().await.unwrap();
}

#[tokio::test]
async fn hls_pinger_via_timed_helper() {
    let addr = testserver::start_hls_ok("127.0.0.1:0").unwrap();
    let url = format!("http://localhost:{}/playlist.m3u8", addr.port());
    let p = zpinger::HlsPinger::new(url);
    let elapsed = zpinger::timed(&p).await.unwrap();
    assert!(elapsed > Duration::from_nanos(0));
}

#[tokio::test]
async fn hls_pinger_fails_on_non_m3u8_response() {
    // /anything path returns 404 from start_hls_ok; ping should fail
    // because the first GET doesn't yield a playlist.
    let addr = testserver::start_hls_ok("127.0.0.1:0").unwrap();
    let url = format!("http://localhost:{}/not-here.m3u8", addr.port());
    assert!(zpinger::HlsPinger::new(url).ping().await.is_err());
}

#[tokio::test]
async fn hls_pinger_fails_on_closed_port() {
    let url = format!("http://{}/playlist.m3u8", closed_tcp_addr());
    let p = zpinger::HlsPinger::new(url).with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn hls_pinger_usable_as_trait_object() {
    let addr = testserver::start_hls_ok("127.0.0.1:0").unwrap();
    let url = format!("http://localhost:{}/playlist.m3u8", addr.port());
    let p: Box<dyn Pinger> = Box::new(zpinger::HlsPinger::new(url));
    p.ping().await.unwrap();
}

#[tokio::test]
async fn dns_pinger_rejects_response_with_tampered_question() {
    // Hand-rolled tiny UDP server: receive the query, set QR=1 +
    // RCODE=0 like the real testserver, but corrupt one byte inside
    // the question section before sending the packet back. The
    // pinger's question-echo check must catch this.
    use std::net::UdpSocket;
    use std::thread;

    let server = UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    thread::spawn(move || {
        let mut buf = [0u8; 512];
        if let Ok((n, src)) = server.recv_from(&mut buf) {
            if n >= 14 {
                buf[2] |= 0x80;
                buf[3] &= 0xF0;
                buf[13] ^= 0xFF;
                let _ = server.send_to(&buf[..n], src);
            }
        }
    });

    let p = zpinger::DnsPinger::new(addr.to_string(), "example.com")
        .with_timeout(Duration::from_millis(500));
    let err = p
        .ping()
        .await
        .expect_err("tampered question must be rejected");
    assert!(
        err.to_string().contains("question"),
        "unexpected error message: {err}"
    );
}

// -- TLS handshake pinger -------------------------------------------------

#[tokio::test]
async fn tls_pinger_succeeds_with_trusted_cert() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("localhost:{}", server.addr.port());
    zpinger::TlsPinger::new(target)
        .with_tls_config(server.client_config)
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn tls_pinger_fails_without_trust_anchor() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("localhost:{}", server.addr.port());
    // No `with_tls_config` → defaults to webpki-roots, which doesn't
    // trust the test cert.
    let err = zpinger::TlsPinger::new(target)
        .with_timeout(Duration::from_secs(2))
        .ping()
        .await
        .expect_err("should fail without trust anchor");
    let msg = err.to_string().to_lowercase();
    assert!(
        msg.contains("certificate") || msg.contains("trust") || msg.contains("unknown"),
        "unexpected TLS error: {err}"
    );
}

#[tokio::test]
async fn tls_pinger_fails_on_closed_port() {
    let target = closed_tcp_addr();
    let p = zpinger::TlsPinger::new(target).with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn tls_pinger_usable_as_trait_object() {
    let server = testserver::start_https_ok("127.0.0.1:0").unwrap();
    let target = format!("localhost:{}", server.addr.port());
    let p: Box<dyn Pinger> =
        Box::new(zpinger::TlsPinger::new(target).with_tls_config(server.client_config));
    p.ping().await.unwrap();
}

// -- NTP pinger -----------------------------------------------------------

#[tokio::test]
async fn ntp_pinger_succeeds() {
    let addr = testserver::start_ntp_ok("127.0.0.1:0").unwrap();
    zpinger::NtpPinger::new(addr.to_string())
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn ntp_pinger_with_custom_timeout() {
    let addr = testserver::start_ntp_ok("127.0.0.1:0").unwrap();
    zpinger::NtpPinger::new(addr.to_string())
        .with_timeout(Duration::from_secs(1))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn ntp_pinger_times_out_on_silent_port() {
    use std::net::UdpSocket;
    let server = UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let p = zpinger::NtpPinger::new(addr.to_string()).with_timeout(Duration::from_millis(200));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn ntp_pinger_usable_as_trait_object() {
    let addr = testserver::start_ntp_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::NtpPinger::new(addr.to_string()));
    p.ping().await.unwrap();
}

// -- STUN pinger ----------------------------------------------------------

#[tokio::test]
async fn stun_pinger_succeeds() {
    let addr = testserver::start_stun_ok("127.0.0.1:0").unwrap();
    zpinger::StunPinger::new(addr.to_string())
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn stun_pinger_with_custom_timeout() {
    let addr = testserver::start_stun_ok("127.0.0.1:0").unwrap();
    zpinger::StunPinger::new(addr.to_string())
        .with_timeout(Duration::from_secs(1))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn stun_pinger_times_out_on_silent_port() {
    use std::net::UdpSocket;
    let server = UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let p = zpinger::StunPinger::new(addr.to_string()).with_timeout(Duration::from_millis(200));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn stun_pinger_usable_as_trait_object() {
    let addr = testserver::start_stun_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::StunPinger::new(addr.to_string()));
    p.ping().await.unwrap();
}

// -- TURN pinger ----------------------------------------------------------

#[tokio::test]
async fn turn_pinger_succeeds_on_401_response() {
    let addr = testserver::start_turn_ok("127.0.0.1:0").unwrap();
    zpinger::TurnPinger::new(addr.to_string())
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn turn_pinger_with_custom_timeout() {
    let addr = testserver::start_turn_ok("127.0.0.1:0").unwrap();
    zpinger::TurnPinger::new(addr.to_string())
        .with_timeout(Duration::from_secs(1))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn turn_pinger_times_out_on_silent_port() {
    use std::net::UdpSocket;
    let server = UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = server.local_addr().unwrap();
    let p = zpinger::TurnPinger::new(addr.to_string()).with_timeout(Duration::from_millis(200));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn turn_pinger_usable_as_trait_object() {
    let addr = testserver::start_turn_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::TurnPinger::new(addr.to_string()));
    p.ping().await.unwrap();
}

// -- RTSP pinger ----------------------------------------------------------

#[tokio::test]
async fn rtsp_pinger_succeeds_against_options_responder() {
    let addr = testserver::start_rtsp_ok("127.0.0.1:0").unwrap();
    zpinger::RtspPinger::new(format!("rtsp://localhost:{}", addr.port()))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn rtsp_pinger_with_custom_timeout() {
    let addr = testserver::start_rtsp_ok("127.0.0.1:0").unwrap();
    zpinger::RtspPinger::new(format!("rtsp://localhost:{}", addr.port()))
        .with_timeout(Duration::from_secs(1))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn rtsp_pinger_fails_on_closed_port() {
    let target = format!("rtsp://{}", closed_tcp_addr());
    let p = zpinger::RtspPinger::new(target).with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn rtsp_pinger_rejects_non_rtsp_scheme() {
    let p = zpinger::RtspPinger::new("http://example.com/").with_timeout(Duration::from_secs(1));
    let err = p.ping().await.unwrap_err();
    assert!(err.to_string().contains("scheme 'http'"));
}

#[tokio::test]
async fn rtsp_pinger_rejects_non_rtsp_response() {
    // HTTP server on RTSP-style URL — response must be rejected.
    let addr = testserver::start_http_ok("127.0.0.1:0").unwrap();
    let p =
        zpinger::RtspPinger::new(format!("rtsp://{}", addr)).with_timeout(Duration::from_secs(1));
    let err = p
        .ping()
        .await
        .expect_err("HTTP/1.1 response must not pass RTSP validation");
    assert!(err.to_string().contains("RTSP/1.0 200"));
}

#[tokio::test]
async fn rtsp_pinger_usable_as_trait_object() {
    let addr = testserver::start_rtsp_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::RtspPinger::new(format!(
        "rtsp://localhost:{}",
        addr.port()
    )));
    p.ping().await.unwrap();
}

// -- RTMP pinger ----------------------------------------------------------

#[tokio::test]
async fn rtmp_pinger_succeeds_against_handshake_responder() {
    let addr = testserver::start_rtmp_ok("127.0.0.1:0").unwrap();
    zpinger::RtmpPinger::new(format!("rtmp://localhost:{}", addr.port()))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn rtmp_pinger_with_custom_timeout() {
    let addr = testserver::start_rtmp_ok("127.0.0.1:0").unwrap();
    zpinger::RtmpPinger::new(format!("rtmp://localhost:{}", addr.port()))
        .with_timeout(Duration::from_secs(1))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn rtmp_pinger_fails_on_closed_port() {
    let target = format!("rtmp://{}", closed_tcp_addr());
    let p = zpinger::RtmpPinger::new(target).with_timeout(Duration::from_millis(500));
    assert!(p.ping().await.is_err());
}

#[tokio::test]
async fn rtmp_pinger_rejects_non_rtmp_scheme() {
    let p = zpinger::RtmpPinger::new("ws://example.com/").with_timeout(Duration::from_secs(1));
    let err = p.ping().await.unwrap_err();
    assert!(err.to_string().contains("scheme 'ws'"));
}

#[tokio::test]
async fn rtmp_pinger_fails_when_server_speaks_wrong_protocol() {
    // HTTP server replies with `HTTP/1.1` text on the first 1537 bytes;
    // S0 byte (first byte of "HTTP/...") is 'H' = 0x48, not 0x03.
    let addr = testserver::start_http_ok("127.0.0.1:0").unwrap();
    let p =
        zpinger::RtmpPinger::new(format!("rtmp://{}", addr)).with_timeout(Duration::from_secs(1));
    let err = p
        .ping()
        .await
        .expect_err("HTTP server must not pass RTMP handshake");
    let msg = err.to_string();
    // Either S0 version mismatch or unexpected EOF — both are correct
    // failure modes against an HTTP responder.
    assert!(
        msg.contains("S0 returned version") || msg.to_lowercase().contains("eof"),
        "unexpected error: {msg}"
    );
}

#[tokio::test]
async fn rtmp_pinger_usable_as_trait_object() {
    let addr = testserver::start_rtmp_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(zpinger::RtmpPinger::new(format!(
        "rtmp://localhost:{}",
        addr.port()
    )));
    p.ping().await.unwrap();
}

// -- QUIC pinger ----------------------------------------------------------

#[tokio::test]
async fn quic_pinger_succeeds_with_trusted_cert() {
    let server = testserver::start_quic_ok("127.0.0.1:0").unwrap();
    zpinger::QuicPinger::new(format!("localhost:{}", server.addr.port()))
        .with_tls_config(server.client_config)
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn quic_pinger_fails_without_trust_anchor() {
    let server = testserver::start_quic_ok("127.0.0.1:0").unwrap();
    // No `with_tls_config` → defaults to webpki-roots, which doesn't
    // trust the test cert.
    let err = zpinger::QuicPinger::new(format!("localhost:{}", server.addr.port()))
        .with_timeout(Duration::from_secs(2))
        .ping()
        .await
        .expect_err("should fail without trust anchor");
    let msg = err.to_string().to_lowercase();
    assert!(
        msg.contains("certificate")
            || msg.contains("trust")
            || msg.contains("unknown")
            || msg.contains("handshake"),
        "unexpected QUIC error: {err}"
    );
}

#[tokio::test]
async fn quic_pinger_with_custom_timeout() {
    let server = testserver::start_quic_ok("127.0.0.1:0").unwrap();
    zpinger::QuicPinger::new(format!("localhost:{}", server.addr.port()))
        .with_tls_config(server.client_config)
        .with_timeout(Duration::from_secs(2))
        .ping()
        .await
        .unwrap();
}

#[tokio::test]
async fn quic_pinger_times_out_on_silent_port() {
    use std::net::UdpSocket;
    let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
    let addr = sock.local_addr().unwrap();
    // No QUIC server replying — handshake will stall, our timeout
    // wins.
    let err = zpinger::QuicPinger::new(format!("localhost:{}", addr.port()))
        .with_timeout(Duration::from_millis(300))
        .ping()
        .await
        .expect_err("silent UDP port should time out");
    assert!(
        err.kind() == std::io::ErrorKind::TimedOut
            || err.to_string().to_lowercase().contains("timed out")
            || err.to_string().to_lowercase().contains("timeout"),
        "expected timeout error, got: {err}"
    );
}

#[tokio::test]
async fn quic_pinger_rejects_unsupported_scheme() {
    let p = zpinger::QuicPinger::new("ws://example.com:443").with_timeout(Duration::from_secs(1));
    let err = p.ping().await.unwrap_err();
    assert!(err.to_string().contains("scheme 'ws'"));
}

#[tokio::test]
async fn quic_pinger_usable_as_trait_object() {
    let server = testserver::start_quic_ok("127.0.0.1:0").unwrap();
    let p: Box<dyn Pinger> = Box::new(
        zpinger::QuicPinger::new(format!("localhost:{}", server.addr.port()))
            .with_tls_config(server.client_config),
    );
    p.ping().await.unwrap();
}

#[tokio::test]
async fn quic_pinger_with_alpn_override() {
    let server = testserver::start_quic_ok("127.0.0.1:0").unwrap();
    // Server only advertises h3; if we ask for hq-29 (HTTP/0.9-ish
    // legacy QUIC ALPN) the handshake should fail with no overlap.
    let err = zpinger::QuicPinger::new(format!("localhost:{}", server.addr.port()))
        .with_tls_config(server.client_config)
        .with_alpn(vec![b"hq-29".to_vec()])
        .with_timeout(Duration::from_secs(2))
        .ping()
        .await
        .expect_err("ALPN mismatch must fail");
    assert!(
        err.to_string().to_lowercase().contains("alpn")
            || err.to_string().to_lowercase().contains("handshake")
            || err
                .to_string()
                .to_lowercase()
                .contains("no application protocol"),
        "expected ALPN error, got: {err}"
    );
}