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
//! [![Crates.io](https://img.shields.io/crates/v/tracing-assertions)](https://crates.io/crates/tracing-assertions)
//! [![docs](https://img.shields.io/crates/v/tracing-assertions?color=yellow&label=docs)](https://docs.rs/tracing-assertions)
//! [![codecov](https://codecov.io/gh/JonathanWoollett-Light/tracing-assertions/branch/master/graph/badge.svg?token=II1xtnbCDX)](https://codecov.io/gh/JonathanWoollett-Light/tracing-assertions)
//!
//! An assertions framework for [tracing](https://docs.rs/tracing/latest/tracing/).
//!
//! Simpler and faster than the alternatives.
//!
//! ```
//! use tracing_subscriber::layer::SubscriberExt;
//! // Initialize a subscriber with the layer.
//! let asserter = tracing_assertions::Layer::default();
//! let registry = tracing_subscriber::Registry::default();
//! let subscriber = registry.with(asserter.clone());
//! let guard = tracing::subscriber::set_default(subscriber);
//! let one = asserter.matches("one");
//! let two = asserter.matches("two");
//! let and = &one & &two;
//! tracing::info!("one");
//! one.assert();
//! tracing::info!("two");
//! two.assert();
//! and.assert();
//!
//! drop(guard); // Drop `subscriber` as the current subscriber.
//! ```
//!
//! ### Failing
//!
//! When failing e.g.
//! ```should_panic
//! # use tracing_subscriber::layer::SubscriberExt;
//! # let asserter = tracing_assertions::Layer::default();
//! # let registry = tracing_subscriber::Registry::default();
//! # let subscriber = registry.with(asserter.clone());
//! # let guard = tracing::subscriber::set_default(subscriber);
//! let one = asserter.matches("one");
//! let two = asserter.matches("two");
//! let and = &one & &two;
//! tracing::info!("one");
//! and.assert();
//! # drop(guard);
//! ```
//! Outputs:
//! <pre>
//! thread 'main' panicked at src/lib.rs:14:5:
//! (<font color="green">"one"</font> && <font color="red">"two"</font>)
//! </pre>
//!
//! ### Operations
//!
//! Logical operations clone the underlying assertions.
//! ```
//! # use tracing_subscriber::layer::SubscriberExt;
//! # let asserter = tracing_assertions::Layer::default();
//! # let registry = tracing_subscriber::Registry::default();
//! # let subscriber = registry.with(asserter.clone());
//! # let guard = tracing::subscriber::set_default(subscriber);
//! let one = asserter.matches("one");
//! let two = asserter.matches("two");
//! let and = &one & &two;
//! tracing::info!("one");
//! tracing::info!("two");
//! one.assert().reset();
//! and.assert().reset();
//! two.assert();
//! (!one).assert();
//! (!and).assert();
//! ```
//! Calling [`Assertion::reset`] on `one` does not affect the value of `and` and calling [`Assertion::reset`] on `and` does not affect the value of `two`.
//!
//! ### Similar crates
//! - [test-log](https://crates.io/crates/test-log): A replacement of the `#[test]` attribute that initializes logging and/or tracing infrastructure before running tests.
//! - [tracing_test](https://crates.io/crates/tracing-test): Helper functions and macros that allow for easier testing of crates that use `tracing`.
//! - [tracing-fluent-assertions](https://crates.io/crates/tracing-fluent-assertions): An fluent assertions framework for tracing.
//!

#![warn(clippy::pedantic)]
#![allow(clippy::enum_glob_use)] // Matching is prettier doing this.

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
use std::sync::Mutex;
use tracing::field::Field;
use tracing::Event;
use tracing::Subscriber;
use tracing_subscriber::field::Visit;
use tracing_subscriber::layer::Context;

/// The assertion layer.
#[derive(Default, Clone, Debug)]
pub struct Layer(Arc<InnerLayer>);

/// The inner layer shared between assertions and the assertion layer.
///
/// You should probably not use this directly.
#[derive(Default, Debug)]
struct InnerLayer {
    pass_all: AtomicBool,
    assertions: Mutex<Vec<Arc<InnerAssertion>>>,
}

