summaryrefslogtreecommitdiff
path: root/src/matches.rs
blob: 91306411e170c91e8db5b9f8742087f6d9b659f9 (plain)
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
use crate::Binding;
use crate::Scenario;
use crate::StepKind;
use crate::SubplotError;
use crate::{bindings::CaptureType, Bindings};

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// A scenario that has all of its steps matched with steps using bindings.
#[derive(Debug, Serialize, Deserialize)]
pub struct MatchedScenario {
    title: String,
    steps: Vec<MatchedStep>,
}

impl MatchedScenario {
    /// Construct a new matched scenario
    pub fn new(
        template: &str,
        scen: &Scenario,
        bindings: &Bindings,
    ) -> Result<MatchedScenario, SubplotError> {
        let steps: Result<Vec<MatchedStep>, SubplotError> = scen
            .steps()
            .iter()
            .map(|step| bindings.find(template, step))
            .collect();
        Ok(MatchedScenario {
            title: scen.title().to_string(),
            steps: steps?,
        })
    }

    /// Get the steps in this matched scenario
    pub fn steps(&self) -> &[MatchedStep] {
        &self.steps
    }

    /// Retrieve the scenario title
    pub fn title(&self) -> &str {
        &self.title
    }
}

/// A list of matched steps.
#[derive(Debug)]
pub struct MatchedSteps {
    matches: Vec<MatchedStep>,
}

impl MatchedSteps {
    /// Create new set of steps that match a scenario step.
    pub fn new(matches: Vec<MatchedStep>) -> Self {
        Self { matches }
    }
}

impl std::fmt::Display for MatchedSteps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        let matches: Vec<String> = self.matches.iter().map(|m| m.pattern()).collect();
        write!(f, "{}", matches.join("\n"))
    }
}

/// A matched binding and scenario step, with captured parts.
///
/// A MatchedStep is a sequence of partial steps, each representing
/// either a captured or a matching part of the text of the step.
#[derive(Debug, Serialize, Deserialize)]
pub struct MatchedStep {
    kind: StepKind,
    pattern: String,
    text: String,
    parts: Vec<PartialStep>,
    function: Option<String>,
    cleanup: Option<String>,
    types: HashMap<String, CaptureType>,
}

impl MatchedStep {
    /// Return a new empty match. Empty means it has no step parts.
    pub fn new(binding: &Binding, template: &str) -> MatchedStep {
        let bimpl = binding.step_impl(template);
        MatchedStep {
            kind: binding.kind(),
            pattern: binding.pattern().to_string(),
            text: "".to_string(),
            parts: vec![],
            function: bimpl.clone().map(|b| b.function().to_owned()),
            cleanup: bimpl.and_then(|b| b.cleanup().map(String::from)),
            types: binding.types().map(|(s, c)| (s.to_string(), c)).collect(),
        }
    }

    /// The kind of step that has been matched.
    pub fn kind(&self) -> StepKind {
        self.kind
    }

    /// The name of the function to call for the step.
    pub fn function(&self) -> Option<&str> {
        self.function.as_deref()
    }

    /// Append a partial step to the match.
    pub fn append_part(&mut self, part: PartialStep) {
        self.parts.push(part);
        self.text = self.update_text();
    }

    /// Iterate over all partial steps in the match.
    pub fn parts(&self) -> impl Iterator<Item = &PartialStep> {
        self.parts.iter()
    }

    fn pattern(&self) -> String {
        self.pattern.to_string()
    }

    fn update_text(&self) -> String {
        let mut t = String::new();
        for part in self.parts() {
            t.push_str(part.as_text());
        }
        t
    }

    /// Return the step's text
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Return the typemap for the matched step
    pub fn types(&self) -> &HashMap<String, CaptureType> {
        &self.types
    }
}

/// Part of a scenario step, possibly captured by a pattern.
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum PartialStep {
    /// The text of a step part that isn't captured.
    UncapturedText(StepSnippet),

    /// A captured step part that is just text, and the regex capture
    /// name that corresponds to it.
    CapturedText {
        /// Name of the capture.
        name: String,
        /// Text of the capture.
        text: String,
    },
}

impl PartialStep {
    /// Construct an uncaptured part of a scenario step.
    pub fn uncaptured(text: &str) -> PartialStep {
        PartialStep::UncapturedText(StepSnippet::new(text))
    }

    /// Construct a textual captured part of a scenario step.
    pub fn text(name: &str, text: &str) -> PartialStep {
        PartialStep::CapturedText {
            name: name.to_string(),
            text: text.to_string(),
        }
    }

    fn as_text(&self) -> &str {
        match self {
            PartialStep::UncapturedText(snippet) => snippet.text(),
            PartialStep::CapturedText { text, .. } => text,
        }
    }
}

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

    #[test]
    fn identical_uncaptured_texts_match() {
        let p1 = PartialStep::uncaptured("foo");
        let p2 = PartialStep::uncaptured("foo");
        assert_eq!(p1, p2);
    }

    #[test]
    fn different_uncaptured_texts_dont_match() {
        let p1 = PartialStep::uncaptured("foo");
        let p2 = PartialStep::uncaptured("bar");
        assert_ne!(p1, p2);
    }

    #[test]
    fn identical_captured_texts_match() {
        let p1 = PartialStep::text("xxx", "foo");
        let p2 = PartialStep::text("xxx", "foo");
        assert_eq!(p1, p2);
    }

    #[test]
    fn different_captured_texts_dont_match() {
        let p1 = PartialStep::text("xxx", "foo");
        let p2 = PartialStep::text("xxx", "bar");
        assert_ne!(p1, p2);
    }

    #[test]
    fn differently_named_captured_texts_dont_match() {
        let p1 = PartialStep::text("xxx", "foo");
        let p2 = PartialStep::text("yyy", "foo");
        assert_ne!(p1, p2);
    }

    #[test]
    fn differently_captured_texts_dont_match() {
        let p1 = PartialStep::uncaptured("foo");
        let p2 = PartialStep::text("xxx", "foo");
        assert_ne!(p1, p2);
    }
}

/// The text of a part of a scenario step.
///
/// This is used by both unmatched and matched parts of a step. This
/// will later grow to include more information for better error
/// messges etc.
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub struct StepSnippet {
    text: String,
}

impl StepSnippet {
    /// Create a new snippet.
    pub fn new(text: &str) -> StepSnippet {
        StepSnippet {
            text: text.to_owned(),
        }
    }

    /// Return the text of the snippet.
    pub fn text(&self) -> &str {
        &self.text
    }
}

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

    #[test]
    fn returns_uncaptured() {
        let p = PartialStep::uncaptured("foo");
        match p {
            PartialStep::UncapturedText(s) => assert_eq!(s.text(), "foo"),
            _ => panic!("expected UncapturedText: {:?}", p),
        }
    }

    #[test]
    fn returns_text() {
        let p = PartialStep::text("xxx", "foo");
        match p {
            PartialStep::CapturedText { name, text } => {
                assert_eq!(name, "xxx");
                assert_eq!(text, "foo");
            }
            _ => panic!("expected CapturedText: {:?}", p),
        }
    }
}