choreo 0.13.0

DSL for BDD type testing.
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
use crate::parser::ast::{Action, Condition, Value};
use crate::parser::helpers::{substitute_string, substitute_variables_in_action};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::fmt;
use std::fmt::{Debug, Display};
use ureq::http::{Response, StatusCode};
use ureq::{Agent, Body};

#[derive(Debug)]
enum CompatResult {
    Success(Response<Body>),
    ClientError(Response<Body>),
    ServerError(Response<Body>),
    TransportError(ureq::Error),
}

impl Display for CompatResult {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CompatResult::Success(response) => {
                write!(
                    f,
                    "HTTP request succeeded with status {}",
                    response.status()
                )
            }
            CompatResult::ClientError(response) => {
                write!(f, "HTTP client error: {}", response.status())
            }
            CompatResult::ServerError(response) => {
                write!(f, "HTTP server error: {}", response.status())
            }
            CompatResult::TransportError(error) => {
                write!(f, "HTTP transport error: {}", error)
            }
        }
    }
}

/// State of the last web request made.
#[derive(Debug, Clone, Default)]
pub struct LastResponse {
    pub status: StatusCode,
    pub body: String,
    pub message: Option<String>,
    pub response_time_ms: u128,
}

/// The backend responsible for handling web-based actions and conditions.
#[derive(Debug)]
pub struct WebBackend {
    agent: Agent,
    headers: HashMap<String, String>,
    pub last_response: Option<LastResponse>,
}

impl WebBackend {
    pub fn with_headers(headers: HashMap<String, String>) -> Self {
        let mut wb = WebBackend::new();
        for (k, v) in headers.into_iter() {
            wb.set_header(&k, &v);
        }
        wb
    }

    pub fn get_headers(&self) -> HashMap<String, String> {
        // Adjust to match the actual internal representation (this assumes a HashMap field named headers)
        self.headers.clone()
    }

    pub fn set_header(&mut self, key: &str, value: &str) {
        self.headers.insert(key.to_string(), value.to_string());
    }
    /// Creates a new WebBackend with a persistent HTTP client.
    pub fn new() -> Self {
        let config = Agent::config_builder().http_status_as_error(false).build();
        let agent: Agent = config.into();
        Self {
            agent,
            headers: HashMap::new(),
            last_response: None,
        }
    }

