Skip to main content

rstest_bdd/execution/
mod.rs

1//! Runtime execution policy and helpers for scenario step execution.
2//!
3//! This module provides abstractions and utilities that were previously embedded
4//! in the codegen layer. By moving them here, we achieve clearer separation of
5//! concerns: the macro layer generates minimal glue code that delegates to these
6//! runtime functions.
7//!
8//! # Key Components
9//!
10//! - [`RuntimeMode`]: Canonical definition of execution modes (sync, async variants), re-exported
11//!   from `rstest_bdd_policy`.
12//! - [`TestAttributeHint`]: Canonical definition for test attribute generation hints, re-exported
13//!   from `rstest_bdd_policy`.
14//! - [`StepExecutionRequest`]: Groups step data and diagnostic context for execution.
15//! - Helper functions for step execution, fixture validation, and skip encoding. `RuntimeMode` and
16//!   `TestAttributeHint` are re-exported from `rstest_bdd_policy`, the shared source of truth used
17//!   by the macro crate. Runtime and macro tests guard that single-source policy boundary.
18
19mod error;
20/// Fixture validation helpers for step execution.
21mod fixtures;
22
23use std::{any::Any, sync::Arc};
24
25pub use error::{ExecutionError, MissingFixtureDiagnostic, MissingFixturesDetails};
26use fixtures::validate_required_fixtures;
27
28use crate::{
29    Step,
30    StepExecution,
31    StepExecutionMode,
32    StepKeyword,
33    StepText,
34    context::StepContext,
35    find_step_with_metadata,
36};
37
38/// Prefix character for encoded skip messages with no message content.
39pub(crate) const SKIP_NONE_PREFIX: char = '\u{0}';
40
41/// Prefix character for encoded skip messages with message content.
42pub(crate) const SKIP_SOME_PREFIX: char = '\u{1}';
43
44/// Runtime mode for scenario test execution (canonical definition).
45///
46/// This type is re-exported from `rstest_bdd_policy` to keep the public API in
47/// `rstest_bdd::execution` stable for downstream users.
48pub use rstest_bdd_policy::RuntimeMode;
49/// Hint for which test attributes the macro layer should generate
50/// (canonical definition).
51///
52/// This type is re-exported from `rstest_bdd_policy` to keep the public API in
53/// `rstest_bdd::execution` stable for downstream users.
54pub use rstest_bdd_policy::TestAttributeHint;
55
56/// Resolve the registered step described by an execution request.
57fn resolve_step_for_request(
58    request: &StepExecutionRequest<'_>,
59) -> Result<&'static Step, ExecutionError> {
60    find_step_with_metadata(request.keyword, StepText::from(request.text)).ok_or_else(|| {
61        ExecutionError::StepNotFound {
62            index: request.index,
63            keyword: request.keyword,
64            text: request.text.to_owned(),
65            feature_path: request.feature_path.to_owned(),
66            scenario_name: request.scenario_name.to_owned(),
67        }
68    })
69}
70
71/// Convert a step result into the executor's structured outcome.
72fn handle_step_result(
73    request: &StepExecutionRequest<'_>,
74    result: Result<StepExecution, crate::StepError>,
75) -> Result<Option<Box<dyn Any>>, ExecutionError> {
76    match result {
77        Ok(StepExecution::Skipped { message }) => Err(ExecutionError::Skip { message }),
78        Ok(StepExecution::Continue { value }) => Ok(value),
79        Err(err) => Err(ExecutionError::HandlerFailed {
80            index: request.index,
81            keyword: request.keyword,
82            text: request.text.to_owned(),
83            error: Arc::new(err),
84            feature_path: request.feature_path.to_owned(),
85            scenario_name: request.scenario_name.to_owned(),
86        }),
87    }
88}
89
90/// Encode a skip message for propagation through the executor loop.
91///
92/// The encoding uses prefix characters to distinguish between skip requests
93/// with and without messages, allowing the skip signal to be transmitted
94/// through `Result<_, String>` return types.
95///
96/// # Deprecation
97///
98/// This function is deprecated in favour of using [`ExecutionError::Skip`]
99/// directly. The new error type provides structured skip handling without
100/// string encoding.
101///
102/// # Arguments
103///
104/// * `message` - Optional skip message to encode
105///
106/// # Returns
107///
108/// An encoded string starting with `SKIP_NONE_PREFIX` (no message) or
109/// `SKIP_SOME_PREFIX` followed by the message content.
110///
111/// # Examples
112///
113/// ```
114/// use rstest_bdd::execution::{decode_skip_message, encode_skip_message};
115///
116/// // Round-trip with no message
117/// let encoded = encode_skip_message(None);
118/// assert_eq!(decode_skip_message(encoded), None);
119///
120/// // Round-trip with message
121/// let encoded = encode_skip_message(Some("reason".to_string()));
122/// assert_eq!(decode_skip_message(encoded), Some("reason".to_string()));
123/// ```
124#[deprecated(
125    since = "0.8.0",
126    note = "Use ExecutionError::Skip variant instead of string encoding"
127)]
128#[must_use]
129pub fn encode_skip_message(message: Option<String>) -> String {
130    message.map_or_else(
131        || SKIP_NONE_PREFIX.to_string(),
132        |msg| {
133            let mut encoded = String::with_capacity(1 + msg.len());
134            encoded.push(SKIP_SOME_PREFIX);
135            encoded.push_str(&msg);
136            encoded
137        },
138    )
139}
140
141/// Decode an encoded skip message.
142///
143/// Reverses the encoding performed by [`encode_skip_message`], extracting
144/// the original message content from the prefixed format.
145///
146/// # Deprecation
147///
148/// This function is deprecated in favour of using [`ExecutionError::Skip`]
149/// directly. The new error type provides structured skip handling without
150/// string encoding. Use [`ExecutionError::skip_message`] to extract skip
151/// messages from the new error type.
152///
153/// # Arguments
154///
155/// * `encoded` - The encoded skip message string
156///
157/// # Returns
158///
159/// `None` if the message was encoded without content, `Some(message)` otherwise.
160/// Malformed input is returned as-is wrapped in `Some` for diagnostic purposes.
161///
162/// # Examples
163///
164/// ```
165/// use rstest_bdd::execution::{decode_skip_message, encode_skip_message};
166///
167/// let encoded = encode_skip_message(Some("test".to_string()));
168/// assert_eq!(decode_skip_message(encoded), Some("test".to_string()));
169/// ```
170#[deprecated(
171    since = "0.8.0",
172    note = "Use ExecutionError::skip_message() instead of string decoding"
173)]
174#[must_use]
175pub fn decode_skip_message(encoded: String) -> Option<String> {
176    match encoded.chars().next() {
177        Some(c) if c == SKIP_NONE_PREFIX => None,
178        Some(c) if c == SKIP_SOME_PREFIX => {
179            // Safe: prefix_len is the byte length of the first char we just matched
180            let prefix_len = c.len_utf8();
181            Some(encoded.get(prefix_len..)?.to_owned())
182        }
183        // Defensive fallback: preserve unexpected or malformed input rather than
184        // panicking. This handles edge cases such as:
185        // - Empty strings (no prefix character present)
186        // - Future format changes where the prefix characters evolve
187        // - Corrupted messages from unexpected runtime conditions
188        // Returning the original input wrapped in `Some` allows downstream code
189        // to inspect and diagnose the unexpected format.
190        _ => Some(encoded),
191    }
192}
193
194/// Groups step identification, data, and diagnostic context for execution.
195///
196/// This struct bundles all the information needed to execute a single scenario step,
197/// reducing the parameter count of [`execute_step`] and making call sites more readable.
198///
199/// # Fields
200///
201/// * `index` - Zero-based step index for error messages
202/// * `keyword` - The step keyword (Given, When, Then, etc.)
203/// * `text` - The step text to match against patterns
204/// * `docstring` - Optional docstring argument
205/// * `table` - Optional data table argument
206/// * `feature_path` - Path to the feature file for diagnostics
207/// * `scenario_name` - Name of the scenario for diagnostics
208#[derive(Debug)]
209pub struct StepExecutionRequest<'a> {
210    /// Zero-based step index for error messages.
211    pub index: usize,
212    /// The step keyword (Given, When, Then, etc.).
213    pub keyword: StepKeyword,
214    /// The step text to match against patterns.
215    pub text: &'a str,
216    /// Optional docstring argument.
217    pub docstring: Option<&'a str>,
218    /// Optional data table argument.
219    pub table: Option<&'a [&'a [&'a str]]>,
220    /// Path to the feature file for diagnostics.
221    pub feature_path: &'a str,
222    /// Name of the scenario for diagnostics.
223    pub scenario_name: &'a str,
224}
225
226/// Execute a single step with validation and error handling.
227///
228/// This function encapsulates the core step execution logic:
229/// 1. Look up the step in the registry
230/// 2. Validate required fixtures are available
231/// 3. Execute the step handler
232/// 4. Handle the result (success, skip, or error)
233///
234/// # Arguments
235///
236/// * `request` - The step execution request containing all step data and context
237/// * `ctx` - Mutable reference to the scenario context
238///
239/// # Returns
240///
241/// * `Ok(Some(value))` - Step succeeded and returned a value
242/// * `Ok(None)` - Step succeeded without returning a value
243/// * `Err(ExecutionError::Skip { .. })` - Step requested to be skipped
244/// * `Err(ExecutionError::StepNotFound { .. })` - Step pattern not in registry
245/// * `Err(ExecutionError::MissingFixtures(..))` - Required fixtures missing
246/// * `Err(ExecutionError::HandlerFailed { .. })` - Step handler returned error
247///
248/// # Errors
249///
250/// Returns [`ExecutionError`] for all failure cases:
251///
252/// - [`ExecutionError::Skip`]: The step requested skipping (control flow signal, not an error). Use
253///   [`ExecutionError::is_skip`] to detect this case.
254/// - [`ExecutionError::StepNotFound`]: No step matching the keyword and text was found in the
255///   registry.
256/// - [`ExecutionError::MissingFixtures`]: The step requires fixtures that are not available in the
257///   context.
258/// - [`ExecutionError::HandlerFailed`]: The step handler function returned an error during
259///   execution.
260///
261/// # Examples
262///
263/// ```
264/// use rstest_bdd::{
265///     StepContext,
266///     StepKeyword,
267///     execution::{ExecutionError, StepExecutionRequest, execute_step},
268/// };
269///
270/// let request = StepExecutionRequest {
271///     index: 0,
272///     keyword: StepKeyword::Given,
273///     text: "undefined step",
274///     docstring: None,
275///     table: None,
276///     feature_path: "feature.feature",
277///     scenario_name: "Scenario",
278/// };
279/// let mut ctx = StepContext::default();
280///
281/// let error = match execute_step(&request, &mut ctx) {
282///     Err(error) => error,
283///     Ok(_) => panic!("expected missing step"),
284/// };
285/// assert!(matches!(error, ExecutionError::StepNotFound { .. }));
286/// ```
287pub fn execute_step(
288    request: &StepExecutionRequest<'_>,
289    ctx: &mut StepContext<'_>,
290) -> Result<Option<Box<dyn Any>>, ExecutionError> {
291    let step = resolve_step_for_request(request)?;
292
293    validate_required_fixtures(step, ctx, request)?;
294
295    handle_step_result(
296        request,
297        (step.run)(ctx, request.text, request.docstring, request.table),
298    )
299}
300
301/// Execute a single step via the async handler with validation and error handling.
302///
303/// This mirrors [`execute_step`] but drives execution through the registered
304/// async handler (`Step::run_async`) and awaits the returned future. This
305/// enables true `async fn` step bodies under async scenario runtimes while
306/// preserving the same fixture validation and error reporting behaviour.
307///
308/// # Errors
309///
310/// Returns [`ExecutionError`] for all failure cases, mirroring [`execute_step`].
311///
312/// # Examples
313///
314/// ```rust,no_run
315/// use rstest_bdd::{
316///     StepContext,
317///     StepKeyword,
318///     execution::{ExecutionError, StepExecutionRequest, execute_step_async},
319/// };
320///
321/// let request = StepExecutionRequest {
322///     index: 0,
323///     keyword: StepKeyword::Given,
324///     text: "undefined step",
325///     docstring: None,
326///     table: None,
327///     feature_path: "feature.feature",
328///     scenario_name: "Scenario",
329/// };
330/// let mut ctx = StepContext::default();
331///
332/// let runtime = tokio::runtime::Builder::new_current_thread()
333///     .enable_all()
334///     .build()
335///     .expect("tokio runtime builds");
336/// let error = runtime
337///     .block_on(async { execute_step_async(&request, &mut ctx).await })
338///     .unwrap_err();
339/// assert!(matches!(error, ExecutionError::StepNotFound { .. }));
340/// ```
341pub async fn execute_step_async(
342    request: &StepExecutionRequest<'_>,
343    ctx: &mut StepContext<'_>,
344) -> Result<Option<Box<dyn Any>>, ExecutionError> {
345    let step = resolve_step_for_request(request)?;
346
347    validate_required_fixtures(step, ctx, request)?;
348
349    let result = match step.execution_mode {
350        StepExecutionMode::Async => {
351            (step.run_async)(ctx, request.text, request.docstring, request.table).await
352        }
353        StepExecutionMode::Sync | StepExecutionMode::Both => {
354            (step.run)(ctx, request.text, request.docstring, request.table)
355        }
356    };
357
358    handle_step_result(request, result)
359}
360
361#[cfg(test)]
362mod tests;