mockforge-bench 0.3.135

Load and performance testing for MockForge
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! CRUD Flow support for load testing
//!
//! This module provides functionality to automatically detect and configure
//! CRUD (Create, Read, Update, Delete) flows from OpenAPI specifications,
//! enabling sequential testing with response chaining.

use crate::error::{BenchError, Result};
use crate::spec_parser::ApiOperation;
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::Path;

/// Field extraction configuration - supports field extraction, aliased extraction, and full body extraction
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ExtractField {
    /// The field name to extract from the response (None if extracting full body)
    /// Supports nested paths: "uuid", "data.uuid", "results[0].uuid", "results[?name=\"global\"].uuid"
    #[serde(skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,
    /// Extract entire response body instead of a single field
    #[serde(default)]
    pub body: bool,
    /// The name to store it as (defaults to field name if not specified)
    /// Note: Deserialization accepts "as" via custom Deserialize impl, but serializes as "store_as"
    pub store_as: String,
    /// Keys to exclude when extracting full body (only used when body=true)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,
    /// Match mode for filter expressions: "first" (default) or "last"
    /// Used when field path contains a filter like results[?name="global"]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub match_mode: Option<String>,
}

impl ExtractField {
    /// Create a new extract field with the same name for field and storage
    pub fn simple(field: String) -> Self {
        Self {
            store_as: field.clone(),
            field: Some(field),
            body: false,
            exclude: Vec::new(),
            match_mode: None,
        }
    }

    /// Create a new extract field with an alias
    pub fn aliased(field: String, store_as: String) -> Self {
        Self {
            field: Some(field),
            store_as,
            body: false,
            exclude: Vec::new(),
            match_mode: None,
        }
    }

    /// Create a new extract field with an alias and match mode
    pub fn aliased_with_match(field: String, store_as: String, match_mode: Option<String>) -> Self {
        Self {
            field: Some(field),
            store_as,
            body: false,
            exclude: Vec::new(),
            match_mode,
        }
    }

    /// Create a full body extraction with optional key filtering
    pub fn full_body(store_as: String, exclude: Vec<String>) -> Self {
        Self {
            field: None,
            body: true,
            store_as,
            exclude,
            match_mode: None,
        }
    }
}

impl<'de> Deserialize<'de> for ExtractField {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};

        struct ExtractFieldVisitor;

        impl<'de> Visitor<'de> for ExtractFieldVisitor {
            type Value = ExtractField;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a string, an object with 'field' and optional 'as' keys, or an object with 'body: true' and 'as' keys")
            }

            // Handle simple string: "uuid"
            fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(ExtractField::simple(value.to_string()))
            }

            // Handle object: {field: "uuid", as: "pool_uuid"} or {body: true, as: "vs_body", exclude: [...]}
            fn visit_map<M>(self, mut map: M) -> std::result::Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut field: Option<String> = None;
                let mut store_as: Option<String> = None;
                let mut body: bool = false;
                let mut exclude: Vec<String> = Vec::new();
                let mut match_mode: Option<String> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "field" => {
                            field = Some(map.next_value()?);
                        }
                        "as" => {
                            store_as = Some(map.next_value()?);
                        }
                        "body" => {
                            body = map.next_value()?;
                        }
                        "exclude" => {
                            exclude = map.next_value()?;
                        }
                        "match" | "match_mode" => {
                            match_mode = Some(map.next_value()?);
                        }
                        _ => {
                            let _: de::IgnoredAny = map.next_value()?;
                        }
                    }
                }

                if body {
                    // Full body extraction mode
                    let store_as = store_as.ok_or_else(|| de::Error::missing_field("as"))?;
                    Ok(ExtractField {
                        field: None,
                        body: true,
                        store_as,
                        exclude,
                        match_mode: None,
                    })
                } else {
                    // Field extraction mode
                    let field = field.ok_or_else(|| de::Error::missing_field("field"))?;
                    let store_as = store_as.unwrap_or_else(|| field.clone());
                    Ok(ExtractField {
                        field: Some(field),
                        body: false,
                        store_as,
                        exclude: Vec::new(),
                        match_mode,
                    })
                }
            }
        }

        deserializer.deserialize_any(ExtractFieldVisitor)
    }
}

