tracing_mock/
subscriber.rs

1//! An implementation of the [`Subscriber`] trait to receive and validate
2//! `tracing` data.
3//!
4//! The [`MockSubscriber`] is the central component of this crate. The
5//! `MockSubscriber` has expectations set on it which are later
6//! validated as the code under test is run.
7//!
8//! # Examples
9//!
10//! ```
11//! use tracing_mock::{expect, subscriber, field};
12//!
13//! let (subscriber, handle) = subscriber::mock()
14//!     // Expect a single event with a specified message
15//!     .event(expect::event().with_fields(expect::msg("droids")))
16//!     .only()
17//!     .run_with_handle();
18//!
19//! // Use `with_default` to apply the `MockSubscriber` for the duration
20//! // of the closure - this is what we are testing.
21//! tracing::subscriber::with_default(subscriber, || {
22//!     // These *are* the droids we are looking for
23//!     tracing::info!("droids");
24//! });
25//!
26//! // Use the handle to check the assertions. This line will panic if an
27//! // assertion is not met.
28//! handle.assert_finished();
29//! ```
30//!
31//! A more complex example may consider multiple spans and events with
32//! their respective fields:
33//!
34//! ```
35//! use tracing_mock::{expect, subscriber, field};
36//!
37//! let span = expect::span()
38//!     .named("my_span");
39//! let (subscriber, handle) = subscriber::mock()
40//!     // Enter a matching span
41//!     .enter(&span)
42//!     // Record an event with message "subscriber parting message"
43//!     .event(expect::event().with_fields(expect::msg("subscriber parting message")))
44//!     // Record a value for the field `parting` on a matching span
45//!     .record(&span, expect::field("parting").with_value(&"goodbye world!"))
46//!     // Exit a matching span
47//!     .exit(span)
48//!     // Expect no further messages to be recorded
49//!     .only()
50//!     // Return the subscriber and handle
51//!     .run_with_handle();
52//!
53//! // Use `with_default` to apply the `MockSubscriber` for the duration
54//! // of the closure - this is what we are testing.
55//! tracing::subscriber::with_default(subscriber, || {
56//!     let span = tracing::trace_span!(
57//!         "my_span",
58//!         greeting = "hello world",
59//!         parting = tracing::field::Empty
60//!     );
61//!
62//!     let _guard = span.enter();
63//!     tracing::info!("subscriber parting message");
64//!     let parting = "goodbye world!";
65//!
66//!     span.record("parting", &parting);
67//! });
68//!
69//! // Use the handle to check the assertions. This line will panic if an
70//! // assertion is not met.
71//! handle.assert_finished();
72//! ```
73//!
74//! If we modify the previous example so that we **don't** enter the
75//! span before recording an event, the test will fail:
76//!
77//! ```should_panic
78//! use tracing_mock::{expect, subscriber, field};
79//!
80//! let span = expect::span()
81//!     .named("my_span");
82//! let (subscriber, handle) = subscriber::mock()
83//!     .enter(&span)
84//!     .event(expect::event().with_fields(expect::msg("collect parting message")))
85//!     .record(&span, expect::field("parting").with_value(&"goodbye world!"))
86//!     .exit(span)
87//!     .only()
88//!     .run_with_handle();
89//!
90//! // Use `with_default` to apply the `MockSubscriber` for the duration
91//! // of the closure - this is what we are testing.
92//! tracing::subscriber::with_default(subscriber, || {
93//!     let span = tracing::trace_span!(
94//!         "my_span",
95//!         greeting = "hello world",
96//!         parting = tracing::field::Empty
97//!     );
98//!
99//!     // Don't enter the span.
100//!     // let _guard = span.enter();
101//!     tracing::info!("subscriber parting message");
102//!     let parting = "goodbye world!";
103//!
104//!     span.record("parting", &parting);
105//! });
106//!
107//! // Use the handle to check the assertions. This line will panic if an
108//! // assertion is not met.
109//! handle.assert_finished();
110//! ```
111//!
112//! This will result in an error message such as the following:
113//!
114//! ```text
115//! thread 'main' panicked at '
116//! [main] expected to enter a span named `my_span`
117//! [main] but instead observed event Event {
118//!     fields: ValueSet {
119//!         message: subscriber parting message,
120//!         callsite: Identifier(0x10eda3278),
121//!     },
122//!     metadata: Metadata {
123//!         name: "event src/subscriber.rs:27",
124//!         target: "rust_out",
125//!         level: Level(
126//!             Info,
127//!         ),
128//!         module_path: "rust_out",
129//!         location: src/subscriber.rs:27,
130//!         fields: {message},
131//!         callsite: Identifier(0x10eda3278),
132//!         kind: Kind(EVENT),
133//!     },
134//!     parent: Current,
135//! }', tracing/tracing-mock/src/expect.rs:59:33
136//! ```
137//!
138//! [`Subscriber`]: trait@tracing::Subscriber
139//! [`MockSubscriber`]: struct@crate::subscriber::MockSubscriber
140use std::{
141    collections::{HashMap, VecDeque},
142    sync::{
143        atomic::{AtomicUsize, Ordering},
144        Arc, Mutex,
145    },
146    thread,
147};
148use tracing::{
149    level_filters::LevelFilter,
150    span::{self, Attributes, Id},
151    subscriber::Interest,
152    Event, Metadata, Subscriber,
153};
154
155use crate::{
156    ancestry::get_ancestry,
157    event::ExpectedEvent,
158    expect::Expect,
159    field::ExpectedFields,
160    span::{ActualSpan, ExpectedSpan, NewSpan},
161};
162
163pub(crate) struct SpanState {
164    id: Id,
165    name: &'static str,
166    refs: usize,
167    meta: &'static Metadata<'static>,
168}
169
170impl From<&SpanState> for ActualSpan {
171    fn from(span_state: &SpanState) -> Self {
172        Self::new(span_state.id.clone(), Some(span_state.meta))
173    }
174}
175
176struct Running<F: Fn(&Metadata<'_>) -> bool> {
177    spans: Mutex<HashMap<Id, SpanState>>,
178    expected: Arc<Mutex<VecDeque<Expect>>>,
179    current: Mutex<Vec<Id>>,
180    ids: AtomicUsize,
181    max_level: Option<LevelFilter>,
182    filter: F,
183    name: String,
184}
185
186/// A subscriber which can validate received traces.
187///
188/// For a detailed description and examples see the documentation
189/// for the methods and the [`subscriber`] module.
190///
191/// [`subscriber`]: mod@crate::subscriber
192#[derive(Debug)]
193pub struct MockSubscriber<F: Fn(&Metadata<'_>) -> bool> {
194    expected: VecDeque<Expect>,
195    max_level: Option<LevelFilter>,
196    filter: F,
197    name: String,
198}
199
200/// A handle which is used to invoke validation of expectations.
201///
202/// The handle is currently only used to assert that all the expected
203/// events and spans were seen.
204///
205/// For additional information and examples, see the [`subscriber`]
206/// module documentation.
207///
208/// [`subscriber`]: mod@crate::subscriber
209#[derive(Debug)]
210pub struct MockHandle(Arc<Mutex<VecDeque<Expect>>>, String);
211
212/// Create a new [`MockSubscriber`].
213///
214/// For additional information and examples, see the [`subscriber`]
215/// module and [`MockSubscriber`] documentation.
216///
217/// # Examples
218///
219///
220/// ```
221/// use tracing_mock::{expect, subscriber, field};
222///
223/// let span = expect::span()
224///     .named("my_span");
225/// let (subscriber, handle) = subscriber::mock()
226///     // Enter a matching span
227///     .enter(&span)
228///     // Record an event with message "subscriber parting message"
229///     .event(expect::event().with_fields(expect::msg("subscriber parting message")))
230///     // Record a value for the field `parting` on a matching span
231///     .record(&span, expect::field("parting").with_value(&"goodbye world!"))
232///     // Exit a matching span
233///     .exit(span)
234///     // Expect no further messages to be recorded
235///     .only()
236///     // Return the subscriber and handle
237///     .run_with_handle();
238///
239/// // Use `with_default` to apply the `MockSubscriber` for the duration
240/// // of the closure - this is what we are testing.
241/// tracing::subscriber::with_default(subscriber, || {
242///     let span = tracing::trace_span!(
243///         "my_span",
244///         greeting = "hello world",
245///         parting = tracing::field::Empty
246///     );
247///
248///     let _guard = span.enter();
249///     tracing::info!("subscriber parting message");
250///     let parting = "goodbye world!";
251///
252///     span.record("parting", &parting);
253/// });
254///
255/// // Use the handle to check the assertions. This line will panic if an
256/// // assertion is not met.
257/// handle.assert_finished();
258/// ```
259///
260/// [`subscriber`]: mod@crate::subscriber
261#[must_use]
262pub fn mock() -> MockSubscriber<fn(&Metadata<'_>) -> bool> {
263    MockSubscriber {
264        expected: VecDeque::new(),
265        filter: (|_: &Metadata<'_>| true) as for<'r, 's> fn(&'r Metadata<'s>) -> _,
266        max_level: None,
267        name: thread::current()
268            .name()
269            .unwrap_or("mock_subscriber")
270            .to_string(),
271    }
272}
273
274impl<F> MockSubscriber<F>
275where
276    F: Fn(&Metadata<'_>) -> bool + 'static,
277{
278    /// Overrides the name printed by the mock subscriber's debugging output.
279    ///
280    /// The debugging output is displayed if the test panics, or if the test is
281    /// run with `--nocapture`.
282    ///
283    /// By default, the mock subscriber's name is the  name of the test
284    /// (*technically*, the name of the thread where it was created, which is
285    /// the name of the test unless tests are run with `--test-threads=1`).
286    /// When a test has only one mock subscriber, this is sufficient. However,
287    /// some tests may include multiple subscribers, in order to test
288    /// interactions between multiple subscribers. In that case, it can be
289    /// helpful to give each subscriber a separate name to distinguish where the
290    /// debugging output comes from.
291    ///
292    /// # Examples
293    ///
294    /// In the following example, we create 2 subscribers, both
295    /// expecting to receive an event. As we only record a single
296    /// event, the test will fail:
297    ///
298    /// ```should_panic
299    /// use tracing_mock::{expect, subscriber};
300    ///
301    /// let (subscriber_1, handle_1) = subscriber::mock()
302    ///     .named("subscriber-1")
303    ///     .event(expect::event())
304    ///     .run_with_handle();
305    ///
306    /// let (subscriber_2, handle_2) = subscriber::mock()
307    ///     .named("subscriber-2")
308    ///     .event(expect::event())
309    ///     .run_with_handle();
310    ///
311    /// let _guard = tracing::subscriber::set_default(subscriber_2);
312    ///
313    /// tracing::subscriber::with_default(subscriber_1, || {
314    ///     tracing::info!("a");
315    /// });
316    ///
317    /// handle_1.assert_finished();
318    /// handle_2.assert_finished();
319    /// ```
320    ///
321    /// In the test output, we see that the subscriber which didn't
322    /// received the event was the one named `subscriber-2`, which is
323    /// correct as the subscriber named `subscriber-1` was the default
324    /// when the event was recorded:
325    ///
326    /// ```text
327    /// [subscriber-2] more notifications expected: [
328    ///     Event(
329    ///         MockEvent,
330    ///     ),
331    /// ]', tracing-mock/src/subscriber.rs:1276:13
332    /// ```
333    pub fn named(self, name: impl ToString) -> Self {
334        Self {
335            name: name.to_string(),
336            ..self
337        }
338    }
339
340    /// Adds an expectation that an event matching the [`ExpectedEvent`]
341    /// will be recorded next.
342    ///
343    /// The `event` can be a default mock which will match any event
344    /// (`expect::event()`) or can include additional expectations.
345    /// See the [`ExpectedEvent`] documentation for more details.
346    ///
347    /// If an event is recorded that doesn't match the `ExpectedEvent`,
348    /// or if something else (such as entering a span) is recorded
349    /// first, then the expectation will fail.
350    ///
351    /// # Examples
352    ///
353    /// ```
354    /// use tracing_mock::{expect, subscriber};
355    ///
356    /// let (subscriber, handle) = subscriber::mock()
357    ///     .event(expect::event())
358    ///     .run_with_handle();
359    ///
360    /// tracing::subscriber::with_default(subscriber, || {
361    ///     tracing::info!("a");
362    /// });
363    ///
364    /// handle.assert_finished();
365    /// ```
366    ///
367    /// A span is entered before the event, causing the test to fail:
368    ///
369    /// ```should_panic
370    /// use tracing_mock::{expect, subscriber};
371    ///
372    /// let (subscriber, handle) = subscriber::mock()
373    ///     .event(expect::event())
374    ///     .run_with_handle();
375    ///
376    /// tracing::subscriber::with_default(subscriber, || {
377    ///     let span = tracing::info_span!("span");
378    ///     let _guard = span.enter();
379    ///     tracing::info!("a");
380    /// });
381    ///
382    /// handle.assert_finished();
383    /// ```
384    pub fn event(mut self, event: ExpectedEvent) -> Self {
385        self.expected.push_back(Expect::Event(event));
386        self
387    }
388
389    /// Adds an expectation that the creation of a span will be
390    /// recorded next.
391    ///
392    /// This function accepts `Into<NewSpan>` instead of
393    /// [`ExpectedSpan`] directly, so it can be used to test
394    /// span fields and the span parent. This is because a
395    /// subscriber only receives the span fields and parent when
396    /// a span is created, not when it is entered.
397    ///
398    /// The new span doesn't need to be entered for this expectation
399    /// to succeed.
400    ///
401    /// If a span is recorded that doesn't match the `ExpectedSpan`,
402    /// or if something else (such as an event) is recorded first,
403    /// then the expectation will fail.
404    ///
405    /// # Examples
406    ///
407    /// ```
408    /// use tracing_mock::{expect, subscriber};
409    ///
410    /// let span = expect::span()
411    ///     .at_level(tracing::Level::INFO)
412    ///     .named("the span we're testing")
413    ///     .with_fields(expect::field("testing").with_value(&"yes"));
414    /// let (subscriber, handle) = subscriber::mock()
415    ///     .new_span(span)
416    ///     .run_with_handle();
417    ///
418    /// tracing::subscriber::with_default(subscriber, || {
419    ///     _ = tracing::info_span!("the span we're testing", testing = "yes");
420    /// });
421    ///
422    /// handle.assert_finished();
423    /// ```
424    ///
425    /// An event is recorded before the span is created, causing the
426    /// test to fail:
427    ///
428    /// ```should_panic
429    /// use tracing_mock::{expect, subscriber};
430    ///
431    /// let span = expect::span()
432    ///     .at_level(tracing::Level::INFO)
433    ///     .named("the span we're testing")
434    ///     .with_fields(expect::field("testing").with_value(&"yes"));
435    /// let (subscriber, handle) = subscriber::mock()
436    ///     .new_span(span)
437    ///     .run_with_handle();
438    ///
439    /// tracing::subscriber::with_default(subscriber, || {
440    ///     tracing::info!("an event");
441    ///     _ = tracing::info_span!("the span we're testing", testing = "yes");
442    /// });
443    ///
444    /// handle.assert_finished();
445    /// ```
446    pub fn new_span<I>(mut self, new_span: I) -> Self
447    where
448        I: Into<NewSpan>,
449    {
450        self.expected.push_back(Expect::NewSpan(new_span.into()));
451        self
452    }
453
454    /// Adds an expectation that entering a span matching the
455    /// [`ExpectedSpan`] will be recorded next.
456    ///
457    /// This expectation is generally accompanied by a call to
458    /// [`exit`] as well. If used together with [`only`], this
459    /// is necessary.
460    ///
461    /// If the span that is entered doesn't match the [`ExpectedSpan`],
462    /// or if something else (such as an event) is recorded first,
463    /// then the expectation will fail.
464    ///
465    /// # Examples
466    ///
467    /// ```
468    /// use tracing_mock::{expect, subscriber};
469    ///
470    /// let span = expect::span()
471    ///     .at_level(tracing::Level::INFO)
472    ///     .named("the span we're testing");
473    /// let (subscriber, handle) = subscriber::mock()
474    ///     .enter(&span)
475    ///     .exit(&span)
476    ///     .only()
477    ///     .run_with_handle();
478    ///
479    /// tracing::subscriber::with_default(subscriber, || {
480    ///     let span = tracing::info_span!("the span we're testing");
481    ///     let _entered = span.enter();
482    /// });
483    ///
484    /// handle.assert_finished();
485    /// ```
486    ///
487    /// An event is recorded before the span is entered, causing the
488    /// test to fail:
489    ///
490    /// ```should_panic
491    /// use tracing_mock::{expect, subscriber};
492    ///
493    /// let span = expect::span()
494    ///     .at_level(tracing::Level::INFO)
495    ///     .named("the span we're testing");
496    /// let (subscriber, handle) = subscriber::mock()
497    ///     .enter(&span)
498    ///     .exit(&span)
499    ///     .only()
500    ///     .run_with_handle();
501    ///
502    /// tracing::subscriber::with_default(subscriber, || {
503    ///     tracing::info!("an event");
504    ///     let span = tracing::info_span!("the span we're testing");
505    ///     let _entered = span.enter();
506    /// });
507    ///
508    /// handle.assert_finished();
509    /// ```
510    ///
511    /// [`exit`]: fn@Self::exit
512    /// [`only`]: fn@Self::only
513    pub fn enter<S>(mut self, span: S) -> Self
514    where
515        S: Into<ExpectedSpan>,
516    {
517        self.expected.push_back(Expect::Enter(span.into()));
518        self
519    }
520
521    /// Adds ab expectation that exiting a span matching the
522    /// [`ExpectedSpan`] will be recorded next.
523    ///
524    /// As a span may be entered and exited multiple times,
525    /// this is different from the span being closed. In
526    /// general [`enter`] and `exit` should be paired.
527    ///
528    /// If the span that is exited doesn't match the [`ExpectedSpan`],
529    /// or if something else (such as an event) is recorded first,
530    /// then the expectation will fail.
531    ///
532    /// # Examples
533    ///
534    /// ```
535    /// use tracing_mock::{expect, subscriber};
536    ///
537    /// let span = expect::span()
538    ///     .at_level(tracing::Level::INFO)
539    ///     .named("the span we're testing");
540    /// let (subscriber, handle) = subscriber::mock()
541    ///     .enter(&span)
542    ///     .exit(&span)
543    ///     .run_with_handle();
544    ///
545    /// tracing::subscriber::with_default(subscriber, || {
546    ///     let span = tracing::info_span!("the span we're testing");
547    ///     let _entered = span.enter();
548    /// });
549    ///
550    /// handle.assert_finished();
551    /// ```
552    ///
553    /// An event is recorded before the span is exited, causing the
554    /// test to fail:
555    ///
556    /// ```should_panic
557    /// use tracing_mock::{expect, subscriber};
558    ///
559    /// let span = expect::span()
560    ///     .at_level(tracing::Level::INFO)
561    ///     .named("the span we're testing");
562    /// let (subscriber, handle) = subscriber::mock()
563    ///     .enter(&span)
564    ///     .exit(&span)
565    ///     .run_with_handle();
566    ///
567    /// tracing::subscriber::with_default(subscriber, || {
568    ///     let span = tracing::info_span!("the span we're testing");
569    ///     let _entered = span.enter();
570    ///     tracing::info!("an event");
571    /// });
572    ///
573    /// handle.assert_finished();
574    /// ```
575    ///
576    /// [`enter`]: fn@Self::enter
577    pub fn exit<S>(mut self, span: S) -> Self
578    where
579        S: Into<ExpectedSpan>,
580    {
581        self.expected.push_back(Expect::Exit(span.into()));
582        self
583    }
584
585    /// Adds an expectation that cloning a span matching the
586    /// [`ExpectedSpan`] will be recorded next.
587    ///
588    /// The cloned span does need to be entered.
589    ///
590    /// If the span that is cloned doesn't match the [`ExpectedSpan`],
591    /// or if something else (such as an event) is recorded first,
592    /// then the expectation will fail.
593    ///
594    /// # Examples
595    ///
596    /// ```
597    /// use tracing_mock::{expect, subscriber};
598    ///
599    /// let span = expect::span()
600    ///     .at_level(tracing::Level::INFO)
601    ///     .named("the span we're testing");
602    /// let (subscriber, handle) = subscriber::mock()
603    ///     .clone_span(span)
604    ///     .run_with_handle();
605    ///
606    /// tracing::subscriber::with_default(subscriber, || {
607    ///     let span = tracing::info_span!("the span we're testing");
608    ///     _ = span.clone();
609    /// });
610    ///
611    /// handle.assert_finished();
612    /// ```
613    ///
614    /// An event is recorded before the span is cloned, causing the
615    /// test to fail:
616    ///
617    /// ```should_panic
618    /// use tracing_mock::{expect, subscriber};
619    ///
620    /// let span = expect::span()
621    ///     .at_level(tracing::Level::INFO)
622    ///     .named("the span we're testing");
623    /// let (subscriber, handle) = subscriber::mock()
624    ///     .clone_span(span)
625    ///     .run_with_handle();
626    ///
627    /// tracing::subscriber::with_default(subscriber, || {
628    ///     let span = tracing::info_span!("the span we're testing");
629    ///     tracing::info!("an event");
630    ///     _ = span.clone();
631    /// });
632    ///
633    /// handle.assert_finished();
634    /// ```
635    pub fn clone_span<S>(mut self, span: S) -> Self
636    where
637        S: Into<ExpectedSpan>,
638    {
639        self.expected.push_back(Expect::CloneSpan(span.into()));
640        self
641    }
642
643    /// **This method is deprecated.**
644    ///
645    /// Adds an expectation that a span matching the [`ExpectedSpan`]
646    /// getting dropped via the deprecated function
647    /// [`Subscriber::drop_span`] will be recorded next.
648    ///
649    /// Instead [`Subscriber::try_close`] should be used on the subscriber
650    /// and should be asserted with `close_span` (which hasn't been
651    /// implemented yet, but will be done as part of #539).
652    ///
653    /// [`Subscriber::drop_span`]: fn@tracing::Subscriber::drop_span
654    #[allow(deprecated)]
655    pub fn drop_span<S>(mut self, span: S) -> Self
656    where
657        S: Into<ExpectedSpan>,
658    {
659        self.expected.push_back(Expect::DropSpan(span.into()));
660        self
661    }
662
663    /// Adds an expectation that a `follows_from` relationship will be
664    /// recorded next. Specifically that a span matching `consequence`
665    /// follows from a span matching `cause`.
666    ///
667    /// For further details on what this causal relationship means, see
668    /// [`Span::follows_from`].
669    ///
670    /// If either of the 2 spans don't match their respective
671    /// [`ExpectedSpan`] or if something else (such as an event) is
672    /// recorded first, then the expectation will fail.
673    ///
674    /// **Note**: The 2 spans, `consequence` and `cause` are matched
675    /// by `name` only.
676    ///
677    /// # Examples
678    ///
679    /// ```
680    /// use tracing_mock::{expect, subscriber};
681    ///
682    /// let cause = expect::span().named("cause");
683    /// let consequence = expect::span().named("consequence");
684    ///
685    /// let (subscriber, handle) = subscriber::mock()
686    ///     .follows_from(consequence, cause)
687    ///     .run_with_handle();
688    ///
689    /// tracing::subscriber::with_default(subscriber, || {
690    ///     let cause = tracing::info_span!("cause");
691    ///     let consequence = tracing::info_span!("consequence");
692    ///
693    ///     consequence.follows_from(&cause);
694    /// });
695    ///
696    /// handle.assert_finished();
697    /// ```
698    ///
699    /// The `cause` span doesn't match, it is actually recorded at
700    /// `Level::WARN` instead of the expected `Level::INFO`, causing
701    /// this test to fail:
702    ///
703    /// ```should_panic
704    /// use tracing_mock::{expect, subscriber};
705    ///
706    /// let cause = expect::span().named("cause");
707    /// let consequence = expect::span().named("consequence");
708    ///
709    /// let (subscriber, handle) = subscriber::mock()
710    ///     .follows_from(consequence, cause)
711    ///     .run_with_handle();
712    ///
713    /// tracing::subscriber::with_default(subscriber, || {
714    ///     let cause = tracing::info_span!("another cause");
715    ///     let consequence = tracing::info_span!("consequence");
716    ///
717    ///     consequence.follows_from(&cause);
718    /// });
719    ///
720    /// handle.assert_finished();
721    /// ```
722    ///
723    /// [`Span::follows_from`]: fn@tracing::Span::follows_from
724    pub fn follows_from<S1, S2>(mut self, consequence: S1, cause: S2) -> Self
725    where
726        S1: Into<ExpectedSpan>,
727        S2: Into<ExpectedSpan>,
728    {
729        self.expected.push_back(Expect::FollowsFrom {
730            consequence: consequence.into(),
731            cause: cause.into(),
732        });
733        self
734    }
735
736    /// Adds an expectation that `fields` are recorded on a span
737    /// matching the [`ExpectedSpan`] will be recorded next.
738    ///
739    /// For further information on how to specify the expected
740    /// fields, see the documentation on the [`field`] module.
741    ///
742    /// If either the span doesn't match the [`ExpectedSpan`], the
743    /// fields don't match the expected fields, or if something else
744    /// (such as an event) is recorded first, then the expectation
745    /// will fail.
746    ///
747    /// # Examples
748    ///
749    /// ```
750    /// use tracing_mock::{expect, subscriber};
751    ///
752    /// let span = expect::span()
753    ///     .named("my_span");
754    /// let (subscriber, handle) = subscriber::mock()
755    ///     .record(span, expect::field("parting").with_value(&"goodbye world!"))
756    ///     .run_with_handle();
757    ///
758    /// tracing::subscriber::with_default(subscriber, || {
759    ///     let span = tracing::trace_span!(
760    ///         "my_span",
761    ///         greeting = "hello world",
762    ///         parting = tracing::field::Empty
763    ///     );
764    ///     span.record("parting", "goodbye world!");
765    /// });
766    ///
767    /// handle.assert_finished();
768    /// ```
769    ///
770    /// The value of the recorded field doesn't match the expectation,
771    /// causing the test to fail:
772    ///
773    /// ```should_panic
774    /// use tracing_mock::{expect, subscriber};
775    ///
776    /// let span = expect::span()
777    ///     .named("my_span");
778    /// let (subscriber, handle) = subscriber::mock()
779    ///     .record(span, expect::field("parting").with_value(&"goodbye world!"))
780    ///     .run_with_handle();
781    ///
782    /// tracing::subscriber::with_default(subscriber, || {
783    ///     let span = tracing::trace_span!(
784    ///         "my_span",
785    ///         greeting = "hello world",
786    ///         parting = tracing::field::Empty
787    ///     );
788    ///     span.record("parting", "goodbye universe!");
789    /// });
790    ///
791    /// handle.assert_finished();
792    /// ```
793    ///
794    /// [`field`]: mod@crate::field
795    pub fn record<S, I>(mut self, span: S, fields: I) -> Self
796    where
797        S: Into<ExpectedSpan>,
798        I: Into<ExpectedFields>,
799    {
800        self.expected
801            .push_back(Expect::Visit(span.into(), fields.into()));
802        self
803    }
804
805    /// Adds an expectation that [`Subscriber::on_register_dispatch`] will
806    /// be called next.
807    ///
808    /// **Note**: This expectation is usually fulfilled automatically when
809    /// a subscriber is set as the default via [`tracing::subscriber::with_default`]
810    /// or [`tracing::subscriber::set_global_default`], so explicitly expecting
811    /// this is not usually necessary. However, it may be useful when testing
812    /// custom subscriber implementations that manually call `on_register_dispatch`.
813    ///
814    /// # Examples
815    ///
816    /// ```
817    /// use tracing_mock::{expect, subscriber};
818    ///
819    /// let (subscriber, handle) = subscriber::mock()
820    ///     .on_register_dispatch()
821    ///     .run_with_handle();
822    ///
823    /// tracing::subscriber::with_default(subscriber, || {
824    ///     // The subscriber's on_register_dispatch was called when it was set as default
825    /// });
826    ///
827    /// handle.assert_finished();
828    /// ```
829    ///
830    /// [`Subscriber::on_register_dispatch`]: tracing::Subscriber::on_register_dispatch
831    pub fn on_register_dispatch(mut self) -> Self {
832        self.expected.push_back(Expect::OnRegisterDispatch);
833        self
834    }
835
836    /// Filter the traces evaluated by the `MockSubscriber`.
837    ///
838    /// The filter will be applied to all traces received before
839    /// any validation occurs - so its position in the call chain
840    /// is not important. The filter does not perform any validation
841    /// itself.
842    ///
843    /// # Examples
844    ///
845    /// ```
846    /// use tracing_mock::{expect, subscriber};
847    ///
848    /// let (subscriber, handle) = subscriber::mock()
849    ///     .with_filter(|meta| meta.level() <= &tracing::Level::WARN)
850    ///     .event(expect::event())
851    ///     .only()
852    ///     .run_with_handle();
853    ///
854    /// tracing::subscriber::with_default(subscriber, || {
855    ///     tracing::info!("a");
856    ///     tracing::warn!("b");
857    /// });
858    ///
859    /// handle.assert_finished();
860    /// ```
861    pub fn with_filter<G>(self, filter: G) -> MockSubscriber<G>
862    where
863        G: Fn(&Metadata<'_>) -> bool + 'static,
864    {
865        MockSubscriber {
866            expected: self.expected,
867            filter,
868            max_level: self.max_level,
869            name: self.name,
870        }
871    }
872
873    /// Sets the max level that will be provided to the `tracing`
874    /// system.
875    ///
876    /// This method can be used to test the internals of `tracing`,
877    /// but it is also useful to filter out traces on more verbose
878    /// levels if you only want to verify above a certain level.
879    ///
880    /// **Note**: this value determines a global filter, if
881    /// `with_max_level_hint` is called on multiple subscribers, the
882    /// global filter will be the least restrictive of all subscribers.
883    /// To filter the events evaluated by a specific `MockSubscriber`,
884    /// use [`with_filter`] instead.
885    ///
886    /// # Examples
887    ///
888    /// ```
889    /// use tracing_mock::{expect, subscriber};
890    ///
891    /// let (subscriber, handle) = subscriber::mock()
892    ///     .with_max_level_hint(tracing::Level::INFO)
893    ///     .event(expect::event().at_level(tracing::Level::INFO))
894    ///     .only()
895    ///     .run_with_handle();
896    ///
897    /// tracing::subscriber::with_default(subscriber, || {
898    ///     tracing::debug!("a message we don't care about");
899    ///     tracing::info!("a message we want to validate");
900    /// });
901    ///
902    /// handle.assert_finished();
903    /// ```
904    ///
905    /// [`with_filter`]: fn@Self::with_filter
906    pub fn with_max_level_hint(self, hint: impl Into<LevelFilter>) -> Self {
907        Self {
908            max_level: Some(hint.into()),
909            ..self
910        }
911    }
912
913    /// Expects that no further traces are received.
914    ///
915    /// The call to `only` should appear immediately before the final
916    /// call to `run` or `run_with_handle`, as any expectations which
917    /// are added after `only` will not be considered.
918    ///
919    /// # Examples
920    ///
921    /// Consider this simple test. It passes even though we only
922    /// expect a single event, but receive three:
923    ///
924    /// ```
925    /// use tracing_mock::{expect, subscriber};
926    ///
927    /// let (subscriber, handle) = subscriber::mock()
928    ///     .event(expect::event())
929    ///     .run_with_handle();
930    ///
931    /// tracing::subscriber::with_default(subscriber, || {
932    ///     tracing::info!("a");
933    ///     tracing::info!("b");
934    ///     tracing::info!("c");
935    /// });
936    ///
937    /// handle.assert_finished();
938    /// ```
939    ///
940    /// After including `only`, the test will fail:
941    ///
942    /// ```should_panic
943    /// use tracing_mock::{expect, subscriber};
944    ///
945    /// let (subscriber, handle) = subscriber::mock()
946    ///     .event(expect::event())
947    ///     .only()
948    ///     .run_with_handle();
949    ///
950    /// tracing::subscriber::with_default(subscriber, || {
951    ///     tracing::info!("a");
952    ///     tracing::info!("b");
953    ///     tracing::info!("c");
954    /// });
955    ///
956    /// handle.assert_finished();
957    /// ```
958    pub fn only(mut self) -> Self {
959        self.expected.push_back(Expect::Nothing);
960        self
961    }
962
963    /// Consume the receiver and return an `impl` [`Subscriber`] which can
964    /// be set as the default subscriber.
965    ///
966    /// This function is similar to [`run_with_handle`], but it doesn't
967    /// return a [`MockHandle`]. This is useful if the desired
968    /// assertions can be checked externally to the subscriber.
969    ///
970    /// # Examples
971    ///
972    /// The following test is used within the `tracing`
973    /// codebase:
974    ///
975    /// ```
976    /// use tracing_mock::subscriber;
977    ///
978    /// tracing::subscriber::with_default(subscriber::mock().run(), || {
979    ///     let foo1 = tracing::span!(tracing::Level::TRACE, "foo");
980    ///     let foo2 = foo1.clone();
981    ///     // Two handles that point to the same span are equal.
982    ///     assert_eq!(foo1, foo2);
983    /// });
984    /// ```
985    ///
986    /// [`Subscriber`]: tracing::Subscriber
987    /// [`run_with_handle`]: fn@Self::run_with_handle
988    pub fn run(self) -> impl Subscriber {
989        let (subscriber, _) = self.run_with_handle();
990        subscriber
991    }
992
993    /// Consume the receiver and return an `impl` [`Subscriber`] which can
994    /// be set as the default subscriber and a [`MockHandle`] which can
995    /// be used to validate the provided expectations.
996    ///
997    /// # Examples
998    ///
999    /// ```
1000    /// use tracing_mock::{expect, subscriber};
1001    ///
1002    /// // subscriber and handle are returned from `run_with_handle()`
1003    /// let (subscriber, handle) = subscriber::mock()
1004    ///     .event(expect::event())
1005    ///     .run_with_handle();
1006    ///
1007    /// tracing::subscriber::with_default(subscriber, || {
1008    ///     tracing::info!("a");
1009    /// });
1010    ///
1011    /// handle.assert_finished();
1012    /// ```
1013    ///
1014    /// [`Subscriber`]: tracing::Subscriber
1015    pub fn run_with_handle(self) -> (impl Subscriber, MockHandle) {
1016        let expected = Arc::new(Mutex::new(self.expected));
1017        let handle = MockHandle(expected.clone(), self.name.clone());
1018        let subscriber = Running {
1019            spans: Mutex::new(HashMap::new()),
1020            expected,
1021            current: Mutex::new(Vec::new()),
1022            ids: AtomicUsize::new(1),
1023            filter: self.filter,
1024            max_level: self.max_level,
1025            name: self.name,
1026        };
1027        (subscriber, handle)
1028    }
1029}
1030
1031impl<F> Subscriber for Running<F>
1032where
1033    F: Fn(&Metadata<'_>) -> bool + 'static,
1034{
1035    fn on_register_dispatch(&self, _subscriber: &tracing::Dispatch) {
1036        println!("[{}] on_register_dispatch", self.name);
1037        let mut expected = self.expected.lock().unwrap();
1038        if let Some(Expect::OnRegisterDispatch) = expected.front() {
1039            expected.pop_front();
1040        }
1041    }
1042
1043    fn enabled(&self, meta: &Metadata<'_>) -> bool {
1044        println!("[{}] enabled: {:#?}", self.name, meta);
1045        let enabled = (self.filter)(meta);
1046        println!("[{}] enabled -> {}", self.name, enabled);
1047        enabled
1048    }
1049
1050    fn register_callsite(&self, meta: &'static Metadata<'static>) -> Interest {
1051        println!("[{}] register_callsite: {:#?}", self.name, meta);
1052        if self.enabled(meta) {
1053            Interest::always()
1054        } else {
1055            Interest::never()
1056        }
1057    }
1058    fn max_level_hint(&self) -> Option<LevelFilter> {
1059        self.max_level
1060    }
1061
1062    fn record(&self, id: &Id, values: &span::Record<'_>) {
1063        let spans = self.spans.lock().unwrap();
1064        let mut expected = self.expected.lock().unwrap();
1065        let span = spans
1066            .get(id)
1067            .unwrap_or_else(|| panic!("[{}] no span for ID {:?}", self.name, id));
1068        println!(
1069            "[{}] record: {}; id={:?}; values={:?};",
1070            self.name, span.name, id, values
1071        );
1072        let was_expected = matches!(expected.front(), Some(Expect::Visit(_, _)));
1073        if was_expected {
1074            if let Expect::Visit(expected_span, mut expected_values) = expected.pop_front().unwrap()
1075            {
1076                if let Some(name) = expected_span.name() {
1077                    assert_eq!(name, span.name);
1078                }
1079                let context = format!("span {}: ", span.name);
1080                let mut checker = expected_values.checker(&context, &self.name);
1081                values.record(&mut checker);
1082                checker.finish();
1083            }
1084        }
1085    }
1086
1087    fn event(&self, event: &Event<'_>) {
1088        let name = event.metadata().name();
1089        println!("[{}] event: {};", self.name, name);
1090        match self.expected.lock().unwrap().pop_front() {
1091            None => {}
1092            Some(Expect::Event(mut expected)) => {
1093                #[cfg(feature = "tracing-subscriber")]
1094                {
1095                    if expected.scope_mut().is_some() {
1096                        unimplemented!(
1097                            "Expected scope for events is not supported with `MockSubscriber`."
1098                        )
1099                    }
1100                }
1101                let event_get_ancestry = || {
1102                    get_ancestry(
1103                        event,
1104                        || self.lookup_current(),
1105                        |span_id| {
1106                            self.spans
1107                                .lock()
1108                                .unwrap()
1109                                .get(span_id)
1110                                .map(|span| span.into())
1111                        },
1112                    )
1113                };
1114                expected.check(event, event_get_ancestry, &self.name);
1115            }
1116            Some(ex) => ex.bad(&self.name, format_args!("observed event {:#?}", event)),
1117        }
1118    }
1119
1120    fn record_follows_from(&self, consequence_id: &Id, cause_id: &Id) {
1121        let spans = self.spans.lock().unwrap();
1122        if let Some(consequence_span) = spans.get(consequence_id) {
1123            if let Some(cause_span) = spans.get(cause_id) {
1124                println!(
1125                    "[{}] record_follows_from: {} (id={:?}) follows {} (id={:?})",
1126                    self.name, consequence_span.name, consequence_id, cause_span.name, cause_id,
1127                );
1128                match self.expected.lock().unwrap().pop_front() {
1129                    None => {}
1130                    Some(Expect::FollowsFrom {
1131                        consequence: ref expected_consequence,
1132                        cause: ref expected_cause,
1133                    }) => {
1134                        if let Some(name) = expected_consequence.name() {
1135                            // TODO(hds): Write proper assertion text.
1136                            assert_eq!(name, consequence_span.name);
1137                        }
1138                        if let Some(name) = expected_cause.name() {
1139                            // TODO(hds): Write proper assertion text.
1140                            assert_eq!(name, cause_span.name);
1141                        }
1142                    }
1143                    Some(ex) => ex.bad(
1144                        &self.name,
1145                        format_args!(
1146                            "consequence {:?} followed cause {:?}",
1147                            consequence_span.name, cause_span.name
1148                        ),
1149                    ),
1150                }
1151            }
1152        };
1153    }
1154
1155    fn new_span(&self, span: &Attributes<'_>) -> Id {
1156        let meta = span.metadata();
1157        let id = self.ids.fetch_add(1, Ordering::SeqCst);
1158        let id = Id::from_u64(id as u64);
1159        println!(
1160            "[{}] new_span: name={:?}; target={:?}; id={:?};",
1161            self.name,
1162            meta.name(),
1163            meta.target(),
1164            id
1165        );
1166        let mut expected = self.expected.lock().unwrap();
1167        let was_expected = matches!(expected.front(), Some(Expect::NewSpan(_)));
1168        let mut spans = self.spans.lock().unwrap();
1169        if was_expected {
1170            if let Expect::NewSpan(mut expected) = expected.pop_front().unwrap() {
1171                if let Some(expected_id) = &expected.span.id {
1172                    expected_id.set(id.into_u64()).unwrap();
1173                }
1174
1175                expected.check(
1176                    span,
1177                    || {
1178                        get_ancestry(
1179                            span,
1180                            || self.lookup_current(),
1181                            |span_id| spans.get(span_id).map(|span| span.into()),
1182                        )
1183                    },
1184                    &self.name,
1185                );
1186            }
1187        }
1188        spans.insert(
1189            id.clone(),
1190            SpanState {
1191                id: id.clone(),
1192                name: meta.name(),
1193                refs: 1,
1194                meta,
1195            },
1196        );
1197        id
1198    }
1199
1200    fn enter(&self, id: &Id) {
1201        let spans = self.spans.lock().unwrap();
1202        if let Some(span) = spans.get(id) {
1203            println!("[{}] enter: {}; id={:?};", self.name, span.name, id);
1204            match self.expected.lock().unwrap().pop_front() {
1205                None => {}
1206                Some(Expect::Enter(ref expected_span)) => {
1207                    expected_span.check(&span.into(), "to enter a span", &self.name);
1208                }
1209                Some(ex) => ex.bad(&self.name, format_args!("entered span {:?}", span.name)),
1210            }
1211        };
1212        self.current.lock().unwrap().push(id.clone());
1213    }
1214
1215    fn exit(&self, id: &Id) {
1216        if std::thread::panicking() {
1217            // `exit()` can be called in `drop` impls, so we must guard against
1218            // double panics.
1219            println!("[{}] exit {:?} while panicking", self.name, id);
1220            return;
1221        }
1222        let spans = self.spans.lock().unwrap();
1223        let span = spans
1224            .get(id)
1225            .unwrap_or_else(|| panic!("[{}] no span for ID {:?}", self.name, id));
1226        println!("[{}] exit: {}; id={:?};", self.name, span.name, id);
1227        match self.expected.lock().unwrap().pop_front() {
1228            None => {}
1229            Some(Expect::Exit(ref expected_span)) => {
1230                expected_span.check(&span.into(), "to exit a span", &self.name);
1231                let curr = self.current.lock().unwrap().pop();
1232                assert_eq!(
1233                    Some(id),
1234                    curr.as_ref(),
1235                    "[{}] exited span {:?}, but the current span was {:?}",
1236                    self.name,
1237                    span.name,
1238                    curr.as_ref().and_then(|id| spans.get(id)).map(|s| s.name)
1239                );
1240            }
1241            Some(ex) => ex.bad(&self.name, format_args!("exited span {:?}", span.name)),
1242        };
1243    }
1244
1245    fn clone_span(&self, id: &Id) -> Id {
1246        let mut spans = self.spans.lock().unwrap();
1247        let mut span = spans.get_mut(id);
1248        match span.as_deref_mut() {
1249            Some(span) => {
1250                println!(
1251                    "[{}] clone_span: {}; id={:?}; refs={:?};",
1252                    self.name, span.name, id, span.refs,
1253                );
1254                span.refs += 1;
1255            }
1256            None => {
1257                println!(
1258                    "[{}] clone_span: id={:?} (not found in span list);",
1259                    self.name, id
1260                );
1261            }
1262        }
1263
1264        let mut expected = self.expected.lock().unwrap();
1265        let was_expected = if let Some(Expect::CloneSpan(ref expected_span)) = expected.front() {
1266            match span {
1267                Some(actual_span) => {
1268                    let actual_span: &_ = actual_span;
1269                    expected_span.check(&actual_span.into(), "to clone a span", &self.name);
1270                }
1271                // Check only by Id
1272                None => expected_span.check(&id.into(), "to clone a span", &self.name),
1273            }
1274            true
1275        } else {
1276            false
1277        };
1278        if was_expected {
1279            expected.pop_front();
1280        }
1281        id.clone()
1282    }
1283
1284    fn drop_span(&self, id: Id) {
1285        let mut is_event = false;
1286        let name = if let Ok(mut spans) = self.spans.try_lock() {
1287            spans.get_mut(&id).map(|span| {
1288                let name = span.name;
1289                if name.contains("event") {
1290                    is_event = true;
1291                }
1292                println!(
1293                    "[{}] drop_span: {}; id={:?}; refs={:?};",
1294                    self.name, name, id, span.refs
1295                );
1296                span.refs -= 1;
1297                name
1298            })
1299        } else {
1300            None
1301        };
1302        if name.is_none() {
1303            println!("[{}] drop_span: id={:?}", self.name, id);
1304        }
1305        if let Ok(mut expected) = self.expected.try_lock() {
1306            let was_expected = match expected.front() {
1307                Some(Expect::DropSpan(ref span)) => {
1308                    // Don't assert if this function was called while panicking,
1309                    // as failing the assertion can cause a double panic.
1310                    if !::std::thread::panicking() {
1311                        assert_eq!(name, span.name());
1312                    }
1313                    true
1314                }
1315                Some(Expect::Event(_)) => {
1316                    if !::std::thread::panicking() {
1317                        assert!(is_event, "[{}] expected an event", self.name);
1318                    }
1319                    true
1320                }
1321                _ => false,
1322            };
1323            if was_expected {
1324                expected.pop_front();
1325            }
1326        }
1327    }
1328
1329    fn current_span(&self) -> tracing_core::span::Current {
1330        let stack = self.current.lock().unwrap();
1331        match stack.last() {
1332            Some(id) => {
1333                let spans = self.spans.lock().unwrap();
1334                let state = spans.get(id).expect("state for current span");
1335                tracing_core::span::Current::new(id.clone(), state.meta)
1336            }
1337            None => tracing_core::span::Current::none(),
1338        }
1339    }
1340}
1341
1342impl<F> Running<F>
1343where
1344    F: Fn(&Metadata<'_>) -> bool,
1345{
1346    fn lookup_current(&self) -> Option<span::Id> {
1347        let stack = self.current.lock().unwrap();
1348        stack.last().cloned()
1349    }
1350}
1351
1352impl MockHandle {
1353    #[cfg(feature = "tracing-subscriber")]
1354    pub(crate) fn new(expected: Arc<Mutex<VecDeque<Expect>>>, name: String) -> Self {
1355        Self(expected, name)
1356    }
1357
1358    /// Checks the expectations which were set on the
1359    /// [`MockSubscriber`].
1360    ///
1361    /// Calling `assert_finished` is usually the final part of a test.
1362    ///
1363    /// # Panics
1364    ///
1365    /// This method will panic if any of the provided expectations are
1366    /// not met.
1367    ///
1368    /// # Examples
1369    ///
1370    /// ```
1371    /// use tracing_mock::{expect, subscriber};
1372    ///
1373    /// let (subscriber, handle) = subscriber::mock()
1374    ///     .event(expect::event())
1375    ///     .run_with_handle();
1376    ///
1377    /// tracing::subscriber::with_default(subscriber, || {
1378    ///     tracing::info!("a");
1379    /// });
1380    ///
1381    /// // Check assertions set on the mock subscriber
1382    /// handle.assert_finished();
1383    /// ```
1384    pub fn assert_finished(&self) {
1385        if let Ok(ref expected) = self.0.lock() {
1386            assert!(
1387                !expected.iter().any(|thing| thing != &Expect::Nothing),
1388                "\n[{}] more notifications expected: {:#?}",
1389                self.1,
1390                **expected
1391            );
1392        }
1393    }
1394}