mx-logging 0.1.0

Tracing and OpenTelemetry logging utilities for MultiversX Rust services.
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
//! Tests for mx-logging crate.
//!
//! Uses `serial_test` for tests that modify global state (`RUST_LOG` env variable).
//!
//! Test Strategy:
//! - `build_filter` tests: Comprehensive coverage of filter priority logic
//! - `init` tests: `OnceLock` behavior verification (global state prevents full init testing)
//! - OpenTelemetry tests: Config, error types, and sampler selection logic

use serial_test::serial;
use std::env;

use crate::build_filter;

/// Helper to safely set `RUST_LOG` environment variable (Rust 2024 edition requires unsafe).
fn set_rust_log(value: &str) {
    // SAFETY: We use serial_test to ensure no concurrent access to RUST_LOG
    unsafe {
        env::set_var("RUST_LOG", value);
    }
}

/// Helper to safely remove `RUST_LOG` environment variable (Rust 2024 edition requires unsafe).
fn remove_rust_log() {
    // SAFETY: We use serial_test to ensure no concurrent access to RUST_LOG
    unsafe {
        env::remove_var("RUST_LOG");
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// build_filter Tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
#[serial]
fn test_build_filter_rust_log_override() {
    // When explicit filter is None, RUST_LOG should be used.
    set_rust_log("debug");

    let filter = build_filter(None, "warn");
    let filter_str = format!("{filter:?}");

    assert!(
        filter_str.contains("DEBUG"),
        "Expected filter to use RUST_LOG value 'debug' (DEBUG), got: {filter_str}"
    );

    remove_rust_log();
}

#[test]
#[serial]
fn test_build_filter_explicit_filter() {
    // When RUST_LOG is not set, explicit filter should be used
    remove_rust_log();

    let filter = build_filter(Some("warn"), "info");
    let filter_str = format!("{filter:?}");

    // The filter should contain "WARN" from explicit filter
    assert!(
        filter_str.contains("WARN"),
        "Expected filter to use explicit value 'warn' (WARN), got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_default_fallback() {
    // When RUST_LOG is not set and filter is None, default should be used
    remove_rust_log();

    let filter = build_filter(None, "error");
    let filter_str = format!("{filter:?}");

    // The filter should contain "ERROR" from default_filter
    assert!(
        filter_str.contains("ERROR"),
        "Expected filter to use default value 'error' (ERROR), got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_invalid_fallback() {
    // Invalid filter should fall back to default
    remove_rust_log();

    // Use an invalid filter directive
    let filter = build_filter(Some("invalid[[[filter"), "info");
    let filter_str = format!("{filter:?}");

    // Should fall back to "INFO" since the explicit filter is invalid
    assert!(
        filter_str.contains("INFO"),
        "Expected filter to fall back to default 'info' (INFO), got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_complex_directives() {
    // Test with complex filter directives (module-level filters)
    remove_rust_log();

    let filter = build_filter(Some("mx_logging=debug,tower=warn"), "info");
    let filter_str = format!("{filter:?}");

    // The filter should contain the complex directives
    assert!(
        filter_str.contains("mx_logging") || filter_str.contains("DEBUG"),
        "Expected filter to contain module directive, got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_all_log_levels() {
    // Test all standard log levels
    remove_rust_log();

    for (level, expected) in [
        ("trace", "TRACE"),
        ("debug", "DEBUG"),
        ("info", "INFO"),
        ("warn", "WARN"),
        ("error", "ERROR"),
        ("off", "OFF"),
    ] {
        let filter = build_filter(Some(level), "info");
        let filter_str = format!("{filter:?}");

        assert!(
            filter_str.contains(expected),
            "Expected filter to contain '{expected}' for level '{level}', got: {filter_str}"
        );
    }
}

#[test]
#[serial]
fn test_build_filter_case_insensitive() {
    // Test that filter levels are case-insensitive
    remove_rust_log();

    for level in ["DEBUG", "Debug", "debug", "dEbUg"] {
        let filter = build_filter(Some(level), "info");
        let filter_str = format!("{filter:?}");

        assert!(
            filter_str.contains("DEBUG"),
            "Expected filter to parse '{level}' as DEBUG, got: {filter_str}"
        );
    }
}

#[test]
#[serial]
fn test_build_filter_rust_log_complex() {
    // When explicit filter is None, complex RUST_LOG values are used.
    set_rust_log("mx_logging=trace,tower_http=debug,hyper=warn");

    let filter = build_filter(None, "info");
    let filter_str = format!("{filter:?}");

    assert!(
        filter_str.contains("mx_logging") || filter_str.contains("TRACE"),
        "Expected RUST_LOG directives to be applied, got: {filter_str}"
    );

    remove_rust_log();
}

#[test]
#[serial]
fn test_build_filter_empty_string() {
    // Test with empty filter string
    remove_rust_log();

    let filter = build_filter(Some(""), "warn");
    let filter_str = format!("{filter:?}");

    // Empty string creates a valid filter with OFF level (no directives)
    // This is EnvFilter's behavior for empty strings
    assert!(
        filter_str.contains("OFF") || filter_str.contains("statics"),
        "Expected empty filter to create valid empty filter, got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_whitespace_only() {
    // Test with whitespace-only filter string
    remove_rust_log();

    let filter = build_filter(Some("   "), "error");
    let filter_str = format!("{filter:?}");

    // Whitespace-only is likely invalid, should fall back to default
    assert!(
        filter_str.contains("ERROR"),
        "Expected whitespace filter to fall back to default 'error', got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_build_filter_rust_log_empty() {
    // Test when RUST_LOG is set to empty string
    set_rust_log("");

    // Empty RUST_LOG should fall through to explicit filter or default
    // Note: EnvFilter::try_from_default_env() may succeed with empty value
    let filter = build_filter(Some("debug"), "info");
    let _filter_str = format!("{filter:?}");

    // We just verify it doesn't panic
    remove_rust_log();
}

#[test]
#[serial]
fn test_build_filter_span_directives() {
    // Test with span-based filter directives
    remove_rust_log();

    let filter = build_filter(Some("info,[span_name]=debug"), "warn");
    let filter_str = format!("{filter:?}");

    // Should parse span-based directive
    assert!(
        filter_str.contains("INFO") || filter_str.contains("span"),
        "Expected filter to parse span directive, got: {filter_str}"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// init Tests
// ─────────────────────────────────────────────────────────────────────────────

/// Note: These tests verify the `OnceLock` behavior but cannot actually call `init()`
/// multiple times in the same test process since it's a global singleton.
/// We test the underlying behavior through `build_filter` and verify the
/// `OnceLock` semantics are correct.

#[test]
#[serial]
fn test_init_idempotent() {
    // Verify OnceLock behavior - get_or_init only executes once
    use std::sync::OnceLock;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static INIT_COUNT: AtomicUsize = AtomicUsize::new(0);
    static TEST_LOCK: OnceLock<()> = OnceLock::new();

    // First call should increment
    TEST_LOCK.get_or_init(|| {
        INIT_COUNT.fetch_add(1, Ordering::SeqCst);
    });

    // Second call should NOT increment (no-op)
    TEST_LOCK.get_or_init(|| {
        INIT_COUNT.fetch_add(1, Ordering::SeqCst);
    });

    assert_eq!(
        INIT_COUNT.load(Ordering::SeqCst),
        1,
        "OnceLock should only execute initialization once"
    );
}

#[test]
#[serial]
fn test_init_with_explicit_filter() {
    // Verify that when explicit filter is provided, it's used (when RUST_LOG not set)
    remove_rust_log();

    let filter = build_filter(Some("trace"), "info");
    let filter_str = format!("{filter:?}");

    assert!(
        filter_str.contains("TRACE"),
        "Explicit filter 'trace' (TRACE) should be respected, got: {filter_str}"
    );
}

#[test]
#[serial]
fn test_init_default_filter() {
    // Verify default filter is used when filter=None and no RUST_LOG
    remove_rust_log();

    let filter = build_filter(None, "warn");
    let filter_str = format!("{filter:?}");

    assert!(
        filter_str.contains("WARN"),
        "Default filter 'warn' (WARN) should be used, got: {filter_str}"
    );
}

// ─────────────────────────────────────────────────────────────────────────────
// build_fmt_layer Tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn test_build_fmt_layer_creates_layer() {
    // Verify build_fmt_layer creates a valid layer
    // We can't directly test all internal settings, but we can verify it compiles
    // and produces a valid layer type
    use crate::build_fmt_layer;

    // This tests that the function compiles and returns a valid layer
    // The type system ensures correctness of the configuration
    let _layer = build_fmt_layer::<tracing_subscriber::Registry>();
}

// ─────────────────────────────────────────────────────────────────────────────
// is_initialized Tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn test_is_initialized_behavior() {
    // Test the is_initialized function
    // Note: Due to global state, we can only test the function exists
    // and returns a boolean. The actual value depends on test execution order.
    use crate::is_initialized;

    let _result = is_initialized();
    // We can't assert a specific value since it depends on whether
    // another test has called init() first
}

// ─────────────────────────────────────────────────────────────────────────────
// TRACING OnceLock Tests
// ─────────────────────────────────────────────────────────────────────────────

#[test]
fn test_tracing_oncelock_initialized_check() {
    // Test checking if TRACING is initialized (mirrors init_with_otel check)
    use std::sync::OnceLock;

    static TEST_TRACING: OnceLock<()> = OnceLock::new();

    // Initially not set
    assert!(TEST_TRACING.get().is_none());

    // After get_or_init
    TEST_TRACING.get_or_init(|| ());
    assert!(TEST_TRACING.get().is_some());
}

#[test]
fn test_tracing_oncelock_multiple_init_attempts() {
    // Test that multiple init attempts are handled correctly
    use std::sync::OnceLock;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static CALL_COUNT: AtomicUsize = AtomicUsize::new(0);
    static TEST_TRACING_2: OnceLock<()> = OnceLock::new();

    // First init
    TEST_TRACING_2.get_or_init(|| {
        CALL_COUNT.fetch_add(1, Ordering::SeqCst);
    });

    // Second init attempt
    TEST_TRACING_2.get_or_init(|| {
        CALL_COUNT.fetch_add(1, Ordering::SeqCst);
    });

    // Third init attempt
    TEST_TRACING_2.get_or_init(|| {
        CALL_COUNT.fetch_add(1, Ordering::SeqCst);
    });

    // Init function should only be called once
    assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1);
}

// ─────────────────────────────────────────────────────────────────────────────
// OtelConfig Tests
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(feature = "opentelemetry")]
mod otel_tests {
    use crate::otel::{OtelConfig, OtelError};

    // ─────────────────────────────────────────────────────────────────────────────
    // OtelConfig Tests
    // ─────────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_otel_config_default() {
        let config = OtelConfig::default();

        assert_eq!(config.service_name, "mx-service");
        assert_eq!(config.otlp_endpoint, "http://localhost:4317");
        assert!((config.sampling_ratio - 1.0).abs() < f64::EPSILON);
        assert_eq!(config.batch_size, 512);
        assert_eq!(config.max_queue_size, 2048);
        assert_eq!(config.export_timeout_ms, 30_000);
        assert_eq!(config.connect_timeout_ms, 10_000);
    }

    #[test]
    fn test_otel_config_custom() {
        let config = OtelConfig {
            service_name: "my-custom-service".to_string(),
            otlp_endpoint: "http://collector.example.com:4317".to_string(),
            sampling_ratio: 0.5,
            batch_size: 1024,
            max_queue_size: 4096,
            export_timeout_ms: 60_000,
            connect_timeout_ms: 5_000,
        };

        assert_eq!(config.service_name, "my-custom-service");
        assert_eq!(config.otlp_endpoint, "http://collector.example.com:4317");
        assert!((config.sampling_ratio - 0.5).abs() < f64::EPSILON);
        assert_eq!(config.batch_size, 1024);
        assert_eq!(config.max_queue_size, 4096);
        assert_eq!(config.export_timeout_ms, 60_000);
        assert_eq!(config.connect_timeout_ms, 5_000);
    }

    #[test]
    fn test_otel_config_clone() {
        let original = OtelConfig {
            service_name: "test-service".to_string(),
            otlp_endpoint: "http://test:4317".to_string(),
            sampling_ratio: 0.75,
            batch_size: 256,
            max_queue_size: 1024,
            export_timeout_ms: 15_000,
            connect_timeout_ms: 3_000,
        };

        let cloned = original.clone();

        // Verify all fields are cloned correctly
        assert_eq!(cloned.service_name, original.service_name);
        assert_eq!(cloned.otlp_endpoint, original.otlp_endpoint);
        assert!((cloned.sampling_ratio - original.sampling_ratio).abs() < f64::EPSILON);
        assert_eq!(cloned.batch_size, original.batch_size);
        assert_eq!(cloned.max_queue_size, original.max_queue_size);
        assert_eq!(cloned.export_timeout_ms, original.export_timeout_ms);
        assert_eq!(cloned.connect_timeout_ms, original.connect_timeout_ms);
    }

    #[test]
    fn test_otel_config_debug() {
        let config = OtelConfig::default();
        let debug_str = format!("{:?}", config);

        // Verify Debug output contains expected fields
        assert!(debug_str.contains("OtelConfig"));
        assert!(debug_str.contains("service_name"));
        assert!(debug_str.contains("mx-service"));
        assert!(debug_str.contains("otlp_endpoint"));
        assert!(debug_str.contains("localhost:4317"));
        assert!(debug_str.contains("sampling_ratio"));
        assert!(debug_str.contains("batch_size"));
        assert!(debug_str.contains("max_queue_size"));
        assert!(debug_str.contains("export_timeout_ms"));
        assert!(debug_str.contains("connect_timeout_ms"));
    }

    #[test]
    fn test_otel_config_edge_values() {
        // Test with minimum valid values
        let min_config = OtelConfig {
            service_name: String::new(),
            otlp_endpoint: String::new(),
            sampling_ratio: 0.0,
            batch_size: 0,
            max_queue_size: 0,
            export_timeout_ms: 0,
            connect_timeout_ms: 0,
        };

        assert!(min_config.service_name.is_empty());
        assert!(min_config.sampling_ratio <= 0.0);

        // Test with maximum reasonable values
        let max_config = OtelConfig {
            service_name: "a".repeat(1000),
            otlp_endpoint: "http://very-long-hostname.example.com:4317".to_string(),
            sampling_ratio: 1.0,
            batch_size: usize::MAX,
            max_queue_size: usize::MAX,
            export_timeout_ms: u64::MAX,
            connect_timeout_ms: u64::MAX,
        };

        assert_eq!(max_config.service_name.len(), 1000);
        assert!((max_config.sampling_ratio - 1.0).abs() < f64::EPSILON);
    }

    // ─────────────────────────────────────────────────────────────────────────────
    // Sampler Selection Logic Tests
    // ─────────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_init_with_otel_sampler_always_on() {
        // When sampling_ratio is 1.0, sampler should be AlwaysOn
        let config = OtelConfig {
            sampling_ratio: 1.0,
            ..Default::default()
        };

        // Verify the condition used in init_with_otel
        let is_always_on = (config.sampling_ratio - 1.0).abs() < f64::EPSILON;
        assert!(
            is_always_on,
            "sampling_ratio=1.0 should trigger AlwaysOn sampler"
        );
    }

    #[test]
    fn test_init_with_otel_sampler_always_on_near_one() {
        // Test values very close to 1.0 but not exactly 1.0
        let config = OtelConfig {
            sampling_ratio: 1.0 - f64::EPSILON / 2.0,
            ..Default::default()
        };

        // This should still trigger AlwaysOn due to epsilon comparison
        let is_always_on = (config.sampling_ratio - 1.0).abs() < f64::EPSILON;
        assert!(
            is_always_on,
            "sampling_ratio very close to 1.0 should trigger AlwaysOn sampler"
        );
    }

    #[test]
    fn test_init_with_otel_sampler_always_off() {
        // When sampling_ratio is 0.0, sampler should be AlwaysOff
        let config = OtelConfig {
            sampling_ratio: 0.0,
            ..Default::default()
        };

        // Verify the condition used in init_with_otel
        let is_always_off = config.sampling_ratio <= 0.0;
        assert!(
            is_always_off,
            "sampling_ratio=0.0 should trigger AlwaysOff sampler"
        );
    }

    #[test]
    fn test_init_with_otel_sampler_always_off_negative() {
        // Test negative sampling ratio (should also be AlwaysOff)
        let config = OtelConfig {
            sampling_ratio: -0.5,
            ..Default::default()
        };

        let is_always_off = config.sampling_ratio <= 0.0;
        assert!(
            is_always_off,
            "negative sampling_ratio should trigger AlwaysOff sampler"
        );
    }

    #[test]
    fn test_init_with_otel_sampler_ratio() {
        // When 0 < sampling_ratio < 1, sampler should be TraceIdRatioBased
        let config = OtelConfig {
            sampling_ratio: 0.5,
            ..Default::default()
        };

        // Verify the condition used in init_with_otel
        let is_ratio_based =
            config.sampling_ratio > 0.0 && (config.sampling_ratio - 1.0).abs() >= f64::EPSILON;
        assert!(
            is_ratio_based,
            "sampling_ratio=0.5 should trigger TraceIdRatioBased sampler"
        );
    }

    #[test]
    fn test_init_with_otel_sampler_ratio_edge_cases() {
        // Test various ratio values between 0 and 1
        for ratio in [0.001, 0.1, 0.25, 0.33, 0.5, 0.75, 0.9, 0.999] {
            let config = OtelConfig {
                sampling_ratio: ratio,
                ..Default::default()
            };

            let is_ratio_based =
                config.sampling_ratio > 0.0 && (config.sampling_ratio - 1.0).abs() >= f64::EPSILON;

            assert!(
                is_ratio_based,
                "sampling_ratio={ratio} should trigger TraceIdRatioBased sampler"
            );
        }
    }

    // ─────────────────────────────────────────────────────────────────────────────
    // OtelError Tests
    // ─────────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_otel_error_display() {
        // Test Display impl for ExporterCreation variant
        let err = OtelError::ExporterCreation("connection refused".to_string());
        let display = err.to_string();
        assert!(
            display.contains("Failed to create OTLP exporter"),
            "ExporterCreation should contain 'Failed to create OTLP exporter', got: {display}"
        );
        assert!(
            display.contains("connection refused"),
            "ExporterCreation should contain the error message, got: {display}"
        );

        // Test Display impl for TracerInstallation variant
        let err = OtelError::TracerInstallation("runtime error".to_string());
        let display = err.to_string();
        assert!(
            display.contains("Failed to install tracer"),
            "TracerInstallation should contain 'Failed to install tracer', got: {display}"
        );
        assert!(
            display.contains("runtime error"),
            "TracerInstallation should contain the error message, got: {display}"
        );

        // Test Display impl for AlreadyInitialized variant
        let err = OtelError::AlreadyInitialized;
        let display = err.to_string();
        assert!(
            display.contains("already initialized"),
            "AlreadyInitialized should contain 'already initialized', got: {display}"
        );
    }

    #[test]
    fn test_otel_error_debug() {
        // Test Debug impl for all variants
        let err = OtelError::ExporterCreation("test error".to_string());
        let debug = format!("{:?}", err);
        assert!(debug.contains("ExporterCreation"));
        assert!(debug.contains("test error"));

        let err = OtelError::TracerInstallation("install error".to_string());
        let debug = format!("{:?}", err);
        assert!(debug.contains("TracerInstallation"));
        assert!(debug.contains("install error"));

        let err = OtelError::AlreadyInitialized;
        let debug = format!("{:?}", err);
        assert!(debug.contains("AlreadyInitialized"));
    }

    #[test]
    fn test_otel_error_is_std_error() {
        // Verify OtelError implements std::error::Error
        fn assert_error<T: std::error::Error>(_: &T) {}

        let err = OtelError::ExporterCreation("test".to_string());
        assert_error(&err);

        let err = OtelError::TracerInstallation("test".to_string());
        assert_error(&err);

        let err = OtelError::AlreadyInitialized;
        assert_error(&err);
    }

    #[test]
    fn test_otel_error_source() {
        // OtelError doesn't wrap other errors, so source() should return None
        use std::error::Error;

        let err = OtelError::ExporterCreation("test".to_string());
        assert!(err.source().is_none());

        let err = OtelError::TracerInstallation("test".to_string());
        assert!(err.source().is_none());

        let err = OtelError::AlreadyInitialized;
        assert!(err.source().is_none());
    }

    #[test]
    fn test_otel_error_pattern_matching() {
        // Verify pattern matching works correctly
        let err = OtelError::ExporterCreation("test".to_string());
        assert!(matches!(err, OtelError::ExporterCreation(_)));

        let err = OtelError::TracerInstallation("test".to_string());
        assert!(matches!(err, OtelError::TracerInstallation(_)));

        let err = OtelError::AlreadyInitialized;
        assert!(matches!(err, OtelError::AlreadyInitialized));
    }

    #[test]
    fn test_otel_error_with_empty_message() {
        // Test with empty error messages
        let err = OtelError::ExporterCreation(String::new());
        let display = err.to_string();
        assert!(display.contains("Failed to create OTLP exporter"));

        let err = OtelError::TracerInstallation(String::new());
        let display = err.to_string();
        assert!(display.contains("Failed to install tracer"));
    }

    #[test]
    fn test_otel_error_with_long_message() {
        // Test with very long error messages
        let long_msg = "x".repeat(10000);

        let err = OtelError::ExporterCreation(long_msg.clone());
        let display = err.to_string();
        assert!(display.contains(&long_msg));

        let err = OtelError::TracerInstallation(long_msg.clone());
        let display = err.to_string();
        assert!(display.contains(&long_msg));
    }

    // ─────────────────────────────────────────────────────────────────────────────
    // OnceLock Behavior Tests
    // ─────────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_init_with_otel_idempotent() {
        // AlreadyInitialized error should be returned on second initialization attempt
        // We can't actually call init_with_otel in tests since it modifies global state,
        // but we can verify the error type is correctly defined
        let err = OtelError::AlreadyInitialized;
        assert!(matches!(err, OtelError::AlreadyInitialized));
    }

    #[test]
    fn test_shutdown_otel_not_initialized() {
        // shutdown_otel should be a no-op when not initialized
        // This test verifies it doesn't panic when called without initialization
        // Note: We can't actually test this in isolation due to global state,
        // but we verify the function exists and can be called
        use std::sync::OnceLock;

        static TEST_PROVIDER: OnceLock<()> = OnceLock::new();

        // Verify get() returns None when not initialized
        assert!(TEST_PROVIDER.get().is_none());
    }

    #[test]
    fn test_tracer_provider_oncelock_behavior() {
        // Verify OnceLock set() behavior for tracer provider
        use std::sync::OnceLock;

        static TEST_LOCK: OnceLock<String> = OnceLock::new();

        // First set should succeed
        let result = TEST_LOCK.set("first".to_string());
        assert!(result.is_ok());

        // Second set should fail with the value returned
        let result = TEST_LOCK.set("second".to_string());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "second");

        // Get should return the first value
        assert_eq!(TEST_LOCK.get(), Some(&"first".to_string()));
    }
}