tracing_mock/
span.rs

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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! Define expectations to match and validate spans.
//!
//! The [`ExpectedSpan`] and [`NewSpan`] structs define expectations
//! for spans to be matched by the mock subscriber API in the
//! [`subscriber`] module.
//!
//! Expected spans should be created with [`expect::span`] and a
//! chain of method calls describing the assertions made about the
//! span. Expectations about the lifecycle of the span can be set on the [`MockSubscriber`].
//!
//! # Examples
//!
//! ```
//! use tracing_mock::{expect, subscriber};
//!
//! let span = expect::span()
//!     .named("interesting_span")
//!     .at_level(tracing::Level::INFO);
//!
//! let (subscriber, handle) = subscriber::mock()
//!     .enter(&span)
//!     .exit(&span)
//!     .run_with_handle();
//!
//! tracing::subscriber::with_default(subscriber, || {
//!    let span = tracing::info_span!("interesting_span");
//!     let _guard = span.enter();
//! });
//!
//! handle.assert_finished();
//! ```
//!
//! Instead of passing an `ExpectedSpan`, the subscriber methods will also accept
//! anything that implements `Into<String>` which is shorthand for
//! `expect::span().named(name)`.
//!
//! ```
//! use tracing_mock::subscriber;
//!
//! let (subscriber, handle) = subscriber::mock()
//!     .enter("interesting_span")
//!     .run_with_handle();
//!
//! tracing::subscriber::with_default(subscriber, || {
//!    let span = tracing::info_span!("interesting_span");
//!     let _guard = span.enter();
//! });
//!
//! handle.assert_finished();
//! ```
//
//! The following example asserts the name, level, parent, and fields of the span:
//!
//! ```
//! use tracing_mock::{expect, subscriber};
//!
//! let span = expect::span()
//!     .named("interesting_span")
//!     .at_level(tracing::Level::INFO);
//! let new_span = span
//!     .clone()
//!     .with_fields(expect::field("field.name").with_value(&"field_value"))
//!     .with_ancestry(expect::has_explicit_parent("parent_span"));
//!
//! let (subscriber, handle) = subscriber::mock()
//!     .new_span("parent_span")
//!     .new_span(new_span)
//!     .enter(&span)
//!     .exit(&span)
//!     .run_with_handle();
//!
//! tracing::subscriber::with_default(subscriber, || {
//!     let parent = tracing::info_span!("parent_span");
//!
//!     let span = tracing::info_span!(
//!         parent: parent.id(),
//!         "interesting_span",
//!         field.name = "field_value",
//!     );
//!     let _guard = span.enter();
//! });
//!
//! handle.assert_finished();
//! ```
//!
//! All expectations must be met for the test to pass. For example,
//! the following test will fail due to a mismatch in the spans' names:
//!
//! ```should_panic
//! use tracing_mock::{expect, subscriber};
//!
//! let span = expect::span()
//!     .named("interesting_span")
//!     .at_level(tracing::Level::INFO);
//!
//! let (subscriber, handle) = subscriber::mock()
//!     .enter(&span)
//!     .exit(&span)
//!     .run_with_handle();
//!
//! tracing::subscriber::with_default(subscriber, || {
//!    let span = tracing::info_span!("another_span");
//!    let _guard = span.enter();
//! });
//!
//! handle.assert_finished();
//! ```
//!
//! [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
//! [`subscriber`]: mod@crate::subscriber
//! [`expect::span`]: fn@crate::expect::span
use std::{
    error, fmt,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use crate::{
    ancestry::{ActualAncestry, ExpectedAncestry},
    field::ExpectedFields,
    metadata::ExpectedMetadata,
};

/// A mock span.
///
/// This is intended for use with the mock subscriber API in the
/// [`subscriber`] module.
///
/// [`subscriber`]: mod@crate::subscriber
#[derive(Clone, Default, Eq, PartialEq)]
pub struct ExpectedSpan {
    pub(crate) id: Option<ExpectedId>,
    pub(crate) metadata: ExpectedMetadata,
}

impl<I> From<I> for ExpectedSpan
where
    I: Into<String>,
{
    fn from(name: I) -> Self {
        ExpectedSpan::default().named(name)
    }
}

impl From<&ExpectedId> for ExpectedSpan {
    fn from(id: &ExpectedId) -> Self {
        ExpectedSpan::default().with_id(id.clone())
    }
}

impl From<&ExpectedSpan> for ExpectedSpan {
    fn from(span: &ExpectedSpan) -> Self {
        span.clone()
    }
}

/// A mock new span.
///
/// **Note**: This struct contains expectations that can only be asserted
/// on when expecting a new span via [`MockSubscriber::new_span`]. They
/// cannot be validated on [`MockSubscriber::enter`],
/// [`MockSubscriber::exit`], or any other method on [`MockSubscriber`]
/// that takes an `ExpectedSpan`.
///
/// For more details on how to use this struct, see the documentation
/// on the [`subscriber`] module.
///
/// [`subscriber`]: mod@crate::subscriber
/// [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
/// [`MockSubscriber::enter`]: fn@crate::subscriber::MockSubscriber::enter
/// [`MockSubscriber::exit`]: fn@crate::subscriber::MockSubscriber::exit
/// [`MockSubscriber::new_span`]: fn@crate::subscriber::MockSubscriber::new_span
#[derive(Default, Eq, PartialEq)]
pub struct NewSpan {
    pub(crate) span: ExpectedSpan,
    pub(crate) fields: ExpectedFields,
    pub(crate) ancestry: Option<ExpectedAncestry>,
}

pub(crate) struct ActualSpan {
    id: tracing_core::span::Id,
    metadata: Option<&'static tracing_core::Metadata<'static>>,
}

impl ActualSpan {
    pub(crate) fn new(
        id: tracing_core::span::Id,
        metadata: Option<&'static tracing_core::Metadata<'static>>,
    ) -> Self {
        Self { id, metadata }
    }

    /// The Id of the actual span.
    pub(crate) fn id(&self) -> tracing_core::span::Id {
        self.id.clone()
    }

    /// The metadata for the actual span if it is available.
    pub(crate) fn metadata(&self) -> Option<&'static tracing_core::Metadata<'static>> {
        self.metadata
    }
}

impl From<&tracing_core::span::Id> for ActualSpan {
    fn from(id: &tracing_core::span::Id) -> Self {
        Self::new(id.clone(), None)
    }
}

/// A mock span ID.
///
/// This ID makes it possible to link together calls to different
/// [`MockSubscriber`] span methods that take an [`ExpectedSpan`] in
/// addition to those that take a [`NewSpan`].
///
/// Use [`expect::id`] to construct a new, unset `ExpectedId`.
///
/// For more details on how to use this struct, see the documentation
/// on [`ExpectedSpan::with_id`].
///
/// [`expect::id`]: fn@crate::expect::id
/// [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
#[derive(Clone, Default)]
pub struct ExpectedId {
    inner: Arc<AtomicU64>,
}

impl ExpectedSpan {
    /// Sets a name to expect when matching a span.
    ///
    /// If an event is recorded with a name that differs from the one provided to this method, the
    /// expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span().named("span name");
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!("span name");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// If only the name of the span needs to be validated, then
    /// instead of using the `named` method, a string can be passed
    /// to the [`MockSubscriber`] functions directly.
    ///
    /// ```
    /// use tracing_mock::subscriber;
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter("span name")
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!("span name");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// When the span name is different, the assertion will fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span().named("span name");
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!("a different span name");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
    pub fn named<I>(self, name: I) -> Self
    where
        I: Into<String>,
    {
        Self {
            metadata: ExpectedMetadata {
                name: Some(name.into()),
                ..self.metadata
            },
            ..self
        }
    }

    /// Sets the `ID` to expect when matching a span.
    ///
    /// The [`ExpectedId`] can be used to differentiate spans that are
    /// otherwise identical. An [`ExpectedId`] needs to be attached to
    /// an `ExpectedSpan` or [`NewSpan`] which is passed to
    /// [`MockSubscriber::new_span`]. The same [`ExpectedId`] can then
    /// be used to match the exact same span when passed to
    /// [`MockSubscriber::enter`], [`MockSubscriber::exit`], and
    /// [`MockSubscriber::drop_span`].
    ///
    /// This is especially useful when `tracing-mock` is being used to
    /// test the traces being generated within your own crate, in which
    /// case you may need to distinguish between spans which have
    /// identical metadata but different field values, which can
    /// otherwise only be checked in [`MockSubscriber::new_span`].
    ///
    /// # Examples
    ///
    /// Here we expect that the span that is created first is entered
    /// second:
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    /// let id1 = expect::id();
    /// let span1 = expect::span().named("span").with_id(id1.clone());
    /// let id2 = expect::id();
    /// let span2 = expect::span().named("span").with_id(id2.clone());
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&span1)
    ///     .new_span(&span2)
    ///     .enter(&span2)
    ///     .enter(&span1)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     fn create_span() -> tracing::Span {
    ///         tracing::info_span!("span")
    ///     }
    ///
    ///     let span1 = create_span();
    ///     let span2 = create_span();
    ///
    ///     let _guard2 = span2.enter();
    ///     let _guard1 = span1.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// Since `ExpectedId` implements `Into<ExpectedSpan>`, in cases where
    /// only checking on Id is desired, a shorthand version of the previous
    /// example can be used.
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    /// let id1 = expect::id();
    /// let id2 = expect::id();
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&id1)
    ///     .new_span(&id2)
    ///     .enter(&id2)
    ///     .enter(&id1)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     fn create_span() -> tracing::Span {
    ///         tracing::info_span!("span")
    ///     }
    ///
    ///     let span1 = create_span();
    ///     let span2 = create_span();
    ///
    ///     let _guard2 = span2.enter();
    ///     let _guard1 = span1.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// If the order that the spans are entered changes, the test will
    /// fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    /// let id1 = expect::id();
    /// let span1 = expect::span().named("span").with_id(id1.clone());
    /// let id2 = expect::id();
    /// let span2 = expect::span().named("span").with_id(id2.clone());
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&span1)
    ///     .new_span(&span2)
    ///     .enter(&span2)
    ///     .enter(&span1)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     fn create_span() -> tracing::Span {
    ///         tracing::info_span!("span")
    ///     }
    ///
    ///     let span1 = create_span();
    ///     let span2 = create_span();
    ///
    ///     let _guard1 = span1.enter();
    ///     let _guard2 = span2.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`MockSubscriber::new_span`]: fn@crate::subscriber::MockSubscriber::new_span
    /// [`MockSubscriber::enter`]: fn@crate::subscriber::MockSubscriber::enter
    /// [`MockSubscriber::exit`]: fn@crate::subscriber::MockSubscriber::exit
    /// [`MockSubscriber::drop_span`]: fn@crate::subscriber::MockSubscriber::drop_span
    pub fn with_id(self, id: ExpectedId) -> Self {
        Self {
            id: Some(id),
            ..self
        }
    }

    /// Sets the [`Level`](tracing::Level) to expect when matching a span.
    ///
    /// If an span is record with a level that differs from the one provided to this method, the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO);
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!("span");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// Expecting a span at `INFO` level will fail if the event is
    /// recorded at any other level:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO);
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::warn_span!("a serious span");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn at_level(self, level: tracing::Level) -> Self {
        Self {
            metadata: ExpectedMetadata {
                level: Some(level),
                ..self.metadata
            },
            ..self
        }
    }

    /// Sets the target to expect when matching a span.
    ///
    /// If an event is recorded with a target that doesn't match the
    /// provided target, this expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_target("some_target");
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!(target: "some_target", "span");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// The test will fail if the target is different:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_target("some_target");
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .enter(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let span = tracing::info_span!(target: "a_different_target", "span");
    ///     let _guard = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn with_target<I>(self, target: I) -> Self
    where
        I: Into<String>,
    {
        Self {
            metadata: ExpectedMetadata {
                target: Some(target.into()),
                ..self.metadata
            },
            ..self
        }
    }

    /// Configures this `ExpectedSpan` to expect the specified
    /// [`ExpectedAncestry`]. A span's ancestry indicates whether it has a
    /// parent or is a root span and whether the parent is explitly or
    /// contextually assigned.
    ///
    /// **Note**: This method returns a [`NewSpan`] and as such, this
    /// expectation can only be validated when expecting a new span via
    /// [`MockSubscriber::new_span`]. It cannot be validated on
    /// [`MockSubscriber::enter`], [`MockSubscriber::exit`], or any other
    /// method on [`MockSubscriber`] that takes an `ExpectedSpan`.
    ///
    /// An _explicit_ parent span is one passed to the `span!` macro in the
    /// `parent:` field. If no `parent:` field is specified, then the span
    /// will have a contextually determined parent or be a contextual root if
    /// there is no parent.
    ///
    /// If the ancestry is different from the provided one, this expectation
    /// will fail.
    ///
    /// # Examples
    ///
    /// An explicit or contextual parent can be matched on an `ExpectedSpan`.
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let parent = expect::span()
    ///     .named("parent_span")
    ///     .with_target("custom-target")
    ///     .at_level(tracing::Level::INFO);
    /// let span = expect::span()
    ///     .with_ancestry(expect::has_explicit_parent(&parent));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&parent)
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let parent = tracing::info_span!(target: "custom-target", "parent_span");
    ///     tracing::info_span!(parent: parent.id(), "span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// The functions `expect::has_explicit_parent` and
    /// `expect::has_contextual_parent` take `Into<ExpectedSpan>`, so a string
    /// passed directly will match on a span with that name, or an
    /// [`ExpectedId`] can be passed to match a span with that Id.
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_ancestry(expect::has_explicit_parent("parent_span"));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(expect::span().named("parent_span"))
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let parent = tracing::info_span!("parent_span");
    ///     tracing::info_span!(parent: parent.id(), "span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// In the following example, the expected span is an explicit root:
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_ancestry(expect::is_explicit_root());
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     tracing::info_span!(parent: None, "span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// In the example below, the expectation fails because the
    /// span is *contextually*—as opposed to explicitly—within the span
    /// `parent_span`:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let parent_span = expect::span().named("parent_span");
    /// let span = expect::span()
    ///     .with_ancestry(expect::has_explicit_parent("parent_span"));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&parent_span)
    ///     .enter(&parent_span)
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let parent = tracing::info_span!("parent_span");
    ///     let _guard = parent.enter();
    ///     tracing::info_span!("span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// In the following example, we expect that the matched span is
    /// a contextually-determined root:
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_ancestry(expect::is_contextual_root());
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     tracing::info_span!("span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// In the example below, the expectation fails because the
    /// span is *contextually*—as opposed to explicitly—within the span
    /// `parent_span`:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let parent_span = expect::span().named("parent_span");
    /// let span = expect::span()
    ///     .with_ancestry(expect::has_explicit_parent("parent_span"));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(&parent_span)
    ///     .enter(&parent_span)
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     let parent = tracing::info_span!("parent_span");
    ///     let _guard = parent.enter();
    ///     tracing::info_span!("span");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
    /// [`MockSubscriber::enter`]: fn@crate::subscriber::MockSubscriber::enter
    /// [`MockSubscriber::exit`]: fn@crate::subscriber::MockSubscriber::exit
    /// [`MockSubscriber::new_span`]: fn@crate::subscriber::MockSubscriber::new_span
    pub fn with_ancestry(self, ancestry: ExpectedAncestry) -> NewSpan {
        NewSpan {
            ancestry: Some(ancestry),
            span: self,
            ..Default::default()
        }
    }

    /// Adds fields to expect when matching a span.
    ///
    /// **Note**: This method returns a [`NewSpan`] and as such, this
    /// expectation can only be validated when expecting a new span via
    /// [`MockSubscriber::new_span`]. It cannot be validated on
    /// [`MockSubscriber::enter`], [`MockSubscriber::exit`], or any other
    /// method on [`MockSubscriber`] that takes an `ExpectedSpan`.
    ///
    /// If a span is recorded with fields that do not match the provided
    /// [`ExpectedFields`], this expectation will fail.
    ///
    /// If the provided field is not present on the recorded span or
    /// if the value for that field diffs, then the expectation
    /// will fail.
    ///
    /// More information on the available validations is available in
    /// the [`ExpectedFields`] documentation.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_fields(expect::field("field.name").with_value(&"field_value"));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     tracing::info_span!("span", field.name = "field_value");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// A different field value will cause the expectation to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{expect, subscriber};
    ///
    /// let span = expect::span()
    ///     .with_fields(expect::field("field.name").with_value(&"field_value"));
    ///
    /// let (subscriber, handle) = subscriber::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::subscriber::with_default(subscriber, || {
    ///     tracing::info_span!("span", field.name = "different_field_value");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`ExpectedFields`]: struct@crate::field::ExpectedFields
    /// [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
    /// [`MockSubscriber::enter`]: fn@crate::subscriber::MockSubscriber::enter
    /// [`MockSubscriber::exit`]: fn@crate::subscriber::MockSubscriber::exit
    /// [`MockSubscriber::new_span`]: fn@crate::subscriber::MockSubscriber::new_span
    pub fn with_fields<I>(self, fields: I) -> NewSpan
    where
        I: Into<ExpectedFields>,
    {
        NewSpan {
            span: self,
            fields: fields.into(),
            ..Default::default()
        }
    }

    pub(crate) fn id(&self) -> Option<&ExpectedId> {
        self.id.as_ref()
    }

    pub(crate) fn name(&self) -> Option<&str> {
        self.metadata.name.as_ref().map(String::as_ref)
    }

    pub(crate) fn level(&self) -> Option<tracing::Level> {
        self.metadata.level
    }

    pub(crate) fn target(&self) -> Option<&str> {
        self.metadata.target.as_deref()
    }

    pub(crate) fn check(&self, actual: &ActualSpan, ctx: impl fmt::Display, subscriber_name: &str) {
        if let Some(expected_id) = &self.id {
            expected_id.check(&actual.id(), format_args!("{ctx} a span"), subscriber_name);
        }

        match actual.metadata() {
            Some(actual_metadata) => self.metadata.check(actual_metadata, ctx, subscriber_name),
            None => {
                if self.metadata.has_expectations() {
                    panic!(
                        "{}",
                        format_args!(
                            "[{subscriber_name}] expected {ctx} a span with valid metadata, \
                            but got one with unknown Id={actual_id}",
                            actual_id = actual.id().into_u64()
                        )
                    );
                }
            }
        }
    }
}

impl fmt::Debug for ExpectedSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("MockSpan");

        if let Some(id) = self.id() {
            s.field("id", &id);
        }

        if let Some(name) = self.name() {
            s.field("name", &name);
        }

        if let Some(level) = self.level() {
            s.field("level", &format_args!("{:?}", level));
        }

        if let Some(target) = self.target() {
            s.field("target", &target);
        }

        s.finish()
    }
}