    /// Executes a single web-related action. Returns true if the action was handled.
    pub fn execute_action(
        &mut self,
        action: &Action,
        env_vars: &mut HashMap<String, String>,
        verbose: bool,
    ) -> bool {
        self.last_response = None;
        let substituted_action = substitute_variables_in_action(action, env_vars);
        let start_time = std::time::Instant::now();
        let result: Result<Response<Body>, ureq::Error> = match &substituted_action {
            Action::HttpSetHeader { key, value } => {
                if verbose {
                    println!("[WEB_BACKEND] Setting HTTP header: {}: {}", key, value);
                }
                self.headers.insert(key.clone(), value.clone());

                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpClearHeader { key } => {
                if verbose {
                    println!("[WEB_BACKEND] Clearing HTTP header: {}", key);
                }
                self.headers.remove(&*key);
                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpClearHeaders => {
                if verbose {
                    println!("[WEB_BACKEND] Clearing all HTTP headers");
                }
                self.headers.clear();
                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpSetCookie { key, value } => {
                // Handle multiple cookies by appending to existing Cookie header
                let new_cookie = format!("{}={}", key, value);
                match self.headers.get("Cookie") {
                    Some(existing) => {
                        let updated_cookies = format!("{}; {}", existing, new_cookie);
                        self.headers.insert("Cookie".to_string(), updated_cookies);
                    }
                    None => {
                        self.headers.insert("Cookie".to_string(), new_cookie);
                    }
                }

                if verbose {
                    println!("[WEB_BACKEND] Added cookie: {}={}", key, value);
                    println!(
                        "[WEB_BACKEND] Current Cookie header: {}",
                        self.headers.get("Cookie").unwrap_or(&"".to_string())
                    );
                }
                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpClearCookie { key } => {
                if let Some(cookie_header) = self.headers.get("Cookie") {
                    // Parse and filter out the specific cookie
                    let cookies: Vec<&str> = cookie_header.split(';').collect();
                    let filtered_cookies: Vec<&str> = cookies
                        .into_iter()
                        .filter(|cookie| {
                            let cookie_trimmed = cookie.trim();
                            !cookie_trimmed.starts_with(&format!("{}=", key))
                        })
                        .collect();

                    if filtered_cookies.is_empty() {
                        self.headers.remove("Cookie");
                    } else {
                        let new_cookie_header = filtered_cookies.join("; ");
                        self.headers.insert("Cookie".to_string(), new_cookie_header);
                    }
                }

                if verbose {
                    println!("[WEB_BACKEND] Cleared cookie: {}", key);
                }
                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpClearCookies => {
                if verbose {
                    println!("[WEB_BACKEND] Clearing all HTTP cookies");
                }
                self.headers.remove("Cookie");
                // This isn't a request but need to return a response
                let response = Response::builder()
                    .status(200)
                    .body(Body::builder().data("choreo"));
                Ok(response.expect("hmm"))
            }
            Action::HttpGet { url, .. } => {
                if verbose {
                    println!("[WEB_BACKEND] Performing HTTP GET to: {}", url);
                }

                let mut request = self.agent.get(url);

                // Add headers
                for (key, value) in &self.headers {
                    request = request.header(key, value);
                }

                request.call()
            }
            Action::HttpPost { url, body } => {
                if verbose {
                    println!("[WEB_BACKEND] Performing HTTP POST to: {}", url);
                }

                let mut request = self.agent.post(url);

                // Add headers
                for (key, value) in &self.headers {
                    request = request.header(key, value);
                }

                request.send(body)
            }
            Action::HttpPut { url, body } => {
                if verbose {
                    println!("[WEB_BACKEND] Performing HTTP PUT to: {}", url);
                }

                let mut request = self.agent.put(url);

                // Add headers
                for (key, value) in &self.headers {
                    request = request.header(key, value);
                }

                request.send(body)
            }
            Action::HttpPatch { url, body } => {
                if verbose {
                    println!("[WEB_BACKEND] Performing HTTP PATCH to: {}", url);
                }

                let mut request = self.agent.patch(url);

                for (key, value) in &self.headers {
                    request = request.header(key, value);
                }

                request.send(body)
            }
            Action::HttpDelete { url } => {
                if verbose {
                    println!("[WEB_BACKEND] Performing HTTP DELETE to: {}", url);
                }

                let mut request = self.agent.delete(url);

                // Add headers
                for (key, value) in &self.headers {
                    request = request.header(key, value);
                }

                request.call()
            }
            _ => return false,
        };

        let compat_result = match result {
            Ok(response) => {
                let status = response.status();
                match status.as_u16() {
                    200..=299 => CompatResult::Success(response),
                    400..=499 => CompatResult::ClientError(response),
                    500..=599 => CompatResult::ServerError(response),
                    _ => CompatResult::Success(response), // Handle other cases like redirects if needed
                }
            }
            Err(e) => CompatResult::TransportError(e),
        };

        let mut process_response = |response: Response<Body>, message: String| {
            let status = response.status();
            let content_type = response
                .headers()
                .get("content-type")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("")
                .to_string();

            let body = response
                .into_body()
                .read_to_string()
                .unwrap_or_else(|e| format!("[choreo] Failed to read response body: {}", e));

            let body_json = if content_type.contains("application/json") {
                // Pretty print JSON for better readability
                serde_json::from_str::<serde_json::Value>(&body)
                    .map(|v| serde_json::to_string_pretty(&v).unwrap_or(body.clone()))
                    .unwrap_or(body.clone())
            } else {
                body
            };

            let response_time_ms = start_time.elapsed().as_millis();
            self.last_response = Some(LastResponse {
                status,
                body: body_json.clone(),
                message: Some(message.to_string()),
                response_time_ms,
            });
        };

        match compat_result {
            CompatResult::Success(response) => {
                // 200 success
                let status = response.status();
                let message = format!("HTTP request succeeded with status {}", status);
                process_response(response, message);
            }
            CompatResult::ClientError(response) => {
                // client error (4xx)
                let status = response.status();
                let message = format!("HTTP client error: {}", status);
                process_response(response, message);
            }
            CompatResult::ServerError(response) => {
                // server error (5xx)
                let status = response.status();
                let message = format!("HTTP server error: {}", status);
                process_response(response, message);
            }
            CompatResult::TransportError(e) => {
                // Transport-level errors.
                let error_message = format!("[WEB_BACKEND] HTTP request failed: {}", e);
                self.last_response = Some(LastResponse {
                    status: StatusCode::from_u16(599).unwrap(),
                    body: error_message.clone(),
                    response_time_ms: 0,
                    message: Some(error_message),
                });
            }
        }
        true
    }

    /// Checks a single web-related condition against the last response.
    pub fn check_condition(
        &self,
        condition: &Condition,
        variables: &mut HashMap<String, String>,
        verbose: bool,
    ) -> bool {
        // If no request has been made yet, all web conditions fail.
        let last_response = match &self.last_response {
            Some(res) => res,
            None => return false,
        };

        match condition {
            Condition::ResponseStatusIs(expected_status) => {
                last_response.status == *expected_status
            }
            Condition::ResponseStatusIsSuccess => last_response.status.is_success(),
            Condition::ResponseStatusIsError => {
                last_response.status.is_client_error() || last_response.status.is_server_error()
            }
            Condition::ResponseStatusIsIn(statuses) => {
                statuses.contains(&last_response.status.as_u16())
            }
            Condition::ResponseTimeIsBelow { duration } => {
                if let Some(last_response) = &self.last_response {
                    // `duration` is expected in seconds (float). Compare correctly.
                    let actual_time_seconds = last_response.response_time_ms as f32 / 1000.0;
                    let result = actual_time_seconds < *duration;
                    if verbose {
                        println!(
                            "[WEB_BACKEND] Response time: {}ms ({:.3}s), expected below: {:.3}s -> {}",
                            last_response.response_time_ms,
                            actual_time_seconds,
                            duration,
                            result
                        );
                    }
                    result
                } else {
                    false
                }
            }
            Condition::ResponseBodyContains { value } => {
                if verbose {
                    println!("[WEB_BACKEND] Received response body contains '{}'", value);
                    println!("[WEB_BACKEND] Full response body: {}", last_response.body);
                }
                last_response.body.contains(value)
            }
            Condition::ResponseBodyMatches { regex, capture_as } => {
                if let Ok(re) = regex::Regex::new(regex) {
                    if let Some(captures) = re.captures(&last_response.body) {
                        //println!("Regexp: {}", captures.get(0).unwrap().as_str());
                        if let Some(var_name) = capture_as {
                            if let Some(capture_group) = captures.get(1) {
                                let value = capture_group.as_str().to_string();
                                variables.insert(var_name.clone(), value);
                            }
                        }
                        return true;
                    }
                }
                false
            }
            Condition::ResponseBodyEqualsJson { expected, ignored } => {
                // This is the new closure to pre-process and fix malformed JSON strings.
                let fix_json_escaping = |json_str: &str| -> String {
                    json_str.replace(r#"\\d{8,}$"""#, r#"\\d{8,}$""#)
                };

                // Substitute variables in the expected JSON string
                let substituted_expected = substitute_string(expected, variables);
                let fixed_actual_body = fix_json_escaping(&last_response.body);
                let fixed_expected_body = fix_json_escaping(&substituted_expected);

                // Parse both the response body and expected JSON for comparison
                match (
                    serde_json::from_str::<JsonValue>(&fixed_actual_body),
                    serde_json::from_str::<JsonValue>(&fixed_expected_body),
                ) {
                    (Ok(mut actual), Ok(mut expected_json)) => {
                        if verbose {
                            println!(
                                "[WEB_BACKEND] Comparing JSON response body with expected JSON"
                            );
                        }
                        // Remove ignored fields from both actual and expected JSON values
                        for field in ignored {
                            remove_json_field_recursive(&mut actual, field);
                            remove_json_field_recursive(&mut expected_json, field);
                        }

                        // Normalise both JSON values
                        normalise_json(&mut actual);
                        normalise_json(&mut expected_json);

                        let result = json_values_equal(&actual, &expected_json);

                        if !result && verbose {
                            println!(
                                "[WEB_BACKEND] Actual (after ignoring fields): {}",
                                serde_json::to_string_pretty(&actual).unwrap_or_default()
                            );
                            println!(
                                "[WEB_BACKEND] Expected (after ignoring fields): {}",
                                serde_json::to_string_pretty(&expected_json).unwrap_or_default()
                            );
                        }
                        result
                    }
                    (Err(e), _) => {
                        if verbose {
                            println!("[WEB_BACKEND] Failed to parse response body as JSON: {}", e);
                            println!("[WEB_BACKEND] Response body: {}", last_response.body);
                        }
                        false
                    }
                    (_, Err(e)) => {
                        if verbose {
                            println!("[WEB_BACKEND] Failed to parse expected JSON: {}", e);
                            println!("[WEB_BACKEND] Expected JSON: {}", substituted_expected);
                        }
                        false
                    }
                }
            }
            Condition::JsonValueIsString { path } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        return value.is_string();
                    }
                }
                false
            }
            Condition::JsonValueIsNumber { path } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        return value.is_number();
                    }
                }
                false
            }
            Condition::JsonValueIsArray { path } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        return value.is_array();
                    }
                }
                false
            }
            Condition::JsonValueIsObject { path } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        return value.is_object();
                    }
                }
                false
            }
            Condition::JsonValueHasSize { path, size } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        return match value {
                            JsonValue::Array(arr) => arr.len() == *size,
                            JsonValue::String(s) => s.len() == *size,
                            JsonValue::Object(obj) => obj.len() == *size,
                            _ => false,
                        };
                    }
                }
                false
            }
            Condition::JsonBodyHasPath { path } => {
                // Try to parse the body as JSON. If it fails, the condition fails.
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    // Use `pointer` to navigate the JSON structure.
                    // The path must be in JSON Pointer format (e.g., "/user/id").
                    json_body.pointer(path).is_some()
                } else {
                    false
                }
            }
            Condition::JsonPathEquals {
                path,
                expected_value,
            } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(actual_value) = json_body.pointer(path) {
                        // Convert the serde_json::Value to our AST Value for comparison.
                        let our_value = match actual_value {
                            JsonValue::String(s) => Value::String(s.clone()),
                            JsonValue::Number(n) => {
                                // Prefer integer if available, otherwise fall back to float -> i32
                                if let Some(i) = n.as_i64() {
                                    Value::Number(i as i32)
                                } else {
                                    Value::Number(n.as_f64().unwrap_or(0.0) as i32)
                                }
                            }
                            JsonValue::Bool(b) => Value::Bool(*b),
                            // Add other type conversions as needed.
                            // I'm lacking Object, Array abd null - TODO
                            _ => Value::String(actual_value.to_string()),
                        };
                        return &our_value == expected_value;
                    }
                }
                false
            }
            Condition::JsonPathCapture { path, capture_as } => {
                if let Ok(json_body) = serde_json::from_str::<JsonValue>(&last_response.body) {
                    if let Some(value) = json_body.pointer(path) {
                        // Convert the JSON value to a string and capture it
                        let captured_value = match value {
                            JsonValue::String(s) => s.clone(),
                            JsonValue::Number(n) => n.to_string(),
                            JsonValue::Bool(b) => b.to_string(),
                            JsonValue::Null => "null".to_string(),
                            _ => value.to_string(), // For arrays and objects
                        };

                        variables.insert(capture_as.clone(), captured_value);

                        if verbose {
                            println!(
                                "[WEB_BACKEND] Captured value from path '{}': {}",
                                path,
                                variables.get(capture_as).unwrap()
                            );
                        }

                        return true;
                    }
                }
                false
            }
            _ => false, // Not a web condition
        }
    }
}

