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
use itertools::Itertools;
use std::{cell::RefCell, fmt::Display, rc::Rc};

use regex::Regex;

/// Accumulates a sequence of messages (e.g. validation failures).
#[derive(Debug, Default)]
pub struct MessageAccumulator {
    /// Accumulated messages.
    /// This is a `Rc<RefCell>` to support accumulators derived from `with_prefix()` accumulating to
    /// the same underlying collection.
    msgs: Rc<RefCell<Vec<String>>>,
    /// Optional prefix to all new messages, e.g. describing higher level context.
    prefix: String,
}

impl MessageAccumulator {
    /// Returns a new accumulator backed by the same collection, that will prefix each new message with
    /// a formatted string.
    pub fn with_prefix<S: AsRef<str>>(&self, prefix: S) -> Self {
        MessageAccumulator {
            msgs: self.msgs.clone(),
            prefix: self.prefix.to_owned() + prefix.as_ref(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.msgs.borrow().is_empty()
    }

    pub fn messages(&self) -> Vec<String> {
        self.msgs.borrow().to_owned()
    }

    /// Returns the number of accumulated messages
    pub fn len(&self) -> usize {
        self.msgs.borrow().len()
    }

    /// Adds a message to the accumulator
    pub fn add<S: AsRef<str>>(&self, msg: S) {
        self.msgs
            .borrow_mut()
            .push(format!("{}{}", self.prefix, msg.as_ref()));
    }

    /// Adds messages from another accumulator to this one
    pub fn add_all(&self, other: &Self) {
        self.msgs
            .borrow_mut()
            .extend_from_slice(&other.msgs.borrow());
    }

    /// Adds a message if predicate is false
    pub fn require<S: AsRef<str>>(&self, predicate: bool, msg: S) {
        if !predicate {
            self.add(msg);
        }
    }

    /// Adds a message if result is `Err`. Underlying error must be `Display`.
    pub fn require_no_error<V, E: Display, S: AsRef<str>>(&self, result: Result<V, E>, msg: S) {
        if let Err(e) = result {
            self.add(format!("{}: {e}", msg.as_ref()));
        }
    }

    /// Panic if the accumulator isn't empty. The acculumated messages are included in the panic message.
    #[track_caller]
    pub fn assert_empty(&self) {
        assert!(self.is_empty(), "{}", self.messages().join("\n"))
    }

    /// Asserts the accumulator contains messages matching provided pattern *in the given order*.
    #[track_caller]
    pub fn assert_expected(&self, expected_patterns: &[Regex]) {
        let messages = self.messages();
        assert!(
            messages.len() == expected_patterns.len(),
            "Incorrect number of accumulator messages.\nActual: {}.\nExpected: {}",
            messages.join("\n"),
            expected_patterns
                .iter()
                .map(|regex| regex.as_str())
                .join("\n")
        );

        messages
            .iter()
            .zip(expected_patterns)
            .for_each(|(message, pattern)| {
                assert!(
                    pattern.is_match(message),
                    "message does not match. Actual: {}, expected: {}",
                    message,
                    pattern.as_str()
                );
            });
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn adds_messages() {
        let acc = MessageAccumulator::default();
        acc.add("Cthulhu");
        assert_eq!(acc.len(), 1);

        let msgs = acc.messages();
        assert_eq!(msgs, vec!["Cthulhu"]);

        acc.add("Azathoth");
        assert_eq!(acc.len(), 2);

        let msgs = acc.messages();
        assert_eq!(msgs, vec!["Cthulhu", "Azathoth"]);
    }

    #[test]
    fn adds_on_predicate() {
        let acc = MessageAccumulator::default();
        acc.require(true, "Cthulhu");

        assert_eq!(acc.len(), 0);
        assert!(acc.is_empty());

        acc.require(false, "Azathoth");
        let msgs = acc.messages();
        assert_eq!(acc.len(), 1);
        assert_eq!(msgs, vec!["Azathoth"]);
        assert!(!acc.is_empty());
    }

    #[test]
    fn require_no_error() {
        let fiasco: Result<(), String> = Err("fiasco".to_owned());
        let acc = MessageAccumulator::default();
        acc.require_no_error(fiasco, "Cthulhu says");

        let msgs = acc.messages();
        assert_eq!(acc.len(), 1);
        assert_eq!(msgs, vec!["Cthulhu says: fiasco"]);
    }

    #[test]
    fn prefixes() {
        let acc = MessageAccumulator::default();
        acc.add("peasant");

        let gods_acc = acc.with_prefix("elder god -> ");
        gods_acc.add("Cthulhu");

        assert_eq!(acc.messages(), vec!["peasant", "elder god -> Cthulhu"]);
        assert_eq!(gods_acc.messages(), vec!["peasant", "elder god -> Cthulhu"]);
    }

    #[test]
    fn add_all() {
        let acc1 = MessageAccumulator::default();
        acc1.add("Cthulhu");

        let acc2 = MessageAccumulator::default();
        acc2.add("Azathoth");

        let acc3 = MessageAccumulator::default();
        acc3.add_all(&acc1);
        acc3.add_all(&acc2);

        assert_eq!(2, acc3.len());
        assert_eq!(acc3.messages(), vec!["Cthulhu", "Azathoth"]);
    }
}