impl Layer {
    /// Creates a string matching assertion.
    ///
    /// # Panics
    ///
    /// When the internal mutex is poisoned.
    pub fn matches(&self, s: impl Into<String>) -> Assertion {
        let inner_assertion = Arc::new(InnerAssertion {
            boolean: AtomicBool::new(false),
            assertion_type: AssertionType::Matches(s.into()),
        });
        self.0
            .assertions
            .lock()
            .unwrap()
            .push(inner_assertion.clone());
        Assertion(AssertionWrapper::One {
            assertion: inner_assertion.clone(),
            asserter: self.0.clone(),
        })
    }
    /// The inverse of [`Layer::disable`].
    pub fn enable(&self) {
        self.0.pass_all.store(false, SeqCst);
    }
    /// Tells all assertions to pass.
    ///
    /// Useful when you want to disables certain tested logs in a
    /// test for debugging without needing to comment out all the
    /// assertions you added.
    pub fn disable(&self) {
        self.0.pass_all.store(true, SeqCst);
    }
}

#[derive(Debug, Clone)]
enum AssertionType {
    Matches(String),
}

impl std::fmt::Display for AssertionType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Matches(matches) => write!(f, "{matches}"),
        }
    }
}

/// An assertion.
#[derive(Debug, Clone)]
pub struct Assertion(AssertionWrapper);

/// This exists since there is no way of making enum variants private.
#[derive(Debug)]
enum AssertionWrapper {
    And {
        lhs: Box<Assertion>,
        rhs: Box<Assertion>,
    },
    Or {
        lhs: Box<Assertion>,
        rhs: Box<Assertion>,
    },
    One {
        assertion: Arc<InnerAssertion>,
        asserter: Arc<InnerLayer>,
    },
    Not {
        assertion: Box<Assertion>,
    },
}
impl Clone for AssertionWrapper {
    fn clone(&self) -> AssertionWrapper {
        use AssertionWrapper::*;
        match &self {
            One {
                assertion,
                asserter,
            } => {
                let new_assertion = Arc::new(InnerAssertion {
                    boolean: AtomicBool::from(assertion.boolean.load(SeqCst)),
                    assertion_type: assertion.assertion_type.clone(),
                });
                asserter
                    .assertions
                    .lock()
                    .unwrap()
                    .push(new_assertion.clone());
                One {
                    assertion: new_assertion,
                    asserter: asserter.clone(),
                }
            }
            Not { assertion } => Not {
                assertion: assertion.clone(),
            },
            And { lhs, rhs } => And {
                lhs: lhs.clone(),
                rhs: rhs.clone(),
            },
            Or { lhs, rhs } => Or {
                lhs: lhs.clone(),
                rhs: rhs.clone(),
            },
        }
    }
}

impl Assertion {
    /// Evaluates the assertion.
    ///
    /// # Panics
    ///
    /// When the assertion is false.
    #[allow(clippy::must_use_candidate)] // `let _ = x.assert();` is ugly.
    #[track_caller]
    pub fn assert(&self) -> &Self {
        assert!(bool::from(self), "{}", self.ansi());
        self
    }
    /// Create a new assertion with the same condition.
    ///
    /// ```
    /// use tracing_subscriber::layer::SubscriberExt;
    /// let asserter = tracing_assertions::Layer::default();
    /// let registry = tracing_subscriber::Registry::default();
    /// let subscriber = registry.with(asserter.clone());
    /// let guard = tracing::subscriber::set_default(subscriber);
    /// let one = asserter.matches("one");
    /// tracing::info!("one");
    /// one.assert();
    /// let one2 = one.repeat();
    /// (!&one2).assert();
    /// tracing::info!("one");
    /// one2.assert();
    /// ```
    ///
    /// # Panics
    ///
    /// When the inner mutex is poisoned.
    #[must_use]
    pub fn repeat(&self) -> Self {
        use AssertionWrapper::*;
        let inner = match &self.0 {
            One {
                assertion,
                asserter,
            } => {
                let new_assertion = Arc::new(InnerAssertion {
                    boolean: AtomicBool::new(false),
                    assertion_type: assertion.assertion_type.clone(),
                });
                asserter
                    .assertions
                    .lock()
                    .unwrap()
                    .push(new_assertion.clone());
                One {
                    assertion: new_assertion,
                    asserter: asserter.clone(),
                }
            }
            Not { assertion } => Not {
                assertion: Box::new(assertion.repeat()),
            },
            And { lhs, rhs } => And {
                lhs: Box::new(lhs.repeat()),
                rhs: Box::new(rhs.repeat()),
            },
            Or { lhs, rhs } => Or {
                lhs: Box::new(lhs.repeat()),
                rhs: Box::new(rhs.repeat()),
            },
        };
        Self(inner)
    }