/// A single step in a CRUD flow
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowStep {
    /// The operation identifier (e.g., "POST /users" or operation_id)
    pub operation: String,
    /// Fields to extract from the response (for subsequent steps)
    /// Supports multiple formats:
    /// - Simple: "uuid" (extracts uuid, stores as uuid)
    /// - Aliased: {field: "uuid", as: "pool_uuid"} (extracts uuid, stores as pool_uuid)
    /// - Full body: {body: true, as: "vs_body", exclude: ["_last_modified"]}
    #[serde(default)]
    pub extract: Vec<ExtractField>,
    /// Mapping of path/body variables to extracted values
    /// Key: variable name in request, Value: extracted field name
    #[serde(default)]
    pub use_values: HashMap<String, String>,
    /// Use a previously extracted body as the request body for this step
    /// The value should match the 'as' name from a previous body extraction
    #[serde(skip_serializing_if = "Option::is_none")]
    pub use_body: Option<String>,
    /// Merge/override fields in the extracted body before sending
    /// Works with use_body to modify specific fields in the extracted body
    /// Example: merge_body: {enabled: false, name: "updated-name"}
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub merge_body: HashMap<String, serde_json::Value>,
    /// Inject security attack payloads into this step's request
    /// When true, security payloads from wafbench or configured attacks will be injected
    #[serde(default)]
    pub inject_attacks: bool,
    /// Specific attack types to inject (if not all)
    /// Examples: "sqli", "xss", "rce", "lfi"
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attack_types: Vec<String>,
    /// Optional description for this step
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl FlowStep {
    /// Create a new flow step
    pub fn new(operation: String) -> Self {
        Self {
            operation,
            extract: Vec::new(),
            use_values: HashMap::new(),
            use_body: None,
            merge_body: HashMap::new(),
            inject_attacks: false,
            attack_types: Vec::new(),
            description: None,
        }
    }

    /// Add fields to extract from response (simple field names)
    pub fn with_extract(mut self, fields: Vec<String>) -> Self {
        self.extract = fields.into_iter().map(ExtractField::simple).collect();
        self
    }

    /// Add fields to extract with aliases
    pub fn with_extract_fields(mut self, fields: Vec<ExtractField>) -> Self {
        self.extract = fields;
        self
    }

    /// Add value mappings for this step
    pub fn with_values(mut self, values: HashMap<String, String>) -> Self {
        self.use_values = values;
        self
    }

    /// Use a previously extracted body as the request body
    pub fn with_use_body(mut self, body_name: String) -> Self {
        self.use_body = Some(body_name);
        self
    }

    /// Merge/override fields in the extracted body
    pub fn with_merge_body(mut self, merge: HashMap<String, serde_json::Value>) -> Self {
        self.merge_body = merge;
        self
    }

    /// Enable security attack injection for this step
    pub fn with_inject_attacks(mut self, inject: bool) -> Self {
        self.inject_attacks = inject;
        self
    }

    /// Specify which attack types to inject
    pub fn with_attack_types(mut self, types: Vec<String>) -> Self {
        self.attack_types = types;
        self
    }

    /// Add a description
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }
}

/// A complete CRUD flow definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrudFlow {
    /// Name of this flow
    pub name: String,
    /// Base path for this resource (e.g., "/users")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_path: Option<String>,
    /// Ordered list of steps in the flow
    pub steps: Vec<FlowStep>,
}

impl CrudFlow {
    /// Create a new CRUD flow with a name
    pub fn new(name: String) -> Self {
        Self {
            name,
            base_path: None,
            steps: Vec::new(),
        }
    }