impl fmt::Display for ExpectedSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.metadata.name.is_some() {
            write!(f, "a span{}", self.metadata)
        } else {
            write!(f, "any span{}", self.metadata)
        }
    }
}

impl<S> From<S> for NewSpan
where
    S: Into<ExpectedSpan>,
{
    fn from(span: S) -> Self {
        Self {
            span: span.into(),
            ..Default::default()
        }
    }
}

impl NewSpan {
    /// Configures this `NewSpan` to expect the specified [`ExpectedAncestry`].
    /// A span's ancestry indicates whether it has a parent or is a root span
    /// and whether the parent is explitly or contextually assigned.
    ///
    /// For more information and examples, see the documentation on
    /// [`ExpectedSpan::with_ancestry`].
    pub fn with_ancestry(self, ancestry: ExpectedAncestry) -> NewSpan {
        NewSpan {
            ancestry: Some(ancestry),
            ..self
        }
    }

    /// Adds fields to expect when matching a span.
    ///
    /// For more information and examples, see the documentation on
    /// [`ExpectedSpan::with_fields`].
    ///
    /// [`ExpectedSpan::with_fields`]: fn@crate::span::ExpectedSpan::with_fields
    pub fn with_fields<I>(self, fields: I) -> NewSpan
    where
        I: Into<ExpectedFields>,
    {
        NewSpan {
            fields: fields.into(),
            ..self
        }
    }