    /// Resets the assertion.
    ///
    /// ```
    /// use tracing_subscriber::layer::SubscriberExt;
    /// let asserter = tracing_assertions::Layer::default();
    /// let registry = tracing_subscriber::Registry::default();
    /// let subscriber = registry.with(asserter.clone());
    /// let guard = tracing::subscriber::set_default(subscriber);
    /// let one = asserter.matches("one");
    /// tracing::info!("one");
    /// one.assert().reset();
    /// (!&one).assert();
    /// tracing::info!("one");
    /// one.assert();
    /// ```
    ///
    /// # Panics
    ///
    /// When the inner mutex is poisoned.
    pub fn reset(&self) {
        use AssertionWrapper::*;
        match &self.0 {
            One {
                assertion,
                asserter,
            } => {
                if assertion.boolean.swap(false, SeqCst) {
                    asserter.assertions.lock().unwrap().push(assertion.clone());
                }
            }
            Not { assertion } => assertion.reset(),
            And { lhs, rhs } | Or { lhs, rhs } => {
                lhs.reset();
                rhs.reset();
            }
        }
    }

    fn ansi(&self) -> String {
        use AssertionWrapper::*;

        match &self.0 {
            One {
                assertion,
                asserter,
            } => {
                let is_true = if asserter.pass_all.load(SeqCst) {
                    true
                } else {
                    assertion.boolean.load(std::sync::atomic::Ordering::SeqCst)
                };
                let str = format!("{:?}", assertion.assertion_type.to_string());
                let out = if is_true {
                    ansi_term::Colour::Green.paint(str)
                } else {
                    ansi_term::Colour::Red.paint(str)
                };
                out.to_string()
            }
            And { lhs, rhs } => format!("({} && {})", lhs.ansi(), rhs.ansi()),
            Or { lhs, rhs } => format!("({} || {})", lhs.ansi(), rhs.ansi()),
            Not { assertion } => format!("!{}", assertion.ansi()),
        }
    }
}

impl std::ops::Not for Assertion {
    type Output = Self;
    fn not(self) -> Self::Output {
        !&self
    }
}
impl std::ops::Not for &Assertion {
    type Output = Assertion;
    fn not(self) -> Self::Output {
        Assertion(AssertionWrapper::Not {
            assertion: Box::new(self.clone()),
        })
    }
}

impl std::ops::BitAnd for Assertion {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        &self & &rhs
    }
}
impl std::ops::BitAnd for &Assertion {
    type Output = Assertion;
    fn bitand(self, rhs: Self) -> Self::Output {
        Assertion(AssertionWrapper::And {
            lhs: Box::new(self.clone()),
            rhs: Box::new(rhs.clone()),
        })
    }
}
impl std::ops::BitOr for Assertion {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        &self | &rhs
    }
}
impl std::ops::BitOr for &Assertion {
    type Output = Assertion;
    fn bitor(self, rhs: Self) -> Self::Output {
        Assertion(AssertionWrapper::Or {
            lhs: Box::new(self.clone()),
            rhs: Box::new(rhs.clone()),
        })
    }
}

impl From<&Assertion> for bool {
    fn from(value: &Assertion) -> Self {
        use AssertionWrapper::*;
        match &value.0 {
            One {
                assertion,
                asserter,
            } => {
                if asserter.pass_all.load(SeqCst) {
                    return true;
                }
                assertion.boolean.load(std::sync::atomic::Ordering::SeqCst)
            }
            And { lhs, rhs } => bool::from(&**lhs) && bool::from(&**rhs),
            Or { lhs, rhs } => bool::from(&**lhs) || bool::from(&**rhs),
            Not { assertion } => !bool::from(&**assertion),
        }
    }
}
impl From<Assertion> for bool {
    fn from(value: Assertion) -> Self {
        bool::from(&value)
    }
}

/// The inner assertion shared between assertions and the assertion layer.
///
/// You should probably not use this directly.
#[derive(Debug)]
struct InnerAssertion {
    boolean: AtomicBool,
    assertion_type: AssertionType,
}

struct EventVisitor<'a>(&'a mut String);
impl<'a> Visit for EventVisitor<'a> {
    fn record_debug(&mut self, _field: &Field, value: &dyn std::fmt::Debug) {
        *self.0 = format!("{value:?}");
    }
}