    /// Set the base path
    pub fn with_base_path(mut self, path: String) -> Self {
        self.base_path = Some(path);
        self
    }

    /// Add a step to the flow
    pub fn add_step(&mut self, step: FlowStep) {
        self.steps.push(step);
    }

    /// Get all fields that need to be extracted across all steps (returns field names)
    /// Note: Only returns field names, not body extractions
    pub fn get_all_extract_fields(&self) -> HashSet<String> {
        self.steps
            .iter()
            .flat_map(|step| step.extract.iter().filter_map(|e| e.field.clone()))
            .collect()
    }

    /// Get all extract field configurations across all steps
    pub fn get_all_extract_configs(&self) -> Vec<&ExtractField> {
        self.steps.iter().flat_map(|step| step.extract.iter()).collect()
    }
}

/// CRUD flow configuration containing multiple flows
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrudFlowConfig {
    /// List of CRUD flows
    pub flows: Vec<CrudFlow>,
    /// Default fields to extract if not specified
    #[serde(default)]
    pub default_extract_fields: Vec<String>,
}

impl Default for CrudFlowConfig {
    fn default() -> Self {
        Self {
            flows: Vec::new(),
            default_extract_fields: vec!["id".to_string(), "uuid".to_string()],
        }
    }
}

impl CrudFlowConfig {
    /// Load configuration from a YAML file
    pub fn from_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| BenchError::Other(format!("Failed to read flow config: {}", e)))?;

        Self::from_yaml(&content)
    }

    /// Parse configuration from YAML string
    pub fn from_yaml(yaml: &str) -> Result<Self> {
        serde_yaml::from_str(yaml)
            .map_err(|e| BenchError::Other(format!("Failed to parse flow config: {}", e)))
    }

    /// Create configuration with a single flow
    pub fn single_flow(flow: CrudFlow) -> Self {
        Self {
            flows: vec![flow],
            ..Default::default()
        }
    }
}

/// Grouped operations by base path for CRUD detection
#[derive(Debug, Clone)]
pub struct ResourceOperations {
    /// Base path (e.g., "/users")
    pub base_path: String,
    /// CREATE operation (typically POST on base path)
    pub create: Option<ApiOperation>,
    /// READ single operation (typically GET on {id} path)
    pub read: Option<ApiOperation>,
    /// UPDATE operation (typically PUT/PATCH on {id} path)
    pub update: Option<ApiOperation>,
    /// DELETE operation (typically DELETE on {id} path)
    pub delete: Option<ApiOperation>,
    /// LIST operation (typically GET on base path)
    pub list: Option<ApiOperation>,
}

impl ResourceOperations {
    /// Create a new resource operations group
    pub fn new(base_path: String) -> Self {
        Self {
            base_path,
            create: None,
            read: None,
            update: None,
            delete: None,
            list: None,
        }
    }

    /// Check if this resource has CRUD operations
    pub fn has_crud_operations(&self) -> bool {
        self.create.is_some()
            && (self.read.is_some() || self.update.is_some() || self.delete.is_some())
    }

    /// Get the ID parameter name from the path (e.g., "{id}", "{userId}")
    pub fn get_id_param_name(&self) -> Option<String> {
        // Look at read, update, or delete operations to find the ID parameter
        let path = self
            .read
            .as_ref()
            .or(self.update.as_ref())
            .or(self.delete.as_ref())
            .map(|op| &op.path)?;

        // Extract parameter name from path like "/users/{id}" or "/users/{userId}"
        extract_id_param_from_path(path)
    }
}

/// Extract the ID parameter name from a path pattern
fn extract_id_param_from_path(path: &str) -> Option<String> {
    // Find the last path segment that looks like {paramName}
    for segment in path.split('/').rev() {
        if segment.starts_with('{') && segment.ends_with('}') {
            return Some(segment[1..segment.len() - 1].to_string());
        }
    }
    None
}