    pub(crate) fn check(
        &mut self,
        span: &tracing_core::span::Attributes<'_>,
        get_ancestry: impl FnOnce() -> ActualAncestry,
        subscriber_name: &str,
    ) {
        let meta = span.metadata();
        let name = meta.name();
        self.span
            .metadata
            .check(meta, "a new span", subscriber_name);
        let mut checker = self.fields.checker(name, subscriber_name);
        span.record(&mut checker);
        checker.finish();

        if let Some(ref expected_ancestry) = self.ancestry {
            let actual_ancestry = get_ancestry();
            expected_ancestry.check(
                &actual_ancestry,
                format_args!("span `{}`", name),
                subscriber_name,
            );
        }
    }
}

impl fmt::Display for NewSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "a new span{}", self.span.metadata)?;
        if !self.fields.is_empty() {
            write!(f, " with {}", self.fields)?;
        }
        Ok(())
    }
}

impl fmt::Debug for NewSpan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("NewSpan");

        if let Some(name) = self.span.name() {
            s.field("name", &name);
        }

        if let Some(level) = self.span.level() {
            s.field("level", &format_args!("{:?}", level));
        }

        if let Some(target) = self.span.target() {
            s.field("target", &target);
        }

        if let Some(ref parent) = self.ancestry {
            s.field("parent", &format_args!("{:?}", parent));
        }

        if !self.fields.is_empty() {
            s.field("fields", &self.fields);
        }

        s.finish()
    }
}

