🛈 Note: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem.

For the release documentation, please see docs.rs, instead.

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
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
//! An implementation of the [`Collect`] trait to receive and validate
//! `tracing` data.
//!
//! The [`MockCollector`] is the central component of this crate. The
//! `MockCollector` has expectations set on it which are later
//! validated as the code under test is run.
//!
//! # Examples
//!
//! ```
//! use tracing_mock::{collector, expect, field};
//!
//! let (collector, handle) = collector::mock()
//!     // Expect a single event with a specified message
//!     .event(expect::event().with_fields(expect::message("droids")))
//!     .only()
//!     .run_with_handle();
//!
//! // Use `with_default` to apply the `MockCollector` for the duration
//! // of the closure - this is what we are testing.
//! tracing::collect::with_default(collector, || {
//!     // These *are* the droids we are looking for
//!     tracing::info!("droids");
//! });
//!
//! // Use the handle to check the assertions. This line will panic if an
//! // assertion is not met.
//! handle.assert_finished();
//! ```
//!
//! A more complex example may consider multiple spans and events with
//! their respective fields:
//!
//! ```
//! use tracing_mock::{collector, expect, field};
//!
//! let span = expect::span()
//!     .named("my_span");
//! let (collector, handle) = collector::mock()
//!     // Enter a matching span
//!     .enter(span.clone())
//!     // Record an event with message "collect parting message"
//!     .event(expect::event().with_fields(expect::message("collect parting message")))
//!     // Record a value for the field `parting` on a matching span
//!     .record(span.clone(), expect::field("parting").with_value(&"goodbye world!"))
//!     // Exit a matching span
//!     .exit(span)
//!     // Expect no further messages to be recorded
//!     .only()
//!     // Return the collector and handle
//!     .run_with_handle();
//!
//! // Use `with_default` to apply the `MockCollector` for the duration
//! // of the closure - this is what we are testing.
//! tracing::collect::with_default(collector, || {
//!     let span = tracing::trace_span!(
//!         "my_span",
//!         greeting = "hello world",
//!         parting = tracing::field::Empty
//!     );
//!
//!     let _guard = span.enter();
//!     tracing::info!("collect parting message");
//!     let parting = "goodbye world!";
//!
//!     span.record("parting", &parting);
//! });
//!
//! // Use the handle to check the assertions. This line will panic if an
//! // assertion is not met.
//! handle.assert_finished();
//! ```
//!
//! If we modify the previous example so that we **don't** enter the
//! span before recording an event, the test will fail:
//!
//! ```should_panic
//! use tracing_mock::{collector, expect, field};
//!
//! let span = expect::span()
//!     .named("my_span");
//! let (collector, handle) = collector::mock()
//!     .enter(span.clone())
//!     .event(expect::event().with_fields(expect::message("collect parting message")))
//!     .record(span.clone(), expect::field("parting").with_value(&"goodbye world!"))
//!     .exit(span)
//!     .only()
//!     .run_with_handle();
//!
//! // Use `with_default` to apply the `MockCollector` for the duration
//! // of the closure - this is what we are testing.
//! tracing::collect::with_default(collector, || {
//!     let span = tracing::trace_span!(
//!         "my_span",
//!         greeting = "hello world",
//!         parting = tracing::field::Empty
//!     );
//!
//!     // Don't enter the span.
//!     // let _guard = span.enter();
//!     tracing::info!("collect parting message");
//!     let parting = "goodbye world!";
//!
//!     span.record("parting", &parting);
//! });
//!
//! // Use the handle to check the assertions. This line will panic if an
//! // assertion is not met.
//! handle.assert_finished();
//! ```
//!
//! This will result in an error message such as the following:
//!
//! ```text
//! thread 'main' panicked at '
//! [main] expected to enter a span named `my_span`
//! [main] but instead observed event Event {
//!     fields: ValueSet {
//!         message: collect parting message,
//!         callsite: Identifier(0x10eda3278),
//!     },
//!     metadata: Metadata {
//!         name: "event src/collector.rs:27",
//!         target: "rust_out",
//!         level: Level(
//!             Info,
//!         ),
//!         module_path: "rust_out",
//!         location: src/collector.rs:27,
//!         fields: {message},
//!         callsite: Identifier(0x10eda3278),
//!         kind: Kind(EVENT),
//!     },
//!     parent: Current,
//! }', tracing/tracing-mock/src/expect.rs:59:33
//! ```
//!
//! [`Collect`]: trait@tracing::Collect
//! [`MockCollector`]: struct@crate::collector::MockCollector
use crate::{
    event::ExpectedEvent,
    expect::Expect,
    field::ExpectedFields,
    span::{ExpectedSpan, NewSpan},
};
use std::{
    collections::{HashMap, VecDeque},
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc, Mutex,
    },
    thread,
};
use tracing::{
    collect::Interest,
    level_filters::LevelFilter,
    span::{self, Attributes, Id},
    Collect, Event, Metadata,
};