/// Extract the base path from a full path
/// e.g., "/users/{id}" -> "/users"
fn get_base_path(path: &str) -> String {
    let segments: Vec<&str> = path.split('/').collect();
    let mut base_segments = Vec::new();

    for segment in segments {
        if segment.starts_with('{') {
            break;
        }
        if !segment.is_empty() {
            base_segments.push(segment);
        }
    }

    if base_segments.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", base_segments.join("/"))
    }
}

/// Check if a path is a "detail" path (has ID parameter)
fn is_detail_path(path: &str) -> bool {
    path.contains('{') && path.contains('}')
}

/// Auto-detect CRUD flows from a list of operations
pub struct CrudFlowDetector;

impl CrudFlowDetector {
    /// Detect CRUD flows from API operations
    ///
    /// Groups operations by base path and identifies CRUD patterns.
    pub fn detect_flows(operations: &[ApiOperation]) -> Vec<CrudFlow> {
        // Group operations by base path
        let mut resources: HashMap<String, ResourceOperations> = HashMap::new();

        for op in operations {
            let base_path = get_base_path(&op.path);
            let is_detail = is_detail_path(&op.path);
            let method = op.method.to_lowercase();

            let resource = resources
                .entry(base_path.clone())
                .or_insert_with(|| ResourceOperations::new(base_path));

            match (method.as_str(), is_detail) {
                ("post", false) => resource.create = Some(op.clone()),
                ("get", false) => resource.list = Some(op.clone()),
                ("get", true) => resource.read = Some(op.clone()),
                ("put", true) | ("patch", true) => resource.update = Some(op.clone()),
                ("delete", true) => resource.delete = Some(op.clone()),
                _ => {}
            }
        }

        // Build flows from resources that have CRUD operations
        resources
            .into_values()
            .filter(|r| r.has_crud_operations())
            .map(|r| Self::build_flow_from_resource(&r))
            .collect()
    }

    /// Build a CRUD flow from a resource's operations
    fn build_flow_from_resource(resource: &ResourceOperations) -> CrudFlow {
        let name = resource.base_path.trim_start_matches('/').replace('/', "_").to_string();

        let mut flow =
            CrudFlow::new(format!("{} CRUD", name)).with_base_path(resource.base_path.clone());

        let id_param = resource.get_id_param_name().unwrap_or_else(|| "id".to_string());

        // Step 1: CREATE (POST) - extract ID
        if let Some(create_op) = &resource.create {
            let step =
                FlowStep::new(format!("{} {}", create_op.method.to_uppercase(), create_op.path))
                    .with_extract(vec!["id".to_string(), "uuid".to_string()])
                    .with_description("Create resource".to_string());
            flow.add_step(step);
        }

        // Step 2: READ (GET) - verify creation
        if let Some(read_op) = &resource.read {
            let mut values = HashMap::new();
            values.insert(id_param.clone(), "id".to_string());

            let step = FlowStep::new(format!("{} {}", read_op.method.to_uppercase(), read_op.path))
                .with_values(values)
                .with_description("Read created resource".to_string());
            flow.add_step(step);
        }

        // Step 3: UPDATE (PUT/PATCH) - modify resource
        if let Some(update_op) = &resource.update {
            let mut values = HashMap::new();
            values.insert(id_param.clone(), "id".to_string());

            let step =
                FlowStep::new(format!("{} {}", update_op.method.to_uppercase(), update_op.path))
                    .with_values(values)
                    .with_description("Update resource".to_string());
            flow.add_step(step);
        }

        // Step 4: READ again (GET) - verify update
        if let Some(read_op) = &resource.read {
            let mut values = HashMap::new();
            values.insert(id_param.clone(), "id".to_string());

            let step = FlowStep::new(format!("{} {}", read_op.method.to_uppercase(), read_op.path))
                .with_values(values)
                .with_description("Verify update".to_string());
            flow.add_step(step);
        }

        // Step 5: DELETE - cleanup
        if let Some(delete_op) = &resource.delete {
            let mut values = HashMap::new();
            values.insert(id_param.clone(), "id".to_string());

            let step =
                FlowStep::new(format!("{} {}", delete_op.method.to_uppercase(), delete_op.path))
                    .with_values(values)
                    .with_description("Delete resource".to_string());
            flow.add_step(step);
        }

        flow
    }

    /// Merge auto-detected flows with user-provided configuration
    ///
    /// User configuration takes precedence over auto-detected flows.
    pub fn merge_with_config(detected: Vec<CrudFlow>, config: &CrudFlowConfig) -> Vec<CrudFlow> {
        if !config.flows.is_empty() {
            // If user provided flows, use those
            config.flows.clone()
        } else {
            // Otherwise use auto-detected flows
            detected
        }
    }
}

/// Context for CRUD flow execution (tracks extracted values)
#[derive(Debug, Clone, Default)]
pub struct FlowExecutionContext {
    /// Extracted values from previous steps
    /// Key: field name, Value: extracted value
    pub extracted_values: HashMap<String, String>,
    /// Current step index
    pub current_step: usize,
    /// Errors encountered
    pub errors: Vec<String>,
}

impl FlowExecutionContext {
    /// Create a new execution context
    pub fn new() -> Self {
        Self::default()
    }

    /// Store an extracted value
    pub fn store_value(&mut self, key: String, value: String) {
        self.extracted_values.insert(key, value);
    }

    /// Get an extracted value
    pub fn get_value(&self, key: &str) -> Option<&String> {
        self.extracted_values.get(key)
    }

    /// Advance to the next step
    pub fn next_step(&mut self) {
        self.current_step += 1;
    }

    /// Record an error
    pub fn record_error(&mut self, error: String) {
        self.errors.push(error);
    }