impl PartialEq for ExpectedId {
    fn eq(&self, other: &Self) -> bool {
        self.inner.load(Ordering::Relaxed) == other.inner.load(Ordering::Relaxed)
    }
}

impl Eq for ExpectedId {}

impl fmt::Debug for ExpectedId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ExpectedId").field(&self.inner).finish()
    }
}

impl ExpectedId {
    const UNSET: u64 = 0;

    pub(crate) fn new_unset() -> Self {
        Self {
            inner: Arc::new(AtomicU64::from(Self::UNSET)),
        }
    }

    pub(crate) fn set(&self, span_id: u64) -> Result<(), SetActualSpanIdError> {
        self.inner
            .compare_exchange(Self::UNSET, span_id, Ordering::Relaxed, Ordering::Relaxed)
            .map_err(|current| SetActualSpanIdError {
                previous_span_id: current,
                new_span_id: span_id,
            })?;
        Ok(())
    }

    pub(crate) fn check(
        &self,
        actual: &tracing_core::span::Id,
        ctx: fmt::Arguments<'_>,
        subscriber_name: &str,
    ) {
        let expected_id = self.inner.load(Ordering::Relaxed);
        let actual_id = actual.into_u64();

        assert!(
            expected_id != Self::UNSET,
            "{}",
            format!(
                "\n[{subscriber_name}] expected {ctx} with an expected Id set,\n\
                [{subscriber_name}] but it hasn't been, perhaps this `ExpectedId` \
                wasn't used in a call to `new_span()`?"
            )
        );

        assert_eq!(
            expected_id,
            actual_id,
            "{}",
            format_args!(
                "\n[{subscriber_name}] expected {ctx} with Id `{expected_id}`,\n\
                [{subscriber_name}] but got one with Id `{actual_id}` instead",
            )
        );
    }
}

#[derive(Debug)]
pub(crate) struct SetActualSpanIdError {
    previous_span_id: u64,
    new_span_id: u64,
}

impl fmt::Display for SetActualSpanIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Could not set `ExpecedId` to {new}, \
            it had already been set to {previous}",
            new = self.new_span_id,
            previous = self.previous_span_id
        )
    }
}

impl error::Error for SetActualSpanIdError {}