pub(crate) struct SpanState {
    name: &'static str,
    refs: usize,
    meta: &'static Metadata<'static>,
}

impl SpanState {
    pub(crate) fn metadata(&self) -> &'static Metadata<'static> {
        self.meta
    }
}

struct Running<F: Fn(&Metadata<'_>) -> bool> {
    spans: Mutex<HashMap<Id, SpanState>>,
    expected: Arc<Mutex<VecDeque<Expect>>>,
    current: Mutex<Vec<Id>>,
    ids: AtomicUsize,
    max_level: Option<LevelFilter>,
    filter: F,
    name: String,
}

/// A collector which can validate received traces.
///
/// For a detailed description and examples see the documentation
/// for the methods and the [`collector`] module.
///
/// [`collector`]: mod@crate::collector
pub struct MockCollector<F: Fn(&Metadata<'_>) -> bool> {
    expected: VecDeque<Expect>,
    max_level: Option<LevelFilter>,
    filter: F,
    name: String,
}

/// A handle which is used to invoke validation of expectations.
///
/// The handle is currently only used to assert that all the expected
/// events and spans were seen.
///
/// For additional information and examples, see the [`collector`]
/// module documentation.
///
/// [`collector`]: mod@crate::collector
pub struct MockHandle(Arc<Mutex<VecDeque<Expect>>>, String);

