Skip to main content

rstest_bdd_patterns/
keyword.rs

1//! Shared step keyword type and parsing utilities.
2//!
3//! This module provides the canonical [`StepKeyword`] enum used by both the
4//! runtime and proc-macro crates, ensuring consistent keyword handling across
5//! compile-time validation and runtime execution.
6
7use std::{fmt, str::FromStr};
8
9use gherkin::StepType;
10
11/// Keyword used to categorize a step definition.
12///
13/// The enum includes `And` and `But` variants for completeness, but feature
14/// parsing resolves them against the preceding `Given`/`When`/`Then` using
15/// the [`resolve`](Self::resolve) method.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum StepKeyword {
18    /// Setup preconditions for a scenario.
19    Given,
20    /// Perform an action when testing behaviour.
21    When,
22    /// Assert the expected outcome of a scenario.
23    Then,
24    /// Additional conditions that share context with the previous step.
25    And,
26    /// Negative or contrasting conditions.
27    But,
28}
29
30/// Define the canonical keyword table: the single source of truth for the
31/// string ↔ [`StepKeyword`] correspondence.
32///
33/// One invocation lists each `(canonical rendering, variant)` pair exactly
34/// once and expands to both directions of the mapping:
35///
36/// - the `KEYWORDS` table driving the case-insensitive [`StepKeyword::from_str`] lookup, and
37/// - the exhaustive match inside [`StepKeyword::as_str`].
38///
39/// Adding or renaming a keyword therefore means editing exactly one list
40/// (plus the enum variant itself); the parse and render sides cannot drift
41/// apart. The round-trip contract is pinned by the property suite in
42/// `tests/keyword_props.rs`.
43macro_rules! keyword_table {
44    ($(($name:literal, $variant:ident)),+ $(,)?) => {
45        /// Canonical keyword table mapping each rendering to its variant.
46        ///
47        /// Generated by [`keyword_table!`]; entries store the canonical
48        /// (title-case) rendering, and parsing compares ASCII
49        /// case-insensitively.
50        const KEYWORDS: &[(&str, StepKeyword)] = &[$(($name, StepKeyword::$variant)),+];
51
52        impl StepKeyword {
53            /// Return the keyword as a string slice.
54            ///
55            /// The rendering derives from the canonical keyword table entries.
56            ///
57            /// # Examples
58            ///
59            /// ```
60            /// use rstest_bdd_patterns::StepKeyword;
61            ///
62            /// assert_eq!(StepKeyword::Given.as_str(), "Given");
63            /// assert_eq!(StepKeyword::And.as_str(), "And");
64            /// ```
65            #[must_use]
66            pub const fn as_str(&self) -> &'static str {
67                match self {
68                    $(Self::$variant => $name),+
69                }
70            }
71        }
72    };
73}
74
75keyword_table![
76    ("Given", Given),
77    ("When", When),
78    ("Then", Then),
79    ("And", And),
80    ("But", But),
81];
82
83impl StepKeyword {
84    /// Resolve conjunctions to the semantic keyword of the previous step.
85    ///
86    /// When the current keyword is `And` or `But`, returns the value stored in
87    /// `prev`. For primary keywords (`Given`/`When`/`Then`), updates `prev` and
88    /// returns the keyword unchanged.
89    ///
90    /// Callers typically seed `prev` with the first primary keyword in a
91    /// sequence, defaulting to `Given` when none is found.
92    ///
93    /// # Examples
94    ///
95    /// ```
96    /// use rstest_bdd_patterns::StepKeyword;
97    ///
98    /// let mut prev = Some(StepKeyword::Given);
99    /// assert_eq!(StepKeyword::And.resolve(&mut prev), StepKeyword::Given);
100    /// assert_eq!(StepKeyword::When.resolve(&mut prev), StepKeyword::When);
101    /// assert_eq!(prev, Some(StepKeyword::When));
102    /// ```
103    #[must_use]
104    pub fn resolve(self, prev: &mut Option<Self>) -> Self {
105        if matches!(self, Self::And | Self::But) {
106            prev.as_ref().copied().unwrap_or(Self::Given)
107        } else {
108            *prev = Some(self);
109            self
110        }
111    }
112}
113
114/// Error returned when parsing a [`StepKeyword`] from a string fails.
115///
116/// Contains the unrecognized keyword text for diagnostic purposes.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct StepKeywordParseError(pub String);
119
120impl fmt::Display for StepKeywordParseError {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(f, "invalid step keyword: {}", self.0)
123    }
124}
125
126impl std::error::Error for StepKeywordParseError {}
127
128impl FromStr for StepKeyword {
129    type Err = StepKeywordParseError;
130
131    /// Parse a keyword case-insensitively via the canonical keyword table,
132    /// trimming surrounding whitespace first.
133    fn from_str(value: &str) -> Result<Self, Self::Err> {
134        let trimmed = value.trim();
135        KEYWORDS
136            .iter()
137            .find(|(name, _)| trimmed.eq_ignore_ascii_case(name))
138            .map(|&(_, keyword)| keyword)
139            .ok_or_else(|| StepKeywordParseError(trimmed.to_owned()))
140    }
141}
142
143impl TryFrom<&str> for StepKeyword {
144    type Error = StepKeywordParseError;
145
146    fn try_from(value: &str) -> Result<Self, Self::Error> { value.parse() }
147}
148
149/// Error raised when converting a parsed Gherkin [`StepType`] into a
150/// [`StepKeyword`] fails.
151///
152/// Captures the offending [`StepType`] to help callers diagnose missing
153/// language support.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub struct UnsupportedStepType(pub StepType);
156
157impl fmt::Display for UnsupportedStepType {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        write!(f, "unsupported step type: {:?}", self.0)
160    }
161}
162
163impl std::error::Error for UnsupportedStepType {}
164
165impl TryFrom<StepType> for StepKeyword {
166    type Error = UnsupportedStepType;
167
168    /// Convert a parsed Gherkin [`StepType`] to a [`StepKeyword`].
169    ///
170    /// # Gherkin coupling
171    ///
172    /// The `gherkin` crate (v0.14) defines `StepType` with only `Given`, `When`,
173    /// and `Then` variants. Gherkin syntax also includes `And` and `But`
174    /// keywords, but the parser resolves these to the preceding primary keyword
175    /// before exposing them via `StepType`.
176    ///
177    /// If a future `gherkin` release adds new `StepType` variants (e.g., `And`,
178    /// `But`, or others), the `#[expect(unreachable_patterns)]` guard below will
179    /// trigger a compiler warning, prompting an update to this match arm.
180    fn try_from(ty: StepType) -> Result<Self, Self::Error> {
181        match ty {
182            StepType::Given => Ok(Self::Given),
183            StepType::When => Ok(Self::When),
184            StepType::Then => Ok(Self::Then),
185            // Guard against future StepType variants. If gherkin adds new
186            // variants, this pattern becomes reachable and the `expect`
187            // attribute fires a compiler warning, prompting maintainers to
188            // update this conversion.
189            #[expect(unreachable_patterns, reason = "guard future StepType variants")]
190            other => Err(UnsupportedStepType(other)),
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    //! Unit tests for step keyword parsing and conversion.
198
199    use rstest::rstest;
200
201    use super::*;
202
203    #[rstest]
204    #[case("Given", StepKeyword::Given)]
205    #[case("given", StepKeyword::Given)]
206    #[case(" WhEn ", StepKeyword::When)]
207    #[case("THEN", StepKeyword::Then)]
208    #[case("AND", StepKeyword::And)]
209    #[case(" but ", StepKeyword::But)]
210    fn parses_case_insensitively(#[case] input: &str, #[case] expected: StepKeyword) {
211        let Ok(parsed) = input.parse::<StepKeyword>() else {
212            panic!("test input should parse to a valid keyword: {input}");
213        };
214        assert_eq!(parsed, expected);
215    }
216
217    #[test]
218    fn rejects_invalid_keyword() {
219        let result = "invalid".parse::<StepKeyword>();
220        assert!(result.is_err());
221        let err = result.expect_err("expected parse error for invalid keyword");
222        assert_eq!(err.0, "invalid");
223    }
224
225    #[rstest]
226    #[case(StepType::Given, StepKeyword::Given)]
227    #[case(StepType::When, StepKeyword::When)]
228    #[case(StepType::Then, StepKeyword::Then)]
229    fn maps_step_type(#[case] ty: StepType, #[case] expected: StepKeyword) {
230        let Ok(keyword) = StepKeyword::try_from(ty) else {
231            panic!("test StepType should convert to StepKeyword: {ty:?}");
232        };
233        assert_eq!(keyword, expected);
234    }
235
236    #[test]
237    fn as_str_returns_canonical_name() {
238        assert_eq!(StepKeyword::Given.as_str(), "Given");
239        assert_eq!(StepKeyword::When.as_str(), "When");
240        assert_eq!(StepKeyword::Then.as_str(), "Then");
241        assert_eq!(StepKeyword::And.as_str(), "And");
242        assert_eq!(StepKeyword::But.as_str(), "But");
243    }
244
245    #[test]
246    fn resolve_returns_previous_for_conjunctions() {
247        let mut prev = Some(StepKeyword::When);
248        assert_eq!(StepKeyword::And.resolve(&mut prev), StepKeyword::When);
249        assert_eq!(StepKeyword::But.resolve(&mut prev), StepKeyword::When);
250        // prev unchanged for conjunctions
251        assert_eq!(prev, Some(StepKeyword::When));
252    }
253
254    #[test]
255    fn resolve_updates_previous_for_primary_keywords() {
256        let mut prev = Some(StepKeyword::Given);
257        assert_eq!(StepKeyword::When.resolve(&mut prev), StepKeyword::When);
258        assert_eq!(prev, Some(StepKeyword::When));
259        assert_eq!(StepKeyword::Then.resolve(&mut prev), StepKeyword::Then);
260        assert_eq!(prev, Some(StepKeyword::Then));
261    }
262
263    #[test]
264    fn resolve_defaults_to_given_when_unseeded() {
265        let mut prev = None;
266        assert_eq!(StepKeyword::And.resolve(&mut prev), StepKeyword::Given);
267        assert_eq!(prev, None); // conjunctions don't update prev
268    }
269}