1use jsonpath::Selector;
7use roxmltree::{Document, Node};
8use serde_json::Value;
9use std::collections::HashMap;
10use thiserror::Error;
11
12#[derive(Debug, Error)]
14pub enum ConditionError {
15 #[error("Invalid JSONPath expression: {0}")]
17 InvalidJsonPath(String),
18
19 #[error("Invalid XPath expression: {0}")]
21 InvalidXPath(String),
22
23 #[error("Invalid XML: {0}")]
25 InvalidXml(String),
26
27 #[error("Unsupported condition type: {0}")]
29 UnsupportedCondition(String),
30
31 #[error("Condition evaluation failed: {0}")]
33 EvaluationFailed(String),
34}
35
36#[derive(Debug, Clone)]
38pub struct ConditionContext {
39 pub request_body: Option<Value>,
41 pub response_body: Option<Value>,
43 pub request_xml: Option<String>,
45 pub response_xml: Option<String>,
47 pub headers: HashMap<String, String>,
49 pub query_params: HashMap<String, String>,
51 pub path: String,
53 pub method: String,
55 pub operation_id: Option<String>,
57 pub tags: Vec<String>,
59}
60
61impl Default for ConditionContext {
62 fn default() -> Self {
63 Self::new()
64 }
65}
66
67impl ConditionContext {
68 pub fn new() -> Self {
70 Self {
71 request_body: None,
72 response_body: None,
73 request_xml: None,
74 response_xml: None,
75 headers: HashMap::new(),
76 query_params: HashMap::new(),
77 path: String::new(),
78 method: String::new(),
79 operation_id: None,
80 tags: Vec::new(),
81 }
82 }
83
84 pub fn with_request_body(mut self, body: Value) -> Self {
86 self.request_body = Some(body);
87 self
88 }
89
90 pub fn with_response_body(mut self, body: Value) -> Self {
92 self.response_body = Some(body);
93 self
94 }
95
96 pub fn with_request_xml(mut self, xml: String) -> Self {
98 self.request_xml = Some(xml);
99 self
100 }
101
102 pub fn with_response_xml(mut self, xml: String) -> Self {
104 self.response_xml = Some(xml);
105 self
106 }
107
108 pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
110 self.headers = headers;
111 self
112 }
113
114 pub fn with_query_params(mut self, params: HashMap<String, String>) -> Self {
116 self.query_params = params;
117 self
118 }
119
120 pub fn with_path(mut self, path: String) -> Self {
122 self.path = path;
123 self
124 }
125
126 pub fn with_method(mut self, method: String) -> Self {
128 self.method = method;
129 self
130 }
131
132 pub fn with_operation_id(mut self, operation_id: String) -> Self {
134 self.operation_id = Some(operation_id);
135 self
136 }
137
138 pub fn with_tags(mut self, tags: Vec<String>) -> Self {
140 self.tags = tags;
141 self
142 }
143}
144
145pub fn evaluate_condition(
147 condition: &str,
148 context: &ConditionContext,
149) -> Result<bool, ConditionError> {
150 let condition = condition.trim();
151
152 if condition.is_empty() {
153 return Ok(true); }
155
156 if let Some(and_conditions) = condition.strip_prefix("AND(") {
158 if let Some(inner) = and_conditions.strip_suffix(")") {
159 return evaluate_and_condition(inner, context);
160 }
161 }
162
163 if let Some(or_conditions) = condition.strip_prefix("OR(") {
164 if let Some(inner) = or_conditions.strip_suffix(")") {
165 return evaluate_or_condition(inner, context);
166 }
167 }
168
169 if let Some(not_condition) = condition.strip_prefix("NOT(") {
170 if let Some(inner) = not_condition.strip_suffix(")") {
171 return evaluate_not_condition(inner, context);
172 }
173 }
174
175 if condition.starts_with("$.") || condition.starts_with("$[") {
177 return evaluate_jsonpath(condition, context);
178 }
179
180 if condition.starts_with("/") || condition.starts_with("//") {
182 return evaluate_xpath(condition, context);
183 }
184
185 evaluate_simple_condition(condition, context)
187}
188
189fn evaluate_and_condition(
191 conditions: &str,
192 context: &ConditionContext,
193) -> Result<bool, ConditionError> {
194 let parts: Vec<&str> = conditions.split(',').map(|s| s.trim()).collect();
195
196 for part in parts {
197 if !evaluate_condition(part, context)? {
198 return Ok(false);
199 }
200 }
201
202 Ok(true)
203}
204
205fn evaluate_or_condition(
207 conditions: &str,
208 context: &ConditionContext,
209) -> Result<bool, ConditionError> {
210 let parts: Vec<&str> = conditions.split(',').map(|s| s.trim()).collect();
211
212 for part in parts {
213 if evaluate_condition(part, context)? {
214 return Ok(true);
215 }
216 }
217
218 Ok(false)
219}
220
221fn evaluate_not_condition(
223 condition: &str,
224 context: &ConditionContext,
225) -> Result<bool, ConditionError> {
226 Ok(!evaluate_condition(condition, context)?)
227}
228
229fn evaluate_jsonpath(query: &str, context: &ConditionContext) -> Result<bool, ConditionError> {
231 let (_is_request, json_value) = if query.starts_with("$.request.") {
233 let _query = query.replace("$.request.", "$.");
234 (true, &context.request_body)
235 } else if query.starts_with("$.response.") {
236 let _query = query.replace("$.response.", "$.");
237 (false, &context.response_body)
238 } else {
239 (false, &context.response_body)
241 };
242
243 let Some(json_value) = json_value else {
244 return Ok(false); };
246
247 match Selector::new(query) {
248 Ok(selector) => {
249 let results: Vec<_> = selector.find(json_value).collect();
250 Ok(!results.is_empty())
251 }
252 Err(_) => Err(ConditionError::InvalidJsonPath(query.to_string())),
253 }
254}
255
256fn evaluate_xpath(query: &str, context: &ConditionContext) -> Result<bool, ConditionError> {
258 let (_is_request, xml_content) = if query.starts_with("/request/") {
260 let _query = query.replace("/request/", "/");
261 (true, &context.request_xml)
262 } else if query.starts_with("/response/") {
263 let _query = query.replace("/response/", "/");
264 (false, &context.response_xml)
265 } else {
266 (false, &context.response_xml)
268 };
269
270 let Some(xml_content) = xml_content else {
271 println!("Debug - No XML content available for query: {}", query);
272 return Ok(false); };
274
275 println!("Debug - Evaluating XPath '{}' against XML content: {}", query, xml_content);
276
277 match Document::parse(xml_content) {
278 Ok(doc) => {
279 let root = doc.root_element();
281 println!("Debug - XML root element: {}", root.tag_name().name());
282 let matches = evaluate_xpath_simple(&root, query);
283 println!("Debug - XPath result: {}", matches);
284 Ok(matches)
285 }
286 Err(e) => {
287 println!("Debug - Failed to parse XML: {}", e);
288 Err(ConditionError::InvalidXml(xml_content.clone()))
289 }
290 }
291}
292
293fn evaluate_xpath_simple(node: &Node, xpath: &str) -> bool {
295 if let Some(element_name) = xpath.strip_prefix("//") {
300 println!(
301 "Debug - Checking descendant-or-self for element '{}' on node '{}'",
302 element_name,
303 node.tag_name().name()
304 );
305 if node.tag_name().name() == element_name {
306 println!("Debug - Found match: {} == {}", node.tag_name().name(), element_name);
307 return true;
308 }
309 for child in node.children() {
311 if child.is_element() {
312 println!("Debug - Checking child element: {}", child.tag_name().name());
313 if evaluate_xpath_simple(&child, &format!("//{}", element_name)) {
314 return true;
315 }
316 }
317 }
318 return false; }
320
321 let xpath = xpath.trim_start_matches('/');
322
323 if xpath.is_empty() {
324 return true;
325 }
326
327 if let Some((element_part, attr_part)) = xpath.split_once('[') {
329 if let Some(attr_query) = attr_part.strip_suffix(']') {
330 if let Some((attr_name, attr_value)) = attr_query.split_once("='") {
331 if let Some(expected_value) = attr_value.strip_suffix('\'') {
332 if let Some(attr_val) = attr_name.strip_prefix('@') {
333 if node.tag_name().name() == element_part {
334 if let Some(attr) = node.attribute(attr_val) {
335 return attr == expected_value;
336 }
337 }
338 }
339 }
340 }
341 }
342 return false;
343 }
344
345 if let Some((element_name, rest)) = xpath.split_once('/') {
347 if node.tag_name().name() == element_name {
348 if rest.is_empty() {
349 return true;
350 }
351 for child in node.children() {
353 if child.is_element() && evaluate_xpath_simple(&child, rest) {
354 return true;
355 }
356 }
357 }
358 } else if node.tag_name().name() == xpath {
359 return true;
360 }
361
362 if let Some(text_query) = xpath.strip_suffix("/text()") {
364 if node.tag_name().name() == text_query {
365 return node.text().is_some_and(|t| !t.trim().is_empty());
366 }
367 }
368
369 false
370}
371
372fn evaluate_simple_condition(
374 condition: &str,
375 context: &ConditionContext,
376) -> Result<bool, ConditionError> {
377 if let Some(header_condition) = condition.strip_prefix("header[") {
379 if let Some((header_name, expected_value)) = header_condition.split_once("]=") {
380 let expected_value = expected_value.trim();
381 if let Some(actual_value) = context.headers.get(header_name) {
382 return Ok(actual_value == expected_value);
383 }
384 return Ok(false);
385 }
386 }
387
388 if let Some(query_condition) = condition.strip_prefix("query[") {
390 if let Some((param_name, expected_value)) = query_condition.split_once("]=") {
391 let expected_value = expected_value.trim();
392 if let Some(actual_value) = context.query_params.get(param_name) {
393 return Ok(actual_value == expected_value);
394 }
395 return Ok(false);
396 }
397 }
398
399 if let Some(method_condition) = condition.strip_prefix("method=") {
401 return Ok(context.method == method_condition);
402 }
403
404 if let Some(path_condition) = condition.strip_prefix("path=") {
406 return Ok(context.path == path_condition);
407 }
408
409 if let Some(tag_condition) = condition.strip_prefix("has_tag[") {
411 if let Some(tag) = tag_condition.strip_suffix("]") {
412 return Ok(context.tags.contains(&tag.to_string()));
413 }
414 }
415
416 if let Some(op_condition) = condition.strip_prefix("operation=") {
418 if let Some(operation_id) = &context.operation_id {
419 return Ok(operation_id == op_condition);
420 }
421 return Ok(false);
422 }
423
424 Err(ConditionError::UnsupportedCondition(condition.to_string()))
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430 use serde_json::json;
431
432 #[test]
433 fn test_jsonpath_condition() {
434 let context = ConditionContext::new().with_response_body(json!({
435 "user": {
436 "name": "John",
437 "role": "admin"
438 },
439 "items": [1, 2, 3]
440 }));
441
442 assert!(evaluate_condition("$.user", &context).unwrap());
444
445 assert!(evaluate_condition("$.user.role", &context).unwrap());
447
448 assert!(evaluate_condition("$.items[0]", &context).unwrap());
450
451 assert!(!evaluate_condition("$.nonexistent", &context).unwrap());
453 }
454
455 #[test]
456 fn test_simple_conditions() {
457 let mut headers = HashMap::new();
458 headers.insert("authorization".to_string(), "Bearer token123".to_string());
459
460 let mut query_params = HashMap::new();
461 query_params.insert("limit".to_string(), "10".to_string());
462
463 let context = ConditionContext::new()
464 .with_headers(headers)
465 .with_query_params(query_params)
466 .with_method("POST".to_string())
467 .with_path("/api/users".to_string());
468
469 assert!(evaluate_condition("header[authorization]=Bearer token123", &context).unwrap());
471 assert!(!evaluate_condition("header[authorization]=Bearer wrong", &context).unwrap());
472
473 assert!(evaluate_condition("query[limit]=10", &context).unwrap());
475 assert!(!evaluate_condition("query[limit]=20", &context).unwrap());
476
477 assert!(evaluate_condition("method=POST", &context).unwrap());
479 assert!(!evaluate_condition("method=GET", &context).unwrap());
480
481 assert!(evaluate_condition("path=/api/users", &context).unwrap());
483 assert!(!evaluate_condition("path=/api/posts", &context).unwrap());
484 }
485
486 #[test]
487 fn test_logical_conditions() {
488 let context = ConditionContext::new()
489 .with_method("POST".to_string())
490 .with_path("/api/users".to_string());
491
492 assert!(evaluate_condition("AND(method=POST,path=/api/users)", &context).unwrap());
494 assert!(!evaluate_condition("AND(method=GET,path=/api/users)", &context).unwrap());
495
496 assert!(evaluate_condition("OR(method=POST,path=/api/posts)", &context).unwrap());
498 assert!(!evaluate_condition("OR(method=GET,path=/api/posts)", &context).unwrap());
499
500 assert!(!evaluate_condition("NOT(method=POST)", &context).unwrap());
502 assert!(evaluate_condition("NOT(method=GET)", &context).unwrap());
503 }
504
505 #[test]
506 fn test_xpath_condition() {
507 let xml_content = r#"
508 <user id="123">
509 <name>John Doe</name>
510 <role>admin</role>
511 <preferences>
512 <theme>dark</theme>
513 <notifications>true</notifications>
514 </preferences>
515 </user>
516 "#;
517
518 let context = ConditionContext::new().with_response_xml(xml_content.to_string());
519
520 assert!(evaluate_condition("/user", &context).unwrap());
522
523 assert!(evaluate_condition("/user/name", &context).unwrap());
525
526 assert!(evaluate_condition("/user[@id='123']", &context).unwrap());
528 assert!(!evaluate_condition("/user[@id='456']", &context).unwrap());
529
530 assert!(evaluate_condition("/user/name/text()", &context).unwrap());
532
533 assert!(evaluate_condition("//theme", &context).unwrap());
535
536 assert!(!evaluate_condition("/nonexistent", &context).unwrap());
538 }
539}