/// Create a new [`MockCollector`].
///
/// For additional information and examples, see the [`collector`]
/// module and [`MockCollector`] documentation.
///
/// # Examples
///
///
/// ```
/// use tracing_mock::{collector, expect, field};
///
/// let span = expect::span()
///     .named("my_span");
/// let (collector, handle) = collector::mock()
///     // Enter a matching span
///     .enter(span.clone())
///     // Record an event with message "collect parting message"
///     .event(expect::event().with_fields(expect::message("collect parting message")))
///     // Record a value for the field `parting` on a matching span
///     .record(span.clone(), expect::field("parting").with_value(&"goodbye world!"))
///     // Exit a matching span
///     .exit(span)
///     // Expect no further messages to be recorded
///     .only()
///     // Return the collector and handle
///     .run_with_handle();
///
/// // Use `with_default` to apply the `MockCollector` for the duration
/// // of the closure - this is what we are testing.
/// tracing::collect::with_default(collector, || {
///     let span = tracing::trace_span!(
///         "my_span",
///         greeting = "hello world",
///         parting = tracing::field::Empty
///     );
///
///     let _guard = span.enter();
///     tracing::info!("collect parting message");
///     let parting = "goodbye world!";
///
///     span.record("parting", &parting);
/// });
///
/// // Use the handle to check the assertions. This line will panic if an
/// // assertion is not met.
/// handle.assert_finished();
/// ```
///
/// [`collector`]: mod@crate::collector
#[must_use]
pub fn mock() -> MockCollector<fn(&Metadata<'_>) -> bool> {
    MockCollector {
        expected: VecDeque::new(),
        filter: (|_: &Metadata<'_>| true) as for<'r, 's> fn(&'r Metadata<'s>) -> _,
        max_level: None,
        name: thread::current()
            .name()
            .unwrap_or("mock_subscriber")
            .to_string(),
    }
}

impl<F> MockCollector<F>
where
    F: Fn(&Metadata<'_>) -> bool + 'static,
{
    /// Overrides the name printed by the mock subscriber's debugging output.
    ///
    /// The debugging output is displayed if the test panics, or if the test is
    /// run with `--nocapture`.
    ///
    /// By default, the mock collector's name is the  name of the test
    /// (*technically*, the name of the thread where it was created, which is
    /// the name of the test unless tests are run with `--test-threads=1`).
    /// When a test has only one mock collector, this is sufficient. However,
    /// some tests may include multiple collectors, in order to test
    /// interactions between multiple collectors. In that case, it can be
    /// helpful to give each collector a separate name to distinguish where the
    /// debugging output comes from.
    ///
    /// # Examples
    ///
    /// In the following example, we create 2 collectors, both
    /// expecting to receive an event. As we only record a single
    /// event, the test will fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector_1, handle_1) = collector::mock()
    ///     .named("collector-1")
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// let (collector_2, handle_2) = collector::mock()
    ///     .named("collector-2")
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// let _guard = tracing::collect::set_default(collector_2);
    ///
    /// tracing::collect::with_default(collector_1, || {
    ///     tracing::info!("a");
    /// });
    ///
    /// handle_1.assert_finished();
    /// handle_2.assert_finished();
    /// ```
    ///
    /// In the test output, we see that the collector which didn't
    /// received the event was the one named `collector-2`, which is
    /// correct as the collector named `collector-1` was the default
    /// when the event was recorded:
    ///
    /// ```text
    /// [collector-2] more notifications expected: [
    ///     Event(
    ///         MockEvent,
    ///     ),
    /// ]', tracing-mock/src/collector.rs:1276:13
    /// ```
    pub fn named(self, name: impl ToString) -> Self {
        Self {
            name: name.to_string(),
            ..self
        }
    }

    /// Adds an expectation that an event matching the [`ExpectedEvent`]
    /// will be recorded next.
    ///
    /// The `event` can be a default mock which will match any event
    /// (`expect::event()`) or can include additional expectations.
    /// See the [`ExpectedEvent`] documentation for more details.
    ///
    /// If an event is recorded that doesn't match the `ExpectedEvent`,
    /// or if something else (such as entering a span) is recorded
    /// first, then the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// A span is entered before the event, causing the test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("span");
    ///     let _guard = span.enter();
    ///     tracing::info!("a");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn event(mut self, event: ExpectedEvent) -> Self {
        self.expected.push_back(Expect::Event(event));
        self
    }

    /// Adds an expectation that the creation of a span will be
    /// recorded next.
    ///
    /// This function accepts `Into<NewSpan>` instead of
    /// [`ExpectedSpan`] directly, so it can be used to test
    /// span fields and the span parent. This is because a
    /// collector only receives the span fields and parent when
    /// a span is created, not when it is entered.
    ///
    /// The new span doesn't need to be entered for this expectation
    /// to succeed.
    ///
    /// If a span is recorded that doesn't match the `ExpectedSpan`,
    /// or if something else (such as an event) is recorded first,
    /// then the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing")
    ///     .with_fields(expect::field("testing").with_value(&"yes"));
    /// let (collector, handle) = collector::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     _ = tracing::info_span!("the span we're testing", testing = "yes");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// An event is recorded before the span is created, causing the
    /// test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing")
    ///     .with_fields(expect::field("testing").with_value(&"yes"));
    /// let (collector, handle) = collector::mock()
    ///     .new_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("an event");
    ///     _ = tracing::info_span!("the span we're testing", testing = "yes");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn new_span<I>(mut self, new_span: I) -> Self
    where
        I: Into<NewSpan>,
    {
        self.expected.push_back(Expect::NewSpan(new_span.into()));
        self
    }

    /// Adds an expectation that entering a span matching the
    /// [`ExpectedSpan`] will be recorded next.
    ///
    /// This expectation is generally accompanied by a call to
    /// [`exit`] as well. If used together with [`only`], this
    /// is necessary.
    ///
    /// If the span that is entered doesn't match the [`ExpectedSpan`],
    /// or if something else (such as an event) is recorded first,
    /// then the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .enter(span.clone())
    ///     .exit(span)
    ///     .only()
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("the span we're testing");
    ///     let _entered = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// An event is recorded before the span is entered, causing the
    /// test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .enter(span.clone())
    ///     .exit(span)
    ///     .only()
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("an event");
    ///     let span = tracing::info_span!("the span we're testing");
    ///     let _entered = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`exit`]: fn@Self::exit
    /// [`only`]: fn@Self::only
    pub fn enter(mut self, span: ExpectedSpan) -> Self {
        self.expected.push_back(Expect::Enter(span));
        self
    }

    /// Adds ab expectation that exiting a span matching the
    /// [`ExpectedSpan`] will be recorded next.
    ///
    /// As a span may be entered and exited multiple times,
    /// this is different from the span being closed. In
    /// general [`enter`] and `exit` should be paired.
    ///
    /// If the span that is exited doesn't match the [`ExpectedSpan`],
    /// or if something else (such as an event) is recorded first,
    /// then the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .enter(span.clone())
    ///     .exit(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("the span we're testing");
    ///     let _entered = span.enter();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// An event is recorded before the span is exited, causing the
    /// test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .enter(span.clone())
    ///     .exit(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("the span we're testing");
    ///     let _entered = span.enter();
    ///     tracing::info!("an event");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`enter`]: fn@Self::enter
    pub fn exit(mut self, span: ExpectedSpan) -> Self {
        self.expected.push_back(Expect::Exit(span));
        self
    }

    /// Adds an expectation that cloning a span matching the
    /// [`ExpectedSpan`] will be recorded next.
    ///
    /// The cloned span does need to be entered.
    ///
    /// If the span that is cloned doesn't match the [`ExpectedSpan`],
    /// or if something else (such as an event) is recorded first,
    /// then the expectation will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .clone_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("the span we're testing");
    ///     _ = span.clone();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// An event is recorded before the span is cloned, causing the
    /// test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .at_level(tracing::Level::INFO)
    ///     .named("the span we're testing");
    /// let (collector, handle) = collector::mock()
    ///     .clone_span(span)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::info_span!("the span we're testing");
    ///     tracing::info!("an event");
    ///     _ = span.clone();
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn clone_span(mut self, span: ExpectedSpan) -> Self {
        self.expected.push_back(Expect::CloneSpan(span));
        self
    }

    /// **This method is deprecated.**
    ///
    /// Adds an expectation that a span matching the [`ExpectedSpan`]
    /// getting dropped via the deprecated function
    /// [`Collect::drop_span`] will be recorded next.
    ///
    /// Instead [`Collect::try_close`] should be used on the collector
    /// and should be asserted with `close_span` (which hasn't been
    /// implemented yet, but will be done as part of #539).
    ///
    /// [`Collect::drop_span`]: fn@tracing::Collect::drop_span
    #[allow(deprecated)]
    pub fn drop_span(mut self, span: ExpectedSpan) -> Self {
        self.expected.push_back(Expect::DropSpan(span));
        self
    }

    /// Adds an expectation that a `follows_from` relationship will be
    /// recorded next. Specifically that a span matching `consequence`
    /// follows from a span matching `cause`.
    ///
    /// For further details on what this causal relationship means, see
    /// [`Span::follows_from`].
    ///
    /// If either of the 2 spans don't match their respective
    /// [`ExpectedSpan`] or if something else (such as an event) is
    /// recorded first, then the expectation will fail.
    ///
    /// **Note**: The 2 spans, `consequence` and `cause` are matched
    /// by `name` only.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let cause = expect::span().named("cause");
    /// let consequence = expect::span().named("consequence");
    ///
    /// let (collector, handle) = collector::mock()
    ///     .follows_from(consequence, cause)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let cause = tracing::info_span!("cause");
    ///     let consequence = tracing::info_span!("consequence");
    ///
    ///     consequence.follows_from(&cause);
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// The `cause` span doesn't match, it is actually recorded at
    /// `Level::WARN` instead of the expected `Level::INFO`, causing
    /// this test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let cause = expect::span().named("cause");
    /// let consequence = expect::span().named("consequence");
    ///
    /// let (collector, handle) = collector::mock()
    ///     .follows_from(consequence, cause)
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let cause = tracing::info_span!("another cause");
    ///     let consequence = tracing::info_span!("consequence");
    ///
    ///     consequence.follows_from(&cause);
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`Span::follows_from`]: fn@tracing::Span::follows_from
    pub fn follows_from(mut self, consequence: ExpectedSpan, cause: ExpectedSpan) -> Self {
        self.expected
            .push_back(Expect::FollowsFrom { consequence, cause });
        self
    }

    /// Adds an expectation that `fields` are recorded on a span
    /// matching the [`ExpectedSpan`] will be recorded next.
    ///
    /// For further information on how to specify the expected
    /// fields, see the documentation on the [`field`] module.
    ///
    /// If either the span doesn't match the [`ExpectedSpan`], the
    /// fields don't match the expected fields, or if something else
    /// (such as an event) is recorded first, then the expectation
    /// will fail.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .named("my_span");
    /// let (collector, handle) = collector::mock()
    ///     .record(span, expect::field("parting").with_value(&"goodbye world!"))
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::trace_span!(
    ///         "my_span",
    ///         greeting = "hello world",
    ///         parting = tracing::field::Empty
    ///     );
    ///     span.record("parting", "goodbye world!");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// The value of the recorded field doesn't match the expectation,
    /// causing the test to fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let span = expect::span()
    ///     .named("my_span");
    /// let (collector, handle) = collector::mock()
    ///     .record(span, expect::field("parting").with_value(&"goodbye world!"))
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     let span = tracing::trace_span!(
    ///         "my_span",
    ///         greeting = "hello world",
    ///         parting = tracing::field::Empty
    ///     );
    ///     span.record("parting", "goodbye universe!");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`field`]: mod@crate::field
    pub fn record<I>(mut self, span: ExpectedSpan, fields: I) -> Self
    where
        I: Into<ExpectedFields>,
    {
        self.expected.push_back(Expect::Visit(span, fields.into()));
        self
    }

    /// Filter the traces evaluated by the `MockCollector`.
    ///
    /// The filter will be applied to all traces received before
    /// any validation occurs - so its position in the call chain
    /// is not important. The filter does not perform any validation
    /// itself.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .with_filter(|meta| meta.level() <= &tracing::Level::WARN)
    ///     .event(expect::event())
    ///     .only()
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    ///     tracing::warn!("b");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn with_filter<G>(self, filter: G) -> MockCollector<G>
    where
        G: Fn(&Metadata<'_>) -> bool + 'static,
    {
        MockCollector {
            expected: self.expected,
            filter,
            max_level: self.max_level,
            name: self.name,
        }
    }

    /// Sets the max level that will be provided to the `tracing`
    /// system.
    ///
    /// This method can be used to test the internals of `tracing`,
    /// but it is also useful to filter out traces on more verbose
    /// levels if you only want to verify above a certain level.
    ///
    /// **Note**: this value determines a global filter, if
    /// `with_max_level_hint` is called on multiple collectors, the
    /// global filter will be the least restrictive of all collectors.
    /// To filter the events evaluated by a specific `MockCollector`,
    /// use [`with_filter`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .with_max_level_hint(tracing::Level::INFO)
    ///     .event(expect::event().at_level(tracing::Level::INFO))
    ///     .only()
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::debug!("a message we don't care about");
    ///     tracing::info!("a message we want to validate");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`with_filter`]: fn@Self::with_filter
    pub fn with_max_level_hint(self, hint: impl Into<LevelFilter>) -> Self {
        Self {
            max_level: Some(hint.into()),
            ..self
        }
    }

    /// Expects that no further traces are received.
    ///
    /// The call to `only` should appear immediately before the final
    /// call to `run` or `run_with_handle`, as any expectations which
    /// are added after `only` will not be considered.
    ///
    /// # Examples
    ///
    /// Consider this simple test. It passes even though we only
    /// expect a single event, but receive three:
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    ///     tracing::info!("b");
    ///     tracing::info!("c");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// After including `only`, the test will fail:
    ///
    /// ```should_panic
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .only()
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    ///     tracing::info!("b");
    ///     tracing::info!("c");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    pub fn only(mut self) -> Self {
        self.expected.push_back(Expect::Nothing);
        self
    }

    /// Consume the receiver and return an `impl` [`Collect`] which can
    /// be set as the default collector.
    ///
    /// This function is similar to [`run_with_handle`], but it doesn't
    /// return a [`MockHandle`]. This is useful if the desired
    /// assertions can be checked externally to the collector.
    ///
    /// # Examples
    ///
    /// The following test is used within the `tracing`
    /// codebase:
    ///
    /// ```
    /// use tracing_mock::collector;
    ///
    /// tracing::collect::with_default(collector::mock().run(), || {
    ///     let foo1 = tracing::span!(tracing::Level::TRACE, "foo");
    ///     let foo2 = foo1.clone();
    ///     // Two handles that point to the same span are equal.
    ///     assert_eq!(foo1, foo2);
    /// });
    /// ```
    ///
    /// [`Collect`]: tracing::Collect
    /// [`run_with_handle`]: fn@Self::run_with_handle
    pub fn run(self) -> impl Collect {
        let (collector, _) = self.run_with_handle();
        collector
    }

    /// Consume the receiver and return an `impl` [`Collect`] which can
    /// be set as the default collector and a [`MockHandle`] which can
    /// be used to validate the provided expectations.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// // collector and handle are returned from `run_with_handle()`
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    /// });
    ///
    /// handle.assert_finished();
    /// ```
    ///
    /// [`Collect`]: tracing::Collect
    pub fn run_with_handle(self) -> (impl Collect, MockHandle) {
        let expected = Arc::new(Mutex::new(self.expected));
        let handle = MockHandle(expected.clone(), self.name.clone());
        let collector = Running {
            spans: Mutex::new(HashMap::new()),
            expected,
            current: Mutex::new(Vec::new()),
            ids: AtomicUsize::new(1),
            filter: self.filter,
            max_level: self.max_level,
            name: self.name,
        };
        (collector, handle)
    }
}

impl<F> Collect for Running<F>
where
    F: Fn(&Metadata<'_>) -> bool + 'static,
{
    fn enabled(&self, meta: &Metadata<'_>) -> bool {
        println!("[{}] enabled: {:#?}", self.name, meta);
        let enabled = (self.filter)(meta);
        println!("[{}] enabled -> {}", self.name, enabled);
        enabled
    }

    fn register_callsite(&self, meta: &'static Metadata<'static>) -> Interest {
        println!("[{}] register_callsite: {:#?}", self.name, meta);
        if self.enabled(meta) {
            Interest::always()
        } else {
            Interest::never()
        }
    }
    fn max_level_hint(&self) -> Option<LevelFilter> {
        self.max_level
    }

    fn record(&self, id: &Id, values: &span::Record<'_>) {
        let spans = self.spans.lock().unwrap();
        let mut expected = self.expected.lock().unwrap();
        let span = spans
            .get(id)
            .unwrap_or_else(|| panic!("[{}] no span for ID {:?}", self.name, id));
        println!(
            "[{}] record: {}; id={:?}; values={:?};",
            self.name, span.name, id, values
        );
        let was_expected = matches!(expected.front(), Some(Expect::Visit(_, _)));
        if was_expected {
            if let Expect::Visit(expected_span, mut expected_values) = expected.pop_front().unwrap()
            {
                if let Some(name) = expected_span.name() {
                    assert_eq!(name, span.name);
                }
                let context = format!("span {}: ", span.name);
                let mut checker = expected_values.checker(&context, &self.name);
                values.record(&mut checker);
                checker.finish();
            }
        }
    }

    fn event(&self, event: &Event<'_>) {
        let name = event.metadata().name();
        println!("[{}] event: {};", self.name, name);
        match self.expected.lock().unwrap().pop_front() {
            None => {}
            Some(Expect::Event(mut expected)) => {
                #[cfg(feature = "tracing-subscriber")]
                {
                    if expected.scope_mut().is_some() {
                        unimplemented!(
                            "Expected scope for events is not supported with `MockCollector`."
                        )
                    }
                }
                let get_parent_name = || {
                    let stack = self.current.lock().unwrap();
                    let spans = self.spans.lock().unwrap();
                    event
                        .parent()
                        .and_then(|id| spans.get(id))
                        .or_else(|| stack.last().and_then(|id| spans.get(id)))
                        .map(|s| s.name.to_string())
                };
                expected.check(event, get_parent_name, &self.name);
            }
            Some(ex) => ex.bad(&self.name, format_args!("observed event {:#?}", event)),
        }
    }

    fn record_follows_from(&self, consequence_id: &Id, cause_id: &Id) {
        let spans = self.spans.lock().unwrap();
        if let Some(consequence_span) = spans.get(consequence_id) {
            if let Some(cause_span) = spans.get(cause_id) {
                println!(
                    "[{}] record_follows_from: {} (id={:?}) follows {} (id={:?})",
                    self.name, consequence_span.name, consequence_id, cause_span.name, cause_id,
                );
                match self.expected.lock().unwrap().pop_front() {
                    None => {}
                    Some(Expect::FollowsFrom {
                        consequence: ref expected_consequence,
                        cause: ref expected_cause,
                    }) => {
                        if let Some(name) = expected_consequence.name() {
                            // TODO(hds): Write proper assertion text.
                            assert_eq!(name, consequence_span.name);
                        }
                        if let Some(name) = expected_cause.name() {
                            // TODO(hds): Write proper assertion text.
                            assert_eq!(name, cause_span.name);
                        }
                    }
                    Some(ex) => ex.bad(
                        &self.name,
                        format_args!(
                            "consequence {:?} followed cause {:?}",
                            consequence_span.name, cause_span.name
                        ),
                    ),
                }
            }
        };
    }

    fn new_span(&self, span: &Attributes<'_>) -> Id {
        let meta = span.metadata();
        let id = self.ids.fetch_add(1, Ordering::SeqCst);
        let id = Id::from_u64(id as u64);
        println!(
            "[{}] new_span: name={:?}; target={:?}; id={:?};",
            self.name,
            meta.name(),
            meta.target(),
            id
        );
        let mut expected = self.expected.lock().unwrap();
        let was_expected = matches!(expected.front(), Some(Expect::NewSpan(_)));
        let mut spans = self.spans.lock().unwrap();
        if was_expected {
            if let Expect::NewSpan(mut expected) = expected.pop_front().unwrap() {
                let get_parent_name = || {
                    let stack = self.current.lock().unwrap();
                    span.parent()
                        .and_then(|id| spans.get(id))
                        .or_else(|| stack.last().and_then(|id| spans.get(id)))
                        .map(|s| s.name.to_string())
                };
                expected.check(span, get_parent_name, &self.name);
            }
        }
        spans.insert(
            id.clone(),
            SpanState {
                name: meta.name(),
                refs: 1,
                meta,
            },
        );
        id
    }

    fn enter(&self, id: &Id) {
        let spans = self.spans.lock().unwrap();
        if let Some(span) = spans.get(id) {
            println!("[{}] enter: {}; id={:?};", self.name, span.name, id);
            match self.expected.lock().unwrap().pop_front() {
                None => {}
                Some(Expect::Enter(ref expected_span)) => {
                    expected_span.check(span, &self.name);
                }
                Some(ex) => ex.bad(&self.name, format_args!("entered span {:?}", span.name)),
            }
        };
        self.current.lock().unwrap().push(id.clone());
    }

    fn exit(&self, id: &Id) {
        if std::thread::panicking() {
            // `exit()` can be called in `drop` impls, so we must guard against
            // double panics.
            println!("[{}] exit {:?} while panicking", self.name, id);
            return;
        }
        let spans = self.spans.lock().unwrap();
        let span = spans
            .get(id)
            .unwrap_or_else(|| panic!("[{}] no span for ID {:?}", self.name, id));
        println!("[{}] exit: {}; id={:?};", self.name, span.name, id);
        match self.expected.lock().unwrap().pop_front() {
            None => {}
            Some(Expect::Exit(ref expected_span)) => {
                expected_span.check(span, &self.name);
                let curr = self.current.lock().unwrap().pop();
                assert_eq!(
                    Some(id),
                    curr.as_ref(),
                    "[{}] exited span {:?}, but the current span was {:?}",
                    self.name,
                    span.name,
                    curr.as_ref().and_then(|id| spans.get(id)).map(|s| s.name)
                );
            }
            Some(ex) => ex.bad(&self.name, format_args!("exited span {:?}", span.name)),
        };
    }

    fn clone_span(&self, id: &Id) -> Id {
        let name = self.spans.lock().unwrap().get_mut(id).map(|span| {
            let name = span.name;
            println!(
                "[{}] clone_span: {}; id={:?}; refs={:?};",
                self.name, name, id, span.refs
            );
            span.refs += 1;
            name
        });
        if name.is_none() {
            println!("[{}] clone_span: id={:?};", self.name, id);
        }
        let mut expected = self.expected.lock().unwrap();
        let was_expected = if let Some(Expect::CloneSpan(ref span)) = expected.front() {
            assert_eq!(
                name,
                span.name(),
                "[{}] expected to clone a span named {:?}",
                self.name,
                span.name()
            );
            true
        } else {
            false
        };
        if was_expected {
            expected.pop_front();
        }
        id.clone()
    }

    fn drop_span(&self, id: Id) {
        let mut is_event = false;
        let name = if let Ok(mut spans) = self.spans.try_lock() {
            spans.get_mut(&id).map(|span| {
                let name = span.name;
                if name.contains("event") {
                    is_event = true;
                }
                println!(
                    "[{}] drop_span: {}; id={:?}; refs={:?};",
                    self.name, name, id, span.refs
                );
                span.refs -= 1;
                name
            })
        } else {
            None
        };
        if name.is_none() {
            println!("[{}] drop_span: id={:?}", self.name, id);
        }
        if let Ok(mut expected) = self.expected.try_lock() {
            let was_expected = match expected.front() {
                Some(Expect::DropSpan(ref span)) => {
                    // Don't assert if this function was called while panicking,
                    // as failing the assertion can cause a double panic.
                    if !::std::thread::panicking() {
                        assert_eq!(name, span.name());
                    }
                    true
                }
                Some(Expect::Event(_)) => {
                    if !::std::thread::panicking() {
                        assert!(is_event, "[{}] expected an event", self.name);
                    }
                    true
                }
                _ => false,
            };
            if was_expected {
                expected.pop_front();
            }
        }
    }

    fn current_span(&self) -> tracing_core::span::Current {
        let stack = self.current.lock().unwrap();
        match stack.last() {
            Some(id) => {
                let spans = self.spans.lock().unwrap();
                let state = spans.get(id).expect("state for current span");
                tracing_core::span::Current::new(id.clone(), state.meta)
            }
            None => tracing_core::span::Current::none(),
        }
    }
}

impl MockHandle {
    #[cfg(feature = "tracing-subscriber")]
    pub(crate) fn new(expected: Arc<Mutex<VecDeque<Expect>>>, name: String) -> Self {
        Self(expected, name)
    }

    /// Checks the expectations which were set on the
    /// [`MockCollector`].
    ///
    /// Calling `assert_finished` is usually the final part of a test.
    ///
    /// # Panics
    ///
    /// This method will panic if any of the provided expectations are
    /// not met.
    ///
    /// # Examples
    ///
    /// ```
    /// use tracing_mock::{collector, expect};
    ///
    /// let (collector, handle) = collector::mock()
    ///     .event(expect::event())
    ///     .run_with_handle();
    ///
    /// tracing::collect::with_default(collector, || {
    ///     tracing::info!("a");
    /// });
    ///
    /// // Check assertions set on the mock collector
    /// handle.assert_finished();
    /// ```
    pub fn assert_finished(&self) {
        if let Ok(ref expected) = self.0.lock() {
            assert!(
                !expected.iter().any(|thing| thing != &Expect::Nothing),
                "\n[{}] more notifications expected: {:#?}",
                self.1,
                **expected
            );
        }
    }
}