pipeline-service 2.1.0

Pipeline execution service for roxid
Documentation
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
// Testing Framework Module
// Provides pipeline test definitions, execution, assertions, and reporting

pub mod assertions;
pub mod parser;
pub mod reporter;
pub mod runner;

// Re-export key types
pub use assertions::{Assertion, AssertionResult};
pub use parser::TestFileParser;
pub use reporter::{ReportFormat, TestReporter};
pub use runner::{TestResult, TestRunner, TestSuiteResult};

use crate::parser::models::Value;

use std::collections::HashMap;
use std::path::PathBuf;

use serde::de::{self, MapAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};

// =============================================================================
// Test Definition Models
// =============================================================================

/// A complete test suite loaded from a roxid-test.yml file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestSuite {
    /// Optional suite name
    #[serde(default)]
    pub name: Option<String>,
    /// Test definitions
    pub tests: Vec<PipelineTest>,
    /// Default variables applied to all tests
    #[serde(default)]
    pub defaults: Option<TestDefaults>,
}

/// Default values applied to all tests in a suite
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestDefaults {
    /// Default variables
    #[serde(default)]
    pub variables: HashMap<String, String>,
    /// Default parameters
    #[serde(default)]
    pub parameters: HashMap<String, serde_yaml::Value>,
    /// Default working directory
    #[serde(default)]
    pub working_dir: Option<String>,
}

/// A single pipeline test definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineTest {
    /// Test name (used in reporting)
    pub name: String,
    /// Path to the pipeline YAML file (relative to test file)
    pub pipeline: PathBuf,
    /// Variables to set for this test run
    #[serde(default)]
    pub variables: HashMap<String, String>,
    /// Parameters to pass for this test run
    #[serde(default)]
    pub parameters: HashMap<String, serde_yaml::Value>,
    /// Working directory for execution
    #[serde(default)]
    pub working_dir: Option<String>,
    /// Assertions to evaluate after execution
    #[serde(default)]
    pub assertions: Vec<AssertionDef>,
}

/// An assertion definition as parsed from YAML
///
/// Each variant maps to a YAML key in the assertions list.
/// This is the serializable form; it gets converted to `Assertion`
/// for evaluation.
///
/// Supports YAML formats:
/// - Bare string: `pipeline_succeeded`
/// - Key-value: `step_succeeded: Build`
/// - Key-struct: `step_output_contains: { step: Build, pattern: "..." }`
#[derive(Debug, Clone, Serialize)]
pub enum AssertionDef {
    /// Assert a step succeeded
    StepSucceeded(String),

    /// Assert a step failed
    StepFailed(String),

    /// Assert a step was skipped
    StepSkipped(String),

    /// Assert a job succeeded
    JobSucceeded(String),

    /// Assert a job failed
    JobFailed(String),

    /// Assert a job was skipped
    JobSkipped(String),

    /// Assert a stage succeeded
    StageSucceeded(String),

    /// Assert a stage failed
    StageFailed(String),

    /// Assert a stage was skipped
    StageSkipped(String),

    /// Assert step output equals a value
    StepOutputEquals(StepOutputAssertion),

    /// Assert step output contains a pattern
    StepOutputContains(StepOutputPatternAssertion),

    /// Assert a step ran before another step
    StepRanBefore(OrderAssertion),

    /// Assert steps ran in parallel (within the same stage/job level)
    StepsRanInParallel(ParallelAssertion),

    /// Assert a variable has a specific value after execution
    VariableEquals(VariableAssertion),

    /// Assert a variable contains a pattern
    VariableContains(VariablePatternAssertion),

    /// Assert the pipeline succeeded overall
    PipelineSucceeded,

    /// Assert the pipeline failed overall
    PipelineFailed,
}

impl<'de> Deserialize<'de> for AssertionDef {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct AssertionDefVisitor;

        impl<'de> Visitor<'de> for AssertionDefVisitor {
            type Value = AssertionDef;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str(
                    "a string like 'pipeline_succeeded' or a mapping like 'step_succeeded: Build'",
                )
            }

            // Handle bare strings: `- pipeline_succeeded`
            fn visit_str<E>(self, value: &str) -> Result<AssertionDef, E>
            where
                E: de::Error,
            {
                match value {
                    "pipeline_succeeded" => Ok(AssertionDef::PipelineSucceeded),
                    "pipeline_failed" => Ok(AssertionDef::PipelineFailed),
                    _ => Err(de::Error::unknown_variant(
                        value,
                        &["pipeline_succeeded", "pipeline_failed"],
                    )),
                }
            }

            // Handle mappings: `- step_succeeded: Build` or `- step_output_contains: { ... }`
            fn visit_map<M>(self, mut map: M) -> Result<AssertionDef, M::Error>
            where
                M: MapAccess<'de>,
            {
                let key: String = map
                    .next_key()?
                    .ok_or_else(|| de::Error::custom("expected assertion key"))?;

                let result = match key.as_str() {
                    "step_succeeded" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StepSucceeded(val))
                    }
                    "step_failed" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StepFailed(val))
                    }
                    "step_skipped" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StepSkipped(val))
                    }
                    "job_succeeded" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::JobSucceeded(val))
                    }
                    "job_failed" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::JobFailed(val))
                    }
                    "job_skipped" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::JobSkipped(val))
                    }
                    "stage_succeeded" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StageSucceeded(val))
                    }
                    "stage_failed" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StageFailed(val))
                    }
                    "stage_skipped" => {
                        let val: String = map.next_value()?;
                        Ok(AssertionDef::StageSkipped(val))
                    }
                    "step_output_equals" => {
                        let val: StepOutputAssertion = map.next_value()?;
                        Ok(AssertionDef::StepOutputEquals(val))
                    }
                    "step_output_contains" => {
                        let val: StepOutputPatternAssertion = map.next_value()?;
                        Ok(AssertionDef::StepOutputContains(val))
                    }
                    "step_ran_before" => {
                        let val: OrderAssertion = map.next_value()?;
                        Ok(AssertionDef::StepRanBefore(val))
                    }
                    "steps_ran_in_parallel" => {
                        let val: ParallelAssertion = map.next_value()?;
                        Ok(AssertionDef::StepsRanInParallel(val))
                    }
                    "variable_equals" => {
                        let val: VariableAssertion = map.next_value()?;
                        Ok(AssertionDef::VariableEquals(val))
                    }
                    "variable_contains" => {
                        let val: VariablePatternAssertion = map.next_value()?;
                        Ok(AssertionDef::VariableContains(val))
                    }
                    "pipeline_succeeded" => {
                        // Allow `pipeline_succeeded:` with null/empty value in mapping form
                        let _: serde_yaml::Value = map.next_value()?;
                        Ok(AssertionDef::PipelineSucceeded)
                    }
                    "pipeline_failed" => {
                        let _: serde_yaml::Value = map.next_value()?;
                        Ok(AssertionDef::PipelineFailed)
                    }
                    _ => Err(de::Error::unknown_field(
                        &key,
                        &[
                            "step_succeeded",
                            "step_failed",
                            "step_skipped",
                            "job_succeeded",
                            "job_failed",
                            "job_skipped",
                            "stage_succeeded",
                            "stage_failed",
                            "stage_skipped",
                            "step_output_equals",
                            "step_output_contains",
                            "step_ran_before",
                            "steps_ran_in_parallel",
                            "variable_equals",
                            "variable_contains",
                            "pipeline_succeeded",
                            "pipeline_failed",
                        ],
                    )),
                };

                result
            }
        }

        deserializer.deserialize_any(AssertionDefVisitor)
    }
}

/// Assertion for step output equality
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepOutputAssertion {
    /// Step name (the `name:` field of the step)
    pub step: String,
    /// Output variable name
    pub output: String,
    /// Expected value
    pub expected: serde_yaml::Value,
}

/// Assertion for step output pattern matching
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepOutputPatternAssertion {
    /// Step name
    pub step: String,
    /// Substring or pattern to search for in stdout
    pub pattern: String,
    /// Optional: which output to check ("stdout", "stderr", or specific output variable)
    #[serde(default)]
    pub output: Option<String>,
}

/// Assertion for execution ordering
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderAssertion {
    /// The step that should run first
    pub step: String,
    /// The step that should run after
    pub before: String,
}

/// Assertion for parallel execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParallelAssertion {
    /// Steps that should have run in parallel
    pub steps: Vec<String>,
}

/// Assertion for variable values
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariableAssertion {
    /// Variable name
    pub name: String,
    /// Expected value
    pub expected: serde_yaml::Value,
}

/// Assertion for variable pattern matching
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariablePatternAssertion {
    /// Variable name
    pub name: String,
    /// Pattern to match
    pub pattern: String,
}

// =============================================================================
// Conversion helpers
// =============================================================================

impl AssertionDef {
    /// Convert this YAML assertion definition into an evaluable `Assertion`
    pub fn to_assertion(&self) -> Assertion {
        match self {
            AssertionDef::StepSucceeded(name) => Assertion::StepSucceeded { step: name.clone() },
            AssertionDef::StepFailed(name) => Assertion::StepFailed { step: name.clone() },
            AssertionDef::StepSkipped(name) => Assertion::StepSkipped { step: name.clone() },
            AssertionDef::JobSucceeded(name) => Assertion::JobSucceeded { job: name.clone() },
            AssertionDef::JobFailed(name) => Assertion::JobFailed { job: name.clone() },
            AssertionDef::JobSkipped(name) => Assertion::JobSkipped { job: name.clone() },
            AssertionDef::StageSucceeded(name) => Assertion::StageSucceeded {
                stage: name.clone(),
            },
            AssertionDef::StageFailed(name) => Assertion::StageFailed {
                stage: name.clone(),
            },
            AssertionDef::StageSkipped(name) => Assertion::StageSkipped {
                stage: name.clone(),
            },
            AssertionDef::StepOutputEquals(a) => Assertion::StepOutputEquals {
                step: a.step.clone(),
                output: a.output.clone(),
                expected: yaml_to_value(&a.expected),
            },
            AssertionDef::StepOutputContains(a) => Assertion::StepOutputContains {
                step: a.step.clone(),
                pattern: a.pattern.clone(),
                output: a.output.clone(),
            },
            AssertionDef::StepRanBefore(a) => Assertion::StepRanBefore {
                step: a.step.clone(),
                before: a.before.clone(),
            },
            AssertionDef::StepsRanInParallel(a) => Assertion::StepsRanInParallel {
                steps: a.steps.clone(),
            },
            AssertionDef::VariableEquals(a) => Assertion::VariableEquals {
                name: a.name.clone(),
                expected: yaml_to_value(&a.expected),
            },
            AssertionDef::VariableContains(a) => Assertion::VariableContains {
                name: a.name.clone(),
                pattern: a.pattern.clone(),
            },
            AssertionDef::PipelineSucceeded => Assertion::PipelineSucceeded,
            AssertionDef::PipelineFailed => Assertion::PipelineFailed,
        }
    }
}

/// Convert a serde_yaml::Value to our internal Value type
fn yaml_to_value(v: &serde_yaml::Value) -> Value {
    match v {
        serde_yaml::Value::Null => Value::Null,
        serde_yaml::Value::Bool(b) => Value::Bool(*b),
        serde_yaml::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::Number(i as f64)
            } else if let Some(f) = n.as_f64() {
                Value::Number(f)
            } else {
                Value::Null
            }
        }
        serde_yaml::Value::String(s) => Value::String(s.clone()),
        serde_yaml::Value::Sequence(seq) => Value::Array(seq.iter().map(yaml_to_value).collect()),
        serde_yaml::Value::Mapping(map) => {
            let mut obj = HashMap::new();
            for (k, v) in map {
                if let serde_yaml::Value::String(key) = k {
                    obj.insert(key.clone(), yaml_to_value(v));
                }
            }
            Value::Object(obj)
        }
        serde_yaml::Value::Tagged(tagged) => yaml_to_value(&tagged.value),
    }
}

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

    #[test]
    fn test_assertion_def_to_assertion_step_succeeded() {
        let def = AssertionDef::StepSucceeded("Build".to_string());
        let assertion = def.to_assertion();
        assert!(matches!(
            assertion,
            Assertion::StepSucceeded { step } if step == "Build"
        ));
    }

    #[test]
    fn test_assertion_def_to_assertion_variable_equals() {
        let def = AssertionDef::VariableEquals(VariableAssertion {
            name: "BUILD_CONFIG".to_string(),
            expected: serde_yaml::Value::String("Release".to_string()),
        });
        let assertion = def.to_assertion();
        assert!(matches!(
            assertion,
            Assertion::VariableEquals { name, expected }
                if name == "BUILD_CONFIG" && expected == Value::String("Release".to_string())
        ));
    }

    #[test]
    fn test_yaml_to_value_primitives() {
        assert_eq!(yaml_to_value(&serde_yaml::Value::Null), Value::Null);
        assert_eq!(
            yaml_to_value(&serde_yaml::Value::Bool(true)),
            Value::Bool(true)
        );
        assert_eq!(
            yaml_to_value(&serde_yaml::Value::String("hello".to_string())),
            Value::String("hello".to_string())
        );
    }

    #[test]
    fn test_pipeline_test_deserialize() {
        let yaml = r#"
name: "Build test"
pipeline: azure-pipelines.yml
variables:
  BUILD_CONFIG: Release
assertions:
  - step_succeeded: Build
  - pipeline_succeeded
"#;
        let test: PipelineTest = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(test.name, "Build test");
        assert_eq!(test.pipeline, PathBuf::from("azure-pipelines.yml"));
        assert_eq!(test.variables.get("BUILD_CONFIG").unwrap(), "Release");
        assert_eq!(test.assertions.len(), 2);
    }

    #[test]
    fn test_test_suite_deserialize() {
        let yaml = r#"
tests:
  - name: "Build stage runs correctly"
    pipeline: azure-pipelines.yml
    variables:
      BUILD_CONFIG: Release
    assertions:
      - step_succeeded: Build
      - step_output_contains:
          step: Build
          pattern: "Build succeeded"
      - step_ran_before:
          step: Test
          before: Deploy

  - name: "Deploy is skipped on PR"
    pipeline: azure-pipelines.yml
    variables:
      BUILD_REASON: PullRequest
    assertions:
      - step_skipped: Deploy
"#;
        let suite: TestSuite = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(suite.tests.len(), 2);
        assert_eq!(suite.tests[0].name, "Build stage runs correctly");
        assert_eq!(suite.tests[0].assertions.len(), 3);
        assert_eq!(suite.tests[1].name, "Deploy is skipped on PR");
        assert_eq!(suite.tests[1].assertions.len(), 1);
    }
}