Skip to content

Commit 53c0a5e

Browse files
committed
mock: correct contextual/explicit parent assertions
When recording the parent of an event or span, the `MockCollector` treats an explicit parent of `None` (i.e. an event or span that is an explicit root) in the same way as if there is no explicit root. This leads to it picking up the contextual parent or treating the event or span as a contextual root. This change refactors the recording of the parent to use `is_contextual` to distinguish whether or not an explicit parent has been specified. The actual parent is also written into an `Ancestry` enum so that the expected and actual values can be compared in a more explicit way. Additionally, the `Ancestry` struct has been moved into its own module and the check behavior has been fixed. The error message has also been unified across all cases. Another problem with the previous API is that the two methods `with_contextual_parent` and `with_explicit_parent` are actually mutually exclusive, a span or event cannot be both of them. It is also a (small) mental leap for the user to go from `with_*_parent(None)` to understanding that this means that a span or event is a root (either contextual or explicit). As such, the API has been reworked into a single method `with_ancestry`, which takes an enum with the following four variants: * `HasExplicitParent(String)` (parent span name) * `IsExplicitRoot` * `HasContextualParent(String)` (parent span name) * `IsContextualRoot` To make the interface as useable as possible, helper functions have been defined in the `expect` module which can be used to create the enum variants. Specifically, these take `Into<String>` parameter for the span name. Given the number of different cases involved in checking ancestry, separate integration tests have been added to `tracing-mock` specifically for testing all the positive and negative cases when asserting on the ancestry of events and spans. There were two tests in `tracing-attributes` which specified both an explicit and a contextual parent. This behavior was never intended to work as all events and spans are either contextual or not. The tests have been corrected to only expect one of the two. Fixes: #2440
1 parent 382ee01 commit 53c0a5e

File tree

14 files changed

+1106
-378
lines changed

14 files changed

+1106
-378
lines changed

Diff for: tracing-attributes/tests/parents.rs