impl<S: Subscriber> tracing_subscriber::layer::Layer<S> for Layer {
    fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
        // TODO This is a stupid way to access the message, surely there is a better way to get the message.
        let mut message = String::new();
        event.record(&mut EventVisitor(&mut message) as &mut dyn Visit);
        let mut assertions = self.0.assertions.lock().unwrap();
        let mut i = 0;
        while i < assertions.len() {
            let result = match &assertions[i].assertion_type {
                AssertionType::Matches(expected) => *expected == message,
            };
            assertions[i].boolean.store(result, SeqCst);
            if result {
                assertions.remove(i);
            } else {
                i += 1;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use tracing::info;

    use super::*;
    use tracing_subscriber::{layer::SubscriberExt, Registry};

    #[test]
    fn pass_all() {
        let asserter = Layer::default();
        let base_subscriber = Registry::default();
        let subscriber = base_subscriber.with(asserter.clone());
        let guard = tracing::subscriber::set_default(subscriber);

        info!("stuff");
        let condition = asserter.matches("missing");
        asserter.disable();
        info!("more stuff");
        condition.assert();
        asserter.enable();
        (!condition).assert();

        drop(guard);
    }

    #[test]
    #[should_panic(
        expected = "((\u{1b}[32m\"one\"\u{1b}[0m && \u{1b}[31m\"two\"\u{1b}[0m) || (\u{1b}[31m\"three\"\u{1b}[0m && !\u{1b}[31m\"four\"\u{1b}[0m))"
    )]
    fn panics() {
        let asserter = Layer::default();
        let registry = Registry::default();
        let subscriber = registry.with(asserter.clone());
        let guard = tracing::subscriber::set_default(subscriber);
        let one = asserter.matches("one");
        let two = asserter.matches("two");
        let three = asserter.matches("three");
        let four = asserter.matches("four");
        let assertion = one & two | three & !four;
        info!("one");
        asserter.disable();
        assertion.assert();
        assert_eq!(assertion.ansi(),"((\u{1b}[32m\"one\"\u{1b}[0m && \u{1b}[32m\"two\"\u{1b}[0m) || (\u{1b}[32m\"three\"\u{1b}[0m && !\u{1b}[32m\"four\"\u{1b}[0m))");
        asserter.enable();
        assertion.assert();
        drop(guard);
    }

    #[test]
    fn matches() {
        let asserter = Layer::default();
        let base_subscriber = Registry::default();
        let subscriber = base_subscriber.with(asserter.clone());
        let guard = tracing::subscriber::set_default(subscriber);

        let two = asserter.matches("two");
        let three = asserter.matches("three");
        let or = &two | &three;
        let and = &two & &three;
        let or2 = two.clone() | three.clone();
        let and2 = two.clone() & three.clone();

        // The assertion is false as message matching `two` has not been encountered.
        (!&two).assert();

        info!("one");

        // Still false.
        (!&two).assert();
        (!&or).assert();
        (!&or2).assert();

        info!("two");

        // The assertion is true as a message matching `two` has been encountered.
        two.assert();
        or.assert();
        or2.assert();
        (!&and).assert();
        (!&and2).assert();

        info!("three");

        // Still true.
        two.assert();
        and.assert();
        and2.assert();

        // If an assertion is created after the message, it will be false.
        // Each assertion can only be fulfilled based on messages after its creation.
        let two = asserter.matches("two");
        (!&two).assert();
        assert!(!bool::from(two));

        drop(guard);
    }

    #[test]
    fn repeat() {
        let asserter = Layer::default();
        let base_subscriber = Registry::default();
        let subscriber = base_subscriber.with(asserter.clone());
        let guard = tracing::subscriber::set_default(subscriber);

        let one = asserter.matches("one");
        let two = asserter.matches("two");
        let or = &one | &two;
        let and = &one & &two;
        let not = !&one;

        info!("one");
        info!("two");

        one.assert();
        two.assert();
        or.assert();
        and.assert();
        (!&not).assert();

        let one2 = one.repeat();
        let two2 = two.repeat();
        let or2 = or.repeat();
        let and2 = and.repeat();
        let not2 = not.repeat();

        (!&one2).assert();
        (!&two2).assert();
        (!&or2).assert();
        (!&and2).assert();
        (!(!&not2)).assert();

        info!("one");
        info!("two");

        one2.assert();
        two2.assert();
        or2.assert();
        and2.assert();
        (!&not2).assert();

        drop(guard);
    }

    #[test]
    fn reset() {
        let asserter = Layer::default();
        let base_subscriber = Registry::default();
        let subscriber = base_subscriber.with(asserter.clone());
        let guard = tracing::subscriber::set_default(subscriber);

        let one = asserter.matches("one");
        let two = asserter.matches("two");
        let or = &one | &two;
        let and = &one & &two;
        let not = !&one;

        not.assert().reset();

        info!("one");
        info!("two");

        one.assert().reset();
        two.assert().reset();
        or.assert().reset();
        and.assert().reset();

        (!&one).assert();
        (!&two).assert();
        (!&or).assert();
        (!&and).assert();
        (!&not).assert();

        info!("one");
        info!("two");

        one.assert();
        two.assert();
        or.assert();
        and.assert();
        (!&not).assert();

        drop(guard);
    }
}