Debian Codegraph @

third_party/rust/tracing-attributes/tests/async_fn.rs

raw
1 use tracing_mock::*;
2
3 use std::convert::Infallible;
4 use std::{future::Future, pin::Pin, sync::Arc};
5 use tracing::subscriber::with_default;
6 use tracing_attributes::instrument;
7
8 #[instrument]
9 async fn test_async_fn(polls: usize) -> Result<(), ()> {
10 let future = PollN::new_ok(polls);
11 tracing::trace!(awaiting = true);
12 future.await
13 }
14
15 // Reproduces a compile error when returning an `impl Trait` from an
16 // instrumented async fn (see https://github.com/tokio-rs/tracing/issues/1615)
17 #[allow(dead_code)] // this is just here to test whether it compiles.
18 #[instrument]
19 async fn test_ret_impl_trait(n: i32) -> Result<impl Iterator<Item = i32>, ()> {
20 let n = n;
21 Ok((0..10).filter(move |x| *x < n))
22 }
23
24 // Reproduces a compile error when returning an `impl Trait` from an
25 // instrumented async fn (see https://github.com/tokio-rs/tracing/issues/1615)
26 #[allow(dead_code)] // this is just here to test whether it compiles.
27 #[instrument(err)]
28 async fn test_ret_impl_trait_err(n: i32) -> Result<impl Iterator<Item = i32>, &'static str> {
29 Ok((0..10).filter(move |x| *x < n))
30 }
31
32 #[instrument]
33 async fn test_async_fn_empty() {}
34
35 // Reproduces a compile error when an instrumented function body contains inner
36 // attributes (https://github.com/tokio-rs/tracing/issues/2294).
37 #[deny(unused_variables)]
38 #[instrument]
39 async fn repro_async_2294() {
40 #![allow(unused_variables)]
41 let i = 42;
42 }
43
44 // Reproduces https://github.com/tokio-rs/tracing/issues/1613
45 #[instrument]
46 // LOAD-BEARING `#[rustfmt::skip]`! This is necessary to reproduce the bug;
47 // with the rustfmt-generated formatting, the lint will not be triggered!
48 #[rustfmt::skip]
49 #[deny(clippy::suspicious_else_formatting)]
50 async fn repro_1613(var: bool) {
51 println!(
52 "{}",
53 if var { "true" } else { "false" }
54 );
55 }
56
57 // Reproduces https://github.com/tokio-rs/tracing/issues/1613
58 // and https://github.com/rust-lang/rust-clippy/issues/7760
59 #[instrument]
60 #[deny(clippy::suspicious_else_formatting)]
61 async fn repro_1613_2() {
62 // hello world
63 // else
64 }
65
66 // Reproduces https://github.com/tokio-rs/tracing/issues/1831
67 #[allow(dead_code)] // this is just here to test whether it compiles.
68 #[instrument]
69 #[deny(unused_braces)]
70 fn repro_1831() -> Pin<Box<dyn Future<Output = ()>>> {
71 Box::pin(async move {})
72 }
73
74 // This replicates the pattern used to implement async trait methods on nightly using the
75 // `type_alias_impl_trait` feature
76 #[allow(dead_code)] // this is just here to test whether it compiles.
77 #[instrument(ret, err)]
78 #[deny(unused_braces)]
79 #[allow(clippy::manual_async_fn)]
80 fn repro_1831_2() -> impl Future<Output = Result<(), Infallible>> {
81 async { Ok(()) }
82 }
83
84 #[test]
85 fn async_fn_only_enters_for_polls() {
86 let (subscriber, handle) = subscriber::mock()
87 .new_span(span::mock().named("test_async_fn"))
88 .enter(span::mock().named("test_async_fn"))
89 .event(event::mock().with_fields(field::mock("awaiting").with_value(&true)))
90 .exit(span::mock().named("test_async_fn"))
91 .enter(span::mock().named("test_async_fn"))
92 .exit(span::mock().named("test_async_fn"))
93 .enter(span::mock().named("test_async_fn"))
94 .exit(span::mock().named("test_async_fn"))
95 .drop_span(span::mock().named("test_async_fn"))
96 .done()
97 .run_with_handle();
98 with_default(subscriber, || {
99 block_on_future(async { test_async_fn(2).await }).unwrap();
100 });
101 handle.assert_finished();
102 }
103
104 #[test]
105 fn async_fn_nested() {
106 #[instrument]
107 async fn test_async_fns_nested() {
108 test_async_fns_nested_other().await
109 }
110
111 #[instrument]
112 async fn test_async_fns_nested_other() {
113 tracing::trace!(nested = true);
114 }
115
116 let span = span::mock().named("test_async_fns_nested");
117 let span2 = span::mock().named("test_async_fns_nested_other");
118 let (subscriber, handle) = subscriber::mock()
119 .new_span(span.clone())
120 .enter(span.clone())
121 .new_span(span2.clone())
122 .enter(span2.clone())
123 .event(event::mock().with_fields(field::mock("nested").with_value(&true)))
124 .exit(span2.clone())
125 .enter(span2.clone())
126 .exit(span2.clone())
127 .drop_span(span2)
128 .exit(span.clone())
129 .enter(span.clone())
130 .exit(span.clone())
131 .drop_span(span)
132 .done()
133 .run_with_handle();
134
135 with_default(subscriber, || {
136 block_on_future(async { test_async_fns_nested().await });
137 });
138
139 handle.assert_finished();
140 }
141
142 #[test]
143 fn async_fn_with_async_trait() {
144 use async_trait::async_trait;
145
146 // test the correctness of the metadata obtained by #[instrument]
147 // (function name, functions parameters) when async-trait is used
148 #[async_trait]
149 pub trait TestA {
150 async fn foo(&mut self, v: usize);
151 }
152
153 // test nesting of async fns with aync-trait
154 #[async_trait]
155 pub trait TestB {
156 async fn bar(&self);
157 }
158
159 // test skip(self) with async-await
160 #[async_trait]
161 pub trait TestC {
162 async fn baz(&self);
163 }
164
165 #[derive(Debug)]
166 struct TestImpl(usize);
167
168 #[async_trait]
169 impl TestA for TestImpl {
170 #[instrument]
171 async fn foo(&mut self, v: usize) {
172 self.baz().await;
173 self.0 = v;
174 self.bar().await
175 }
176 }
177
178 #[async_trait]
179 impl TestB for TestImpl {
180 #[instrument]
181 async fn bar(&self) {
182 tracing::trace!(val = self.0);
183 }
184 }
185
186 #[async_trait]
187 impl TestC for TestImpl {
188 #[instrument(skip(self))]
189 async fn baz(&self) {
190 tracing::trace!(val = self.0);
191 }
192 }
193
194 let span = span::mock().named("foo");
195 let span2 = span::mock().named("bar");
196 let span3 = span::mock().named("baz");
197 let (subscriber, handle) = subscriber::mock()
198 .new_span(
199 span.clone()
200 .with_field(field::mock("self"))
201 .with_field(field::mock("v")),
202 )
203 .enter(span.clone())
204 .new_span(span3.clone())
205 .enter(span3.clone())
206 .event(event::mock().with_fields(field::mock("val").with_value(&2u64)))
207 .exit(span3.clone())
208 .enter(span3.clone())
209 .exit(span3.clone())
210 .drop_span(span3)
211 .new_span(span2.clone().with_field(field::mock("self")))
212 .enter(span2.clone())
213 .event(event::mock().with_fields(field::mock("val").with_value(&5u64)))
214 .exit(span2.clone())
215 .enter(span2.clone())
216 .exit(span2.clone())
217 .drop_span(span2)
218 .exit(span.clone())
219 .enter(span.clone())
220 .exit(span.clone())
221 .drop_span(span)
222 .done()
223 .run_with_handle();
224
225 with_default(subscriber, || {
226 let mut test = TestImpl(2);
227 block_on_future(async { test.foo(5).await });
228 });
229
230 handle.assert_finished();
231 }
232
233 #[test]
234 fn async_fn_with_async_trait_and_fields_expressions() {
235 use async_trait::async_trait;
236
237 #[async_trait]
238 pub trait Test {
239 async fn call(&mut self, v: usize);
240 }
241
242 #[derive(Clone, Debug)]
243 struct TestImpl;
244
245 impl TestImpl {
246 fn foo(&self) -> usize {
247 42
248 }
249 }
250
251 #[async_trait]
252 impl Test for TestImpl {
253 // check that self is correctly handled, even when using async_trait
254 #[instrument(fields(val=self.foo(), val2=Self::clone(self).foo(), test=%_v+5))]
255 async fn call(&mut self, _v: usize) {}
256 }
257
258 let span = span::mock().named("call");
259 let (subscriber, handle) = subscriber::mock()
260 .new_span(
261 span.clone().with_field(
262 field::mock("_v")
263 .with_value(&5usize)
264 .and(field::mock("test").with_value(&tracing::field::debug(10)))
265 .and(field::mock("val").with_value(&42u64))
266 .and(field::mock("val2").with_value(&42u64)),
267 ),
268 )
269 .enter(span.clone())
270 .exit(span.clone())
271 .enter(span.clone())
272 .exit(span.clone())
273 .drop_span(span)
274 .done()
275 .run_with_handle();
276
277 with_default(subscriber, || {
278 block_on_future(async { TestImpl.call(5).await });
279 });
280
281 handle.assert_finished();
282 }
283
284 #[test]
285 fn async_fn_with_async_trait_and_fields_expressions_with_generic_parameter() {
286 use async_trait::async_trait;
287
288 #[async_trait]
289 pub trait Test {
290 async fn call();
291 async fn call_with_self(&self);
292 async fn call_with_mut_self(&mut self);
293 }
294
295 #[derive(Clone, Debug)]
296 struct TestImpl;
297
298 // we also test sync functions that return futures, as they should be handled just like
299 // async-trait (>= 0.1.44) functions
300 impl TestImpl {
301 #[instrument(fields(Self=std::any::type_name::<Self>()))]
302 fn sync_fun(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
303 let val = self.clone();
304 Box::pin(async move {
305 let _ = val;
306 })
307 }
308 }
309
310 #[async_trait]
311 impl Test for TestImpl {
312 // instrumenting this is currently not possible, see https://github.com/tokio-rs/tracing/issues/864#issuecomment-667508801
313 //#[instrument(fields(Self=std::any::type_name::<Self>()))]
314 async fn call() {}
315
316 #[instrument(fields(Self=std::any::type_name::<Self>()))]
317 async fn call_with_self(&self) {
318 self.sync_fun().await;
319 }
320
321 #[instrument(fields(Self=std::any::type_name::<Self>()))]
322 async fn call_with_mut_self(&mut self) {}
323 }
324
325 //let span = span::mock().named("call");
326 let span2 = span::mock().named("call_with_self");
327 let span3 = span::mock().named("call_with_mut_self");
328 let span4 = span::mock().named("sync_fun");
329 let (subscriber, handle) = subscriber::mock()
330 /*.new_span(span.clone()
331 .with_field(
332 field::mock("Self").with_value(&"TestImpler")))
333 .enter(span.clone())
334 .exit(span.clone())
335 .drop_span(span)*/
336 .new_span(
337 span2
338 .clone()
339 .with_field(field::mock("Self").with_value(&std::any::type_name::<TestImpl>())),
340 )
341 .enter(span2.clone())
342 .new_span(
343 span4
344 .clone()
345 .with_field(field::mock("Self").with_value(&std::any::type_name::<TestImpl>())),
346 )
347 .enter(span4.clone())
348 .exit(span4.clone())
349 .enter(span4.clone())
350 .exit(span4)
351 .exit(span2.clone())
352 .enter(span2.clone())
353 .exit(span2.clone())
354 .drop_span(span2)
355 .new_span(
356 span3
357 .clone()
358 .with_field(field::mock("Self").with_value(&std::any::type_name::<TestImpl>())),
359 )
360 .enter(span3.clone())
361 .exit(span3.clone())
362 .enter(span3.clone())
363 .exit(span3.clone())
364 .drop_span(span3)
365 .done()
366 .run_with_handle();
367
368 with_default(subscriber, || {
369 block_on_future(async {
370 TestImpl::call().await;
371 TestImpl.call_with_self().await;
372 TestImpl.call_with_mut_self().await
373 });
374 });
375
376 handle.assert_finished();
377 }
378
379 #[test]
380 fn out_of_scope_fields() {
381 // Reproduces tokio-rs/tracing#1296
382
383 struct Thing {
384 metrics: Arc<()>,
385 }
386
387 impl Thing {
388 #[instrument(skip(self, _req), fields(app_id))]
389 fn call(&mut self, _req: ()) -> Pin<Box<dyn Future<Output = Arc<()>> + Send + Sync>> {
390 // ...
391 let metrics = self.metrics.clone();
392 // ...
393 Box::pin(async move {
394 // ...
395 metrics // cannot find value `metrics` in this scope
396 })
397 }
398 }
399
400 let span = span::mock().named("call");
401 let (subscriber, handle) = subscriber::mock()
402 .new_span(span.clone())
403 .enter(span.clone())
404 .exit(span.clone())
405 .enter(span.clone())
406 .exit(span.clone())
407 .drop_span(span)
408 .done()
409 .run_with_handle();
410
411 with_default(subscriber, || {
412 block_on_future(async {
413 let mut my_thing = Thing {
414 metrics: Arc::new(()),
415 };
416 my_thing.call(()).await;
417 });
418 });
419
420 handle.assert_finished();
421 }
422
423 #[test]
424 fn manual_impl_future() {
425 #[allow(clippy::manual_async_fn)]
426 #[instrument]
427 fn manual_impl_future() -> impl Future<Output = ()> {
428 async {
429 tracing::trace!(poll = true);
430 }
431 }
432
433 let span = span::mock().named("manual_impl_future");
434 let poll_event = || event::mock().with_fields(field::mock("poll").with_value(&true));
435
436 let (subscriber, handle) = subscriber::mock()
437 // await manual_impl_future
438 .new_span(span.clone())
439 .enter(span.clone())
440 .event(poll_event())
441 .exit(span.clone())
442 .enter(span.clone())
443 .exit(span.clone())
444 .drop_span(span)
445 .done()
446 .run_with_handle();
447
448 with_default(subscriber, || {
449 block_on_future(async {
450 manual_impl_future().await;
451 });
452 });
453
454 handle.assert_finished();
455 }
456
457 #[test]
458 fn manual_box_pin() {
459 #[instrument]
460 fn manual_box_pin() -> Pin<Box<dyn Future<Output = ()>>> {
461 Box::pin(async {
462 tracing::trace!(poll = true);
463 })
464 }
465
466 let span = span::mock().named("manual_box_pin");
467 let poll_event = || event::mock().with_fields(field::mock("poll").with_value(&true));
468
469 let (subscriber, handle) = subscriber::mock()
470 // await manual_box_pin
471 .new_span(span.clone())
472 .enter(span.clone())
473 .event(poll_event())
474 .exit(span.clone())
475 .enter(span.clone())
476 .exit(span.clone())
477 .drop_span(span)
478 .done()
479 .run_with_handle();
480
481 with_default(subscriber, || {
482 block_on_future(async {
483 manual_box_pin().await;
484 });
485 });
486
487 handle.assert_finished();
488 }