    /// Check if execution has errors
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }
}

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

    fn create_test_operation(method: &str, path: &str, operation_id: Option<&str>) -> ApiOperation {
        ApiOperation {
            method: method.to_string(),
            path: path.to_string(),
            operation: Operation::default(),
            operation_id: operation_id.map(|s| s.to_string()),
        }
    }

    #[test]
    fn test_get_base_path() {
        assert_eq!(get_base_path("/users"), "/users");
        assert_eq!(get_base_path("/users/{id}"), "/users");
        assert_eq!(get_base_path("/api/v1/users/{userId}"), "/api/v1/users");
        assert_eq!(get_base_path("/resources/{resourceId}/items/{itemId}"), "/resources");
        assert_eq!(get_base_path("/"), "/");
    }

    #[test]
    fn test_is_detail_path() {
        assert!(!is_detail_path("/users"));
        assert!(is_detail_path("/users/{id}"));
        assert!(is_detail_path("/users/{userId}"));
        assert!(!is_detail_path("/users/list"));
    }

    #[test]
    fn test_extract_id_param_from_path() {
        assert_eq!(extract_id_param_from_path("/users/{id}"), Some("id".to_string()));
        assert_eq!(extract_id_param_from_path("/users/{userId}"), Some("userId".to_string()));
        assert_eq!(extract_id_param_from_path("/a/{b}/{c}"), Some("c".to_string()));
        assert_eq!(extract_id_param_from_path("/users"), None);
    }

    #[test]
    fn test_crud_flow_detection() {
        let operations = vec![
            create_test_operation("post", "/users", Some("createUser")),
            create_test_operation("get", "/users", Some("listUsers")),
            create_test_operation("get", "/users/{id}", Some("getUser")),
            create_test_operation("put", "/users/{id}", Some("updateUser")),
            create_test_operation("delete", "/users/{id}", Some("deleteUser")),
        ];

        let flows = CrudFlowDetector::detect_flows(&operations);
        assert_eq!(flows.len(), 1);

        let flow = &flows[0];
        assert!(flow.name.contains("users"));
        assert_eq!(flow.steps.len(), 5); // CREATE, READ, UPDATE, READ, DELETE

        // First step should be POST (create)
        assert!(flow.steps[0].operation.starts_with("POST"));
        // Should extract id
        assert!(flow.steps[0].extract.iter().any(|e| e.field.as_deref() == Some("id")));
    }

    #[test]
    fn test_multiple_resources_detection() {
        let operations = vec![
            // Users resource
            create_test_operation("post", "/users", Some("createUser")),
            create_test_operation("get", "/users/{id}", Some("getUser")),
            create_test_operation("delete", "/users/{id}", Some("deleteUser")),
            // Posts resource
            create_test_operation("post", "/posts", Some("createPost")),
            create_test_operation("get", "/posts/{id}", Some("getPost")),
            create_test_operation("put", "/posts/{id}", Some("updatePost")),
        ];

        let flows = CrudFlowDetector::detect_flows(&operations);
        assert_eq!(flows.len(), 2);
    }

    #[test]
    fn test_no_crud_without_create() {
        let operations = vec![
            // Only read operations - no CREATE
            create_test_operation("get", "/users", Some("listUsers")),
            create_test_operation("get", "/users/{id}", Some("getUser")),
        ];

        let flows = CrudFlowDetector::detect_flows(&operations);
        assert!(flows.is_empty());
    }

    #[test]
    fn test_flow_step_builder() {
        let step = FlowStep::new("POST /users".to_string())
            .with_extract(vec!["id".to_string(), "uuid".to_string()])
            .with_description("Create a new user".to_string());

        assert_eq!(step.operation, "POST /users");
        assert_eq!(step.extract.len(), 2);
        assert_eq!(step.description, Some("Create a new user".to_string()));
    }

    #[test]
    fn test_flow_step_use_values() {
        let mut values = HashMap::new();
        values.insert("id".to_string(), "user_id".to_string());

        let step = FlowStep::new("GET /users/{id}".to_string()).with_values(values);

        assert_eq!(step.use_values.get("id"), Some(&"user_id".to_string()));
    }

    #[test]
    fn test_crud_flow_config_from_yaml() {
        let yaml = r#"
flows:
  - name: "User CRUD"
    base_path: "/users"
    steps:
      - operation: "POST /users"
        extract: ["id"]
        description: "Create user"
      - operation: "GET /users/{id}"
        use_values:
          id: "id"
        description: "Get user"
default_extract_fields:
  - id
  - uuid
"#;

        let config = CrudFlowConfig::from_yaml(yaml).expect("Should parse YAML");
        assert_eq!(config.flows.len(), 1);
        assert_eq!(config.flows[0].name, "User CRUD");
        assert_eq!(config.flows[0].steps.len(), 2);
        assert_eq!(config.default_extract_fields.len(), 2);
    }

    #[test]
    fn test_execution_context() {
        let mut ctx = FlowExecutionContext::new();

        ctx.store_value("id".to_string(), "12345".to_string());
        assert_eq!(ctx.get_value("id"), Some(&"12345".to_string()));

        ctx.next_step();
        assert_eq!(ctx.current_step, 1);

        ctx.record_error("Something went wrong".to_string());
        assert!(ctx.has_errors());
    }

    #[test]
    fn test_resource_operations_has_crud() {
        let mut resource = ResourceOperations::new("/users".to_string());
        assert!(!resource.has_crud_operations());

        resource.create = Some(create_test_operation("post", "/users", Some("createUser")));
        assert!(!resource.has_crud_operations()); // Still needs read/update/delete

        resource.read = Some(create_test_operation("get", "/users/{id}", Some("getUser")));
        assert!(resource.has_crud_operations());
    }

    #[test]
    fn test_get_id_param_name() {
        let mut resource = ResourceOperations::new("/users".to_string());
        resource.read = Some(create_test_operation("get", "/users/{userId}", Some("getUser")));

        assert_eq!(resource.get_id_param_name(), Some("userId".to_string()));
    }

    #[test]
    fn test_merge_with_config_user_provided() {
        let detected = vec![CrudFlow::new("detected_flow".to_string())];

        let mut config = CrudFlowConfig::default();
        config.flows.push(CrudFlow::new("user_flow".to_string()));

        let result = CrudFlowDetector::merge_with_config(detected, &config);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "user_flow");
    }

    #[test]
    fn test_merge_with_config_auto_detected() {
        let detected = vec![CrudFlow::new("detected_flow".to_string())];

        let config = CrudFlowConfig::default();

        let result = CrudFlowDetector::merge_with_config(detected, &config);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "detected_flow");
    }

    #[test]
    fn test_crud_flow_get_all_extract_fields() {
        let mut flow = CrudFlow::new("test".to_string());
        flow.add_step(FlowStep::new("POST /test".to_string()).with_extract(vec!["id".to_string()]));
        flow.add_step(
            FlowStep::new("GET /test/{id}".to_string()).with_extract(vec!["uuid".to_string()]),
        );

        let fields = flow.get_all_extract_fields();
        assert!(fields.contains("id"));
        assert!(fields.contains("uuid"));
        assert_eq!(fields.len(), 2);
    }

    #[test]
    fn test_flow_step_with_merge_body() {
        let mut merge = HashMap::new();
        merge.insert("enabled".to_string(), serde_json::json!(false));
        merge.insert("name".to_string(), serde_json::json!("updated-name"));

        let step = FlowStep::new("PUT /resource/{id}".to_string())
            .with_use_body("resource_body".to_string())
            .with_merge_body(merge);

        assert_eq!(step.use_body, Some("resource_body".to_string()));
        assert_eq!(step.merge_body.get("enabled"), Some(&serde_json::json!(false)));
        assert_eq!(step.merge_body.get("name"), Some(&serde_json::json!("updated-name")));
    }

    #[test]
    fn test_flow_config_with_merge_body() {
        let yaml = r#"
flows:
  - name: "Update Flow"
    steps:
      - operation: "GET /resource/{id}"
        use_values:
          id: "resource_id"
        extract:
          - body: true
            as: resource_body
            exclude: ["_last_modified"]
        description: "Get resource"
      - operation: "PUT /resource/{id}"
        use_values:
          id: "resource_id"
        use_body: "resource_body"
        merge_body:
          enabled: false
          name: "updated"
        description: "Update resource"
"#;

        let config = CrudFlowConfig::from_yaml(yaml).expect("Should parse YAML");
        assert_eq!(config.flows.len(), 1);
        assert_eq!(config.flows[0].steps.len(), 2);

        let put_step = &config.flows[0].steps[1];
        assert_eq!(put_step.use_body, Some("resource_body".to_string()));
        assert!(!put_step.merge_body.is_empty());
        assert_eq!(put_step.merge_body.get("enabled"), Some(&serde_json::json!(false)));
        assert_eq!(put_step.merge_body.get("name"), Some(&serde_json::json!("updated")));
    }

    #[test]
    fn test_flow_step_with_inject_attacks() {
        let step = FlowStep::new("POST /resource".to_string())
            .with_inject_attacks(true)
            .with_attack_types(vec!["sqli".to_string(), "xss".to_string()]);

        assert!(step.inject_attacks);
        assert_eq!(step.attack_types, vec!["sqli".to_string(), "xss".to_string()]);
    }

    #[test]
    fn test_flow_config_with_inject_attacks() {
        let yaml = r#"
flows:
  - name: "Security Test Flow"
    steps:
      - operation: "POST /pool"
        inject_attacks: true
        attack_types:
          - sqli
          - xss
        description: "Create pool with attack payloads"
"#;

        let config = CrudFlowConfig::from_yaml(yaml).expect("Should parse YAML");
        assert_eq!(config.flows.len(), 1);
        assert_eq!(config.flows[0].steps.len(), 1);

        let step = &config.flows[0].steps[0];
        assert!(step.inject_attacks);
        assert_eq!(step.attack_types, vec!["sqli".to_string(), "xss".to_string()]);
    }
}