apif_execution/
assertion_handler.rs1use apif_assert::{AssertionEngine, AssertionResult};
2use apif_plugins::core::PluginManager;
3use serde_json::Value;
4use std::collections::HashMap;
5use std::sync::{Arc, LazyLock};
6
7static PLUGIN_REGISTRY: LazyLock<Arc<dyn apif_assert::registry::PluginRegistry>> =
8 LazyLock::new(|| Arc::new(PluginManager::new()));
9
10#[derive(Default)]
11pub struct AssertionHandler {
12 engine: AssertionEngine,
13}
14
15impl AssertionHandler {
16 pub fn new() -> Self {
17 Self {
18 engine: AssertionEngine::with_registry(PLUGIN_REGISTRY.clone()),
19 }
20 }
21
22 pub fn run_assertions(
23 &self,
24 _assertions: &[String],
25 _response: &Value,
26 _headers: Option<&HashMap<String, String>>,
27 _trailers: Option<&HashMap<String, String>>,
28 ) -> Vec<String> {
29 let mut failures = Vec::new();
30 for expr in _assertions {
31 match self.engine.evaluate(expr, _response, _headers, _trailers) {
32 Ok(AssertionResult::Pass) => {}
33 Ok(AssertionResult::Fail { message, .. }) => {
34 failures.push(format!("{}: {}", expr, message))
35 }
36 Ok(AssertionResult::Error(e)) => failures.push(format!("{}: {}", expr, e)),
37 Err(e) => failures.push(format!("{}: {}", expr, e)),
38 }
39 }
40 failures
41 }
42
43 pub fn evaluate_single_assertion(
44 &self,
45 expression: &str,
46 response: &Value,
47 headers: Option<&HashMap<String, String>>,
48 trailers: Option<&HashMap<String, String>>,
49 ) -> AssertionResult {
50 self.engine
51 .evaluate(expression, response, headers, trailers)
52 .unwrap_or(AssertionResult::Error("evaluation error".into()))
53 }
54
55 pub fn append_single_failure(
56 failures: &mut Vec<String>,
57 result: &AssertionResult,
58 expression: &str,
59 ) {
60 match result {
61 AssertionResult::Fail { message, .. } => {
62 failures.push(format!("{}: {}", expression, message))
63 }
64 AssertionResult::Error(msg) => failures.push(format!("{}: {}", expression, msg)),
65 _ => {}
66 }
67 }
68}