+6-19
Original file line numberDiff line numberDiff line change
@@ -21,23 +21,16 @@ fn default_parent_test() {
2121
.new_span(
2222
contextual_parent
2323
.clone()
24-
.with_contextual_parent(None)
25-
.with_explicit_parent(None),
26-
)
27-
.new_span(
28-
child
29-
.clone()
30-
.with_contextual_parent(Some("contextual_parent"))
31-
.with_explicit_parent(None),
24+
.with_ancestry(expect::is_contextual_root()),
3225
)
26+
.new_span(child.clone().with_ancestry(expect::is_contextual_root()))
3327
.enter(child.clone())
3428
.exit(child.clone())
3529
.enter(contextual_parent.clone())
3630
.new_span(
3731
child
3832
.clone()
39-
.with_contextual_parent(Some("contextual_parent"))
40-
.with_explicit_parent(None),
33+
.with_ancestry(expect::has_contextual_parent("contextual_parent")),
4134
)
4235
.enter(child.clone())
4336
.exit(child)
@@ -68,20 +61,14 @@ fn explicit_parent_test() {
6861
.new_span(
6962
contextual_parent
7063
.clone()
71-
.with_contextual_parent(None)
72-
.with_explicit_parent(None),
73-
)
74-
.new_span(
75-
explicit_parent
76-
.with_contextual_parent(None)
77-
.with_explicit_parent(None),
64+
.with_ancestry(expect::is_contextual_root()),
7865
)
66+
.new_span(explicit_parent.with_ancestry(expect::is_contextual_root()))
7967
.enter(contextual_parent.clone())
8068
.new_span(
8169
child
8270
.clone()
83-
.with_contextual_parent(Some("contextual_parent"))
84-
.with_explicit_parent(Some("explicit_parent")),
71+
.with_ancestry(expect::has_explicit_parent("explicit_parent")),
8572
)
8673
.enter(child.clone())
8774
.exit(child)

Diff for: tracing-futures/tests/std_future.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ fn span_on_drop() {
7171
.enter(expect::span().named("foo"))
7272
.event(
7373
expect::event()
74-
.with_contextual_parent(Some("foo"))
74+
.with_ancestry(expect::has_contextual_parent("foo"))
7575
.at_level(Level::INFO),
7676
)
7777
.exit(expect::span().named("foo"))
@@ -81,7 +81,7 @@ fn span_on_drop() {
8181
.enter(expect::span().named("bar"))
8282
.event(
8383
expect::event()
84-
.with_contextual_parent(Some("bar"))
84+
.with_ancestry(expect::has_contextual_parent("bar"))
8585
.at_level(Level::INFO),
8686
)
8787
.exit(expect::span().named("bar"))

Diff for: tracing-mock/src/ancestry.rs

+145
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
//! Define the ancestry of an event or span.
2+
//!
3+
//! See the documentation on the [`Ancestry`] enum for further details.
4+
5+
use tracing_core::{
6+
span::{self, Attributes},
7+
Event,
8+
};
9+
10+
/// The ancestry of an event or span.
11+
///
12+
/// An event or span can have an explicitly assigned parent, or be an explicit root. Otherwise,
13+
/// an event or span may have a contextually assigned parent or in the final case will be a
14+
/// contextual root.
15+
#[derive(Debug, Eq, PartialEq)]
16+
pub enum Ancestry {
17+
/// The event or span has an explicitly assigned parent (created with `parent: span_id`) with
18+
/// the specified name.
19+
HasExplicitParent(String),
20+
/// The event or span is an explicitly defined root. It was created with `parent: None` and
21+
/// has no parent.
22+
IsExplicitRoot,
23+
/// The event or span has a contextually assigned parent with the specified name. Additionally,
24+
/// it has no explicitly assigned parent.
25+
HasContextualParent(String),
26+
/// The event or span is a contextual root. It has no contextual parent and also has no
27+
/// explicitly assigned parent.
28+
IsContextualRoot,
29+
}
30+
31+
impl Ancestry {
32+
#[track_caller]
33+
pub(crate) fn check(
34+
&self,
35+
actual_ancestry: &Ancestry,
36+
ctx: impl std::fmt::Display,
37+
collector_name: &str,
38+
) {
39+
let expected_description = |ancestry: &Ancestry| match ancestry {
40+
Self::IsExplicitRoot => "be an explicit root".to_string(),
41+
Self::HasExplicitParent(name) => format!("have an explicit parent with name='{name}'"),
42+
Self::IsContextualRoot => "be a contextual root".to_string(),
43+
Self::HasContextualParent(name) => {
44+
format!("have a contextual parent with name='{name}'")
45+
}
46+
};
47+
48+
let actual_description = |ancestry: &Ancestry| match ancestry {
49+
Self::IsExplicitRoot => "was actually an explicit root".to_string(),
50+
Self::HasExplicitParent(name) => {
51+
format!("actually has an explicit parent with name='{name}'")
52+
}
53+
Self::IsContextualRoot => "was actually a contextual root".to_string(),
54+
Self::HasContextualParent(name) => {
55+
format!("actually has a contextual parent with name='{name}'")
56+
}
57+
};
58+
59+
assert_eq!(
60+
self,
61+
actual_ancestry,
62+
"[{collector_name}] expected {ctx} to {expected_description}, but {actual_description}",
63+
expected_description = expected_description(self),
64+
actual_description = actual_description(actual_ancestry)
65+
);
66+
}
67+
}
68+
69+
pub(crate) trait HasAncestry {
70+
fn is_contextual(&self) -> bool;
71+
72+
fn is_root(&self) -> bool;
73+
74+
fn parent(&self) -> Option<&span::Id>;
75+
}
76+
77+
impl HasAncestry for &Event<'_> {
78+
fn is_contextual(&self) -> bool {
79+
(self as &Event<'_>).is_contextual()
80+
}
81+
82+
fn is_root(&self) -> bool {
83+
(self as &Event<'_>).is_root()
84+
}
85+
86+
fn parent(&self) -> Option<&span::Id> {
87+
(self as &Event<'_>).parent()
88+
}
89+
}
90+
91+
impl HasAncestry for &Attributes<'_> {
92+
fn is_contextual(&self) -> bool {
93+
(self as &Attributes<'_>).is_contextual()
94+
}
95+
96+
fn is_root(&self) -> bool {
97+
(self as &Attributes<'_>).is_root()
98+
}
99+
100+
fn parent(&self) -> Option<&span::Id> {
101+
(self as &Attributes<'_>).parent()
102+
}
103+
}
104+
105+
/// Determines the ancestry of an actual span or event.
106+
///
107+
/// The rules for determining the ancestry are as follows:
108+
///
109+
/// +------------+--------------+-----------------+---------------------+
110+
/// | Contextual | Current Span | Explicit Parent | Ancestry |
111+
/// +------------+--------------+-----------------+---------------------+
112+
/// | Yes | Yes | - | HasContextualParent |
113+
/// | Yes | No | - | IsContextualRoot |
114+
/// | No | - | Yes | HasExplicitParent |
115+
/// | No | - | No | IsExplicitRoot |
116+
/// +------------+--------------+-----------------+---------------------+
117+
pub(crate) fn get_ancestry(
118+
item: impl HasAncestry,
119+
lookup_current: impl FnOnce() -> Option<span::Id>,
120+
span_name: impl FnOnce(&span::Id) -> Option<&str>,
121+
) -> Ancestry {
122+
if item.is_contextual() {
123+
if let Some(parent_id) = lookup_current() {
124+
let contextual_parent_name = span_name(&parent_id).expect(
125+
"tracing-mock: contextual parent cannot \
126+
be looked up by ID. Was it recorded correctly?",
127+
);
128+
Ancestry::HasContextualParent(contextual_parent_name.to_string())
129+
} else {
130+
Ancestry::IsContextualRoot
131+
}
132+
} else if item.is_root() {
133+
Ancestry::IsExplicitRoot
134+
} else {
135+
let parent_id = item.parent().expect(
136+
"tracing-mock: is_contextual=false is_root=false \
137+
but no explicit parent found. This is a bug!",
138+
);
139+
let explicit_parent_name = span_name(parent_id).expect(
140+
"tracing-mock: explicit parent cannot be looked \
141+
up by ID. Is the provided Span ID valid: {parent_id}",
142+
);
143+
Ancestry::HasExplicitParent(explicit_parent_name.to_string())
144+
}
145+
}

Diff for: tracing-mock/src/collector.rs

+35-17
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
//! [`Collect`]: trait@tracing::Collect
139139
//! [`MockCollector`]: struct@crate::collector::MockCollector
140140
use crate::{
141+
ancestry::get_ancestry,
141142
event::ExpectedEvent,
142143
expect::Expect,
143144
field::ExpectedFields,
@@ -1034,16 +1035,20 @@ where
10341035
)
10351036
}
10361037
}
1037-
let get_parent_name = || {
1038-
let stack = self.current.lock().unwrap();
1039-
let spans = self.spans.lock().unwrap();
1040-
event
1041-
.parent()
1042-
.and_then(|id| spans.get(id))
1043-
.or_else(|| stack.last().and_then(|id| spans.get(id)))
1044-
.map(|s| s.name.to_string())
1038+
let event_get_ancestry = || {
1039+
get_ancestry(
1040+
event,
1041+
|| self.lookup_current(),
1042+
|span_id| {
1043+
self.spans
1044+
.lock()
1045+
.unwrap()
1046+
.get(span_id)
1047+
.map(|span| span.name)
1048+
},
1049+
)
10451050
};
1046-
expected.check(event, get_parent_name, &self.name);
1051+
expected.check(event, event_get_ancestry, &self.name);
10471052
}
10481053
Some(ex) => ex.bad(&self.name, format_args!("observed event {:#?}", event)),
10491054
}
@@ -1100,14 +1105,17 @@ where
11001105
let mut spans = self.spans.lock().unwrap();
11011106
if was_expected {
11021107
if let Expect::NewSpan(mut expected) = expected.pop_front().unwrap() {
1103-
let get_parent_name = || {
1104-
let stack = self.current.lock().unwrap();
1105-
span.parent()
1106-
.and_then(|id| spans.get(id))
1107-
.or_else(|| stack.last().and_then(|id| spans.get(id)))
1108-
.map(|s| s.name.to_string())
1109-
};
1110-
expected.check(span, get_parent_name, &self.name);
1108+
expected.check(
1109+
span,
1110+
|| {
1111+
get_ancestry(
1112+
span,
1113+
|| self.lookup_current(),
1114+
|span_id| spans.get(span_id).map(|span| span.name),
1115+
)
1116+
},
1117+
&self.name,
1118+
);
11111119
}
11121120
}
11131121
spans.insert(
@@ -1256,6 +1264,16 @@ where
12561264
}
12571265
}
12581266

1267+
impl<F> Running<F>
1268+
where
1269+
F: Fn(&Metadata<'_>) -> bool,
1270+
{
1271+
fn lookup_current(&self) -> Option<span::Id> {
1272+
let stack = self.current.lock().unwrap();
1273+
stack.last().cloned()
1274+
}
1275+
}
1276+
12591277
impl MockHandle {
12601278
#[cfg(feature = "tracing-subscriber")]
12611279
pub(crate) fn new(expected: Arc<Mutex<VecDeque<Expect>>>, name: String) -> Self {

0 commit comments

Comments
 (0)