/// Recursively normalises a JSON value to a canonical form.
fn normalise_json(value: &mut JsonValue) {
    match value {
        JsonValue::Object(map) => {
            // For objects, we just need to recurse into their values.
            for (_, v) in map.iter_mut() {
                normalise_json(v);
            }
        }
        JsonValue::Array(arr) => {
            // For arrays, we must first normalise each item within the array.
            for item in arr.iter_mut() {
                normalise_json(item);
            }

            // Sort the jason in its canonical form
            arr.sort_by_key(|a| serde_json::to_string(a).unwrap_or_default());
        }
        _ => {
            // Primitives are already in their canonical form.
        }
    }
}

/// Recursively removes a field from a serde_json::Value.
fn remove_json_field_recursive(value: &mut JsonValue, field_to_remove: &str) {
    match value {
        JsonValue::Object(map) => {
            map.remove(field_to_remove);
            for (_, v) in map.iter_mut() {
                remove_json_field_recursive(v, field_to_remove);
            }
        }
        JsonValue::Array(arr) => {
            for v in arr.iter_mut() {
                remove_json_field_recursive(v, field_to_remove);
            }
        }
        _ => {}
    }
}

fn numbers_equal(a: &serde_json::Number, b: &serde_json::Number) -> bool {
    // Fast path: identical representation
    if a == b {
        return true;
    }
    // Compare as f64 with small epsilon to allow int vs float equality (23 == 23.0)
    match (a.as_f64(), b.as_f64()) {
        (Some(af), Some(bf)) => (af - bf).abs() < 1e-9,
        _ => false,
    }
}

fn json_values_equal(a: &JsonValue, b: &JsonValue) -> bool {
    match (a, b) {
        (JsonValue::Null, JsonValue::Null) => true,
        (JsonValue::Bool(x), JsonValue::Bool(y)) => x == y,
        (JsonValue::String(x), JsonValue::String(y)) => x == y,
        (JsonValue::Number(x), JsonValue::Number(y)) => numbers_equal(x, y),
        (JsonValue::Array(ax), JsonValue::Array(bx)) => {
            if ax.len() != bx.len() {
                return false;
            }
            for (av, bv) in ax.iter().zip(bx.iter()) {
                if !json_values_equal(av, bv) {
                    return false;
                }
            }
            true
        }
        (JsonValue::Object(am), JsonValue::Object(bm)) => {
            if am.len() != bm.len() {
                return false;
            }
            for (k, av) in am {
                match bm.get(k) {
                    Some(bv) if json_values_equal(av, bv) => continue,
                    _ => return false,
                }
            }
            true
        }
        // allow equality between integer-like string and number? keep strict for other mismatches
        _ => false,
    }
}