momus-core 0.7.11

Generic API test harness — AST types, assertion evaluation, plan runner, template resolution
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
/// Test plan generator engine.
///
/// Takes an `ApiModel` + `TestSpec` and produces a `TestPlan`.
/// This is the format-agnostic counterpart to the assertion evaluator:
/// the evaluator checks responses, the generator creates tests.
///
/// # Pipeline
///
/// ```text
/// ApiModel + TestSpec
//////     ├─ resolve_spec()       — flatten AllOf/OneOf combinators
///     ├─ generate_data()      — create resources with variations
///     ├─ generate_setup()     — POST resources to populate server
///     ├─ generate_crud()      — CRUD sequences with state passing
///     ├─ generate_search()    — search/filter tests
///     ├─ generate_negative()  — invalid input tests
///     ├─ generate_edge_case() — boundary/special char tests
///     ├─ generate_conformance() — profile/schema validation
///     └─ ...                  — operation, security, performance
/////////   TestPlan
/// ```
use crate::ast::*;
use anyhow::Result;
use serde::Serialize;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Resource generator trait
// ---------------------------------------------------------------------------

/// Generates valid resources for a specific API format.
///
/// Each converter (FHIR, OpenAPI, GraphQL, etc.) implements this trait
/// to provide format-specific resource generation, variation, and field
/// extraction. The `TestGenerator` engine calls these methods through
/// the trait, remaining completely format-agnostic.
pub trait ResourceGenerator {
    /// Generate a valid resource of the given type.
    ///
    /// The returned resource should be a valid JSON object conforming
    /// to the API definition for `resource_type`.
    fn generate(&self, resource_type: &str) -> Result<serde_json::Value>;

    /// Apply a variation to a resource.
    ///
    /// Called after `generate()` to produce resources with different
    /// characteristics (e.g., minimal fields, special characters,
    /// boundary values).
    fn vary(&self, resource: &mut serde_json::Value, variation: &DataVariation, index: u64);

    /// Extract searchable field values from a resource.
    ///
    /// Returns a map of field paths to string values that can be used
    /// in search/filter test URLs.
    fn extract_values(
        &self,
        resource_type: &str,
        resource: &serde_json::Value,
    ) -> HashMap<String, String>;
}

// ---------------------------------------------------------------------------
// Generated data
// ---------------------------------------------------------------------------

/// A single generated resource with its metadata.
#[derive(Debug, Clone, Serialize)]
pub struct GeneratedResource {
    /// Assigned resource ID.
    pub id: String,
    /// The generated JSON resource body.
    pub resource: serde_json::Value,
    /// Which variation was applied.
    pub variation: DataVariation,
}

/// All generated data for a test plan.
///
/// Holds the resources, extracted field values, and created IDs
/// that the sub-generators (CRUD, search, etc.) reference.
#[derive(Debug, Clone, Serialize)]
pub struct GeneratedData {
    /// Map of resource type to list of generated resources.
    pub resources: HashMap<String, Vec<GeneratedResource>>,
    /// Map of resource type to field values (from the first happy-path resource).
    pub field_values: HashMap<String, HashMap<String, String>>,
    /// Map of resource type to created ID (from the first happy-path resource).
    pub created_ids: HashMap<String, String>,
}

// ---------------------------------------------------------------------------
// Main entry point
// ---------------------------------------------------------------------------

/// Generate a complete `TestPlan` from an `ApiModel` and `TestSpec`.
///
/// This is the main entry point for the test generation engine.
///
/// # Arguments
///
/// * `api` - The format-agnostic API model (produced by any converter).
/// * `spec` - The test specification (what tests to generate).
/// * `generator` - The format-specific resource generator.
///
/// # Returns
///
/// A complete `TestPlan` with setup steps, CRUD sequences, search tests,
/// negative tests, edge case tests, and conformance tests.
pub fn generate_test_plan(
    api: &ApiModel,
    spec: &TestSpec,
    generator: &dyn ResourceGenerator,
) -> Result<TestPlan> {
    // 1. Resolve the test spec into a flat list of leaf specs
    let leaf_specs = resolve_spec(spec);

    // 2. Extract DataSpec and generate data
    let data_spec = extract_data_spec(&leaf_specs);
    let data = generate_data(api, &data_spec, generator)?;

    // 3. Generate setup steps from the data
    let setup_steps = generate_setup_steps(api, &data);

    // 4. Generate test steps from each leaf spec
    let mut steps = Vec::new();

    for leaf in &leaf_specs {
        match leaf {
            TestSpec::Crud(crud_spec) => {
                steps.extend(generate_crud_tests(api, crud_spec, &data, generator)?);
            }
            TestSpec::Search(search_spec) => {
                steps.extend(generate_search_tests(api, search_spec, &data));
            }
            TestSpec::Negative(neg_spec) => {
                steps.extend(generate_negative_tests(api, neg_spec));
            }
            TestSpec::EdgeCase(edge_spec) => {
                steps.extend(generate_edge_case_tests(api, edge_spec, &data, generator)?);
            }
            TestSpec::Conformance(conf_spec) => {
                steps.extend(generate_conformance_tests(api, conf_spec));
            }
            TestSpec::Operation(op_spec) => {
                steps.extend(generate_operation_tests(api, op_spec));
            }
            TestSpec::Security(sec_spec) => {
                steps.extend(generate_security_tests(api, sec_spec));
            }
            TestSpec::Performance(perf_spec) => {
                steps.extend(generate_performance_tests(api, perf_spec));
            }
            // Already handled above
            TestSpec::Data(_) | TestSpec::AllOf(_) | TestSpec::OneOf(_) => {}
        }
    }

    let plan_name = format!("{} — generated test plan", api.name);

    Ok(TestPlan {
        name: plan_name,
        base_url: String::new(),
        default_headers: HashMap::new(),
        steps,
        setup: setup_steps,
        teardown: vec![],
    })
}

// ---------------------------------------------------------------------------
// Spec resolution
// ---------------------------------------------------------------------------

/// Resolve a `TestSpec` tree into a flat list of leaf specs.
///
/// - `AllOf` is flattened (all children are included).
/// - `OneOf` picks the first child (useful for A/B test selection).
/// - Leaf specs (Data, Crud, Search, etc.) are returned as-is.
fn resolve_spec(spec: &TestSpec) -> Vec<&TestSpec> {
    let mut result = Vec::new();
    resolve_spec_inner(spec, &mut result);
    result
}

fn resolve_spec_inner<'a>(spec: &'a TestSpec, result: &mut Vec<&'a TestSpec>) {
    match spec {
        TestSpec::AllOf(children) => {
            for child in children {
                resolve_spec_inner(child, result);
            }
        }
        TestSpec::OneOf(children) => {
            if let Some(first) = children.first() {
                resolve_spec_inner(first, result);
            }
        }
        _ => {
            result.push(spec);
        }
    }
}

/// Extract the `DataSpec` from a list of leaf specs.
/// Returns `DataSpec::default()` if none is found.
fn extract_data_spec(specs: &[&TestSpec]) -> DataSpec {
    for spec in specs {
        if let TestSpec::Data(ds) = spec {
            return ds.clone();
        }
    }
    DataSpec::default()
}

// ---------------------------------------------------------------------------
// Data generation
// ---------------------------------------------------------------------------

/// Generate resources for each resource type in the API model.
///
/// For each resource type, generates `data_spec.count` resources with
/// the specified variations. The first resource is always the happy-path
/// (base) resource; subsequent resources apply variations.
pub fn generate_data(
    api: &ApiModel,
    data_spec: &DataSpec,
    generator: &dyn ResourceGenerator,
) -> Result<GeneratedData> {
    let resource_count = api.resources.len();
    let mut resources: HashMap<String, Vec<GeneratedResource>> =
        HashMap::with_capacity(resource_count);
    let mut field_values: HashMap<String, HashMap<String, String>> =
        HashMap::with_capacity(resource_count);
    let mut created_ids: HashMap<String, String> = HashMap::with_capacity(resource_count);

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let count = data_spec.count;
        let mut type_resources = Vec::with_capacity(count as usize);

        // Generate the base (happy-path) resource
        let base = generator.generate(rtype)?;

        for i in 0..count {
            let idx = i + 1;
            let id = format!("{}-{:03}", rtype.to_lowercase(), idx);
            let mut resource = base.clone();

            // Stamp the ID
            if let Some(obj) = resource.as_object_mut() {
                obj.insert("id".to_string(), serde_json::json!(&id));
            }

            // Determine which variation to apply
            let variation = if idx == 1 {
                DataVariation::HappyPath
            } else {
                let var_idx = ((idx - 2) as usize) % data_spec.variations.len();
                data_spec.variations[var_idx].clone()
            };

            // Apply the variation (skip for the first resource)
            if idx > 1 {
                generator.vary(&mut resource, &variation, idx);
            }

            type_resources.push(GeneratedResource {
                id,
                resource,
                variation,
            });
        }

        // Extract field values from the first (happy-path) resource
        if let Some(first) = type_resources.first() {
            let values = generator.extract_values(rtype, &first.resource);
            field_values.insert(rtype.clone(), values);
            created_ids.insert(rtype.clone(), first.id.clone());
        }

        resources.insert(rtype.clone(), type_resources);
    }

    Ok(GeneratedData {
        resources,
        field_values,
        created_ids,
    })
}

// ---------------------------------------------------------------------------
// Setup steps
// ---------------------------------------------------------------------------

/// Generate setup steps that POST generated resources to the server.
///
/// Each resource is POSTed in dependency order (if the API model specifies
/// a creation order) and saved under a named reference for downstream use.
pub fn generate_setup_steps(api: &ApiModel, data: &GeneratedData) -> Vec<Step> {
    // Estimate total steps: sum of all resources across all types
    let estimated: usize = api
        .resources
        .iter()
        .filter_map(|r| data.resources.get(&r.name))
        .map(|v| v.len())
        .sum();
    let mut steps = Vec::with_capacity(estimated);

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        if let Some(type_resources) = data.resources.get(rtype) {
            for (i, gr) in type_resources.iter().enumerate() {
                let idx = i + 1;
                let save_name = format!("seed_{rtype_lower}_{idx}");

                let step = RequestStep {
                    name: format!("setup-create-{rtype_lower}-{idx}"),
                    method: Method::Post,
                    url: format!("/{rtype}"),
                    headers: {
                        let mut h = HashMap::new();
                        h.insert("Content-Type".to_string(), "application/json".to_string());
                        h
                    },
                    body: Some(gr.resource.clone()),
                    assert: vec![Assertion::Status(201)],
                    save_as: save_name,
                    soft_fail: false,
                };
                steps.push(Step::Request(step));
            }
        }
    }

    steps
}

// ---------------------------------------------------------------------------
// CRUD test generation
// ---------------------------------------------------------------------------

/// Generate CRUD test sequences from the API model and generated data.
///
/// For each resource type that has create/read/update/delete operations,
/// generates a `Step::Sequence` that chains them together with state
/// passing via `{{steps.<name>.*}}` template references.
fn generate_crud_tests(
    api: &ApiModel,
    spec: &CrudSpec,
    data: &GeneratedData,
    _generator: &dyn ResourceGenerator,
) -> Result<Vec<Step>> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();
        let save_name = format!("seed_{rtype_lower}_1");

        // Check which operations are declared
        let has_create = resource_model
            .operations
            .iter()
            .any(|op| op.name == "create" && spec.create);
        let has_read = resource_model
            .operations
            .iter()
            .any(|op| op.name == "read" && spec.read);
        let has_vread = resource_model
            .operations
            .iter()
            .any(|op| op.name == "vread" && spec.vread);
        let has_update = resource_model
            .operations
            .iter()
            .any(|op| op.name == "update" && spec.update);
        let has_delete = resource_model
            .operations
            .iter()
            .any(|op| op.name == "delete" && spec.delete);
        let has_patch = resource_model
            .operations
            .iter()
            .any(|op| op.name == "patch" && spec.patch);
        let has_history_instance = resource_model
            .operations
            .iter()
            .any(|op| op.name == "history-instance" && spec.history_instance);
        let has_history_type = resource_model
            .operations
            .iter()
            .any(|op| op.name == "history-type" && spec.history_type);

        if !has_create && !has_read && !has_update && !has_delete {
            continue;
        }

        let mut crud_steps: Vec<Step> = Vec::new();

        // Create step
        if has_create {
            let body = data
                .resources
                .get(rtype)
                .and_then(|res| res.first())
                .map(|gr| gr.resource.clone());

            crud_steps.push(Step::Request(RequestStep {
                name: format!("create-{rtype_lower}"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body,
                assert: vec![Assertion::Status(201)],
                save_as: save_name.clone(),
                soft_fail: false,
            }));
        }

        // Read step
        if has_read {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("read-{rtype_lower}"),
                method: Method::Get,
                url: format!("/{rtype}/{{steps.{save_name}.id}}"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // Update step
        if has_update {
            let body = data
                .resources
                .get(rtype)
                .and_then(|res| res.first())
                .map(|gr| gr.resource.clone());

            crud_steps.push(Step::Request(RequestStep {
                name: format!("update-{rtype_lower}"),
                method: Method::Put,
                url: format!("/{rtype}/{{steps.{save_name}.id}}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // Patch step
        if has_patch {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("patch-{rtype_lower}"),
                method: Method::Patch,
                url: format!("/{rtype}/{{steps.{save_name}.id}}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert(
                        "Content-Type".to_string(),
                        "application/json-patch+json".to_string(),
                    );
                    h
                },
                body: Some(serde_json::json!([{
                    "op": "replace",
                    "path": "/active",
                    "value": true
                }])),
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // Vread step (version read)
        if has_vread {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("vread-{rtype_lower}"),
                method: Method::Get,
                url: format!("/{rtype}/{{steps.{save_name}.id}}/_history/1"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // History instance step
        if has_history_instance {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("history-instance-{rtype_lower}"),
                method: Method::Get,
                url: format!("/{rtype}/{{steps.{save_name}.id}}/_history"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // History type step
        if has_history_type {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("history-type-{rtype_lower}"),
                method: Method::Get,
                url: format!("/{rtype}/_history"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // Delete step — last in sequence
        if has_delete {
            crud_steps.push(Step::Request(RequestStep {
                name: format!("delete-{rtype_lower}"),
                method: Method::Delete,
                url: format!("/{rtype}/{{steps.{save_name}.id}}"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(204)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        if !crud_steps.is_empty() {
            if spec.chain {
                steps.push(Step::Sequence(SequenceStep {
                    name: format!("{rtype_lower}-crud"),
                    steps: crud_steps,
                    continue_on_failure: true,
                }));
            } else {
                steps.extend(crud_steps);
            }
        }
    }

    Ok(steps)
}

// ---------------------------------------------------------------------------
// Search test generation
// ---------------------------------------------------------------------------

/// Generate search/filter tests from the API model and generated data.
///
/// For each resource type with search parameters, generates:
/// - Single-parameter search tests with concrete values
/// - Modifier tests (:exact, :contains, :missing)
/// - Prefix tests (gt, lt, ge, le)
/// - Combined parameter tests
/// - Negative search tests (values that should return empty)
fn generate_search_tests(api: &ApiModel, spec: &SearchSpec, data: &GeneratedData) -> Vec<Step> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        // Check if search-type is declared
        let has_search = resource_model
            .operations
            .iter()
            .any(|op| op.name == "search-type");

        if !has_search || resource_model.search_params.is_empty() {
            continue;
        }

        let values = data.field_values.get(rtype);
        let created_id = data.created_ids.get(rtype);

        for sp in &resource_model.search_params {
            // Resolve a concrete value for this search parameter
            let resolved_value = resolve_search_value(sp, values, created_id);

            // --- Single param search ---
            if spec.single_param
                && let Some(ref val) = resolved_value
            {
                steps.push(Step::Request(RequestStep {
                    name: format!("search-{}-{}", rtype_lower, sp.name),
                    method: Method::Get,
                    url: format!("/{}?{}={}", rtype, sp.name, url_encode(val)),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![
                        Assertion::Status(200),
                        Assertion::JsonPath {
                            path: "$.resourceType".to_string(),
                            predicate: JsonPredicate::Eq(serde_json::json!("Bundle")),
                        },
                    ],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }

            // --- Modifier tests ---
            if spec.modifiers {
                for modifier in &sp.modifiers {
                    if let Some(ref val) = resolved_value {
                        steps.push(Step::Request(RequestStep {
                            name: format!("search-{}-{}-{}", rtype_lower, sp.name, modifier),
                            method: Method::Get,
                            url: format!("/{}?{}:{}={}", rtype, sp.name, modifier, url_encode(val)),
                            headers: HashMap::new(),
                            body: None,
                            assert: vec![Assertion::Status(200)],
                            save_as: String::new(),
                            soft_fail: false,
                        }));
                    }
                }

                // Always add :missing=true and :missing=false tests
                steps.push(Step::Request(RequestStep {
                    name: format!("search-{}-{}-missing-true", rtype_lower, sp.name),
                    method: Method::Get,
                    url: format!("/{}?{}:missing=true", rtype, sp.name),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![Assertion::Status(200)],
                    save_as: String::new(),
                    soft_fail: false,
                }));

                steps.push(Step::Request(RequestStep {
                    name: format!("search-{}-{}-missing-false", rtype_lower, sp.name),
                    method: Method::Get,
                    url: format!("/{}?{}:missing=false", rtype, sp.name),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![Assertion::Status(200)],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }

            // --- Prefix tests ---
            if spec.prefixes {
                for prefix in &sp.prefixes {
                    if let Some(ref val) = resolved_value {
                        steps.push(Step::Request(RequestStep {
                            name: format!("search-{}-{}-{}", rtype_lower, sp.name, prefix),
                            method: Method::Get,
                            url: format!("/{}?{}={}{}", rtype, sp.name, prefix, url_encode(val)),
                            headers: HashMap::new(),
                            body: None,
                            assert: vec![Assertion::Status(200)],
                            save_as: String::new(),
                            soft_fail: false,
                        }));
                    }
                }
            }
        }

        // --- Combined param tests ---
        if spec.combined_params && resource_model.search_params.len() >= 2 {
            for i in 0..resource_model.search_params.len() {
                for j in (i + 1)..resource_model.search_params.len() {
                    let p1 = &resource_model.search_params[i];
                    let p2 = &resource_model.search_params[j];
                    let v1 = resolve_search_value(p1, values, created_id);
                    let v2 = resolve_search_value(p2, values, created_id);

                    if let (Some(ref v1), Some(ref v2)) = (v1, v2) {
                        steps.push(Step::Request(RequestStep {
                            name: format!("search-{}-{}-{}-combo", rtype_lower, p1.name, p2.name),
                            method: Method::Get,
                            url: format!(
                                "/{}?{}={}&{}={}",
                                rtype,
                                p1.name,
                                url_encode(v1),
                                p2.name,
                                url_encode(v2)
                            ),
                            headers: HashMap::new(),
                            body: None,
                            assert: vec![Assertion::Status(200)],
                            save_as: String::new(),
                            soft_fail: false,
                        }));
                    }
                }
            }
        }

        // --- Negative search tests ---
        for neg_val in &spec.negative_values {
            if let Some(first_param) = resource_model.search_params.first() {
                steps.push(Step::Request(RequestStep {
                    name: format!(
                        "search-{}-{}-negative-{}",
                        rtype_lower, first_param.name, neg_val
                    ),
                    method: Method::Get,
                    url: format!("/{}?{}={}", rtype, first_param.name, url_encode(neg_val)),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![Assertion::Status(200)],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }
        }

        // --- Result param tests ---
        for result_param in &spec.result_params {
            steps.push(Step::Request(RequestStep {
                name: format!(
                    "search-{}-{}",
                    rtype_lower,
                    result_param.replace('=', "_").replace(':', "-")
                ),
                method: Method::Get,
                url: format!("/{rtype}?{result_param}"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // --- _include tests ---
        if spec.include {
            for include in &resource_model.search_include {
                steps.push(Step::Request(RequestStep {
                    name: format!("search-{rtype_lower}-include-{include}"),
                    method: Method::Get,
                    url: format!("/{rtype}?_include={include}"),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![Assertion::Status(200)],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }
        }

        // --- _revinclude tests ---
        if spec.revinclude {
            for revinclude in &resource_model.search_revinclude {
                steps.push(Step::Request(RequestStep {
                    name: format!("search-{rtype_lower}-revinclude-{revinclude}"),
                    method: Method::Get,
                    url: format!("/{rtype}?_revinclude={revinclude}"),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![Assertion::Status(200)],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }
        }
    }

    steps
}

/// Resolve a search parameter to a concrete value from generated data.
fn resolve_search_value(
    sp: &SearchParamModel,
    field_values: Option<&HashMap<String, String>>,
    created_id: Option<&String>,
) -> Option<String> {
    // Special case: _id always uses the created resource ID
    if sp.name == "_id" {
        return created_id.cloned();
    }

    // For reference params, use the created ID of the target type
    if sp.param_type == "reference" {
        // Try to find a matching resource type from the param name
        // e.g., "patient" → "Patient", "organization" → "Organization"
        let target_type = capitalize_first(&sp.name);
        // The caller should have populated created_ids with the right types
        return created_id.map(|id| format!("{target_type}/{id}"));
    }

    // For other param types, look up from field values
    if let Some(values) = field_values {
        // Try exact field path match first
        let exact_key = format!("{}.{}", sp.name, sp.param_type);
        if let Some(val) = values.get(&exact_key) {
            return Some(val.clone());
        }

        // Try common field path patterns
        let patterns = match sp.param_type.as_str() {
            "string" => vec![sp.name.clone()],
            "token" => vec![
                format!("{}.coding[0].code", sp.name),
                format!("{}.code", sp.name),
                sp.name.clone(),
            ],
            "date" | "dateTime" => vec![sp.name.clone()],
            "number" => vec![sp.name.clone()],
            _ => vec![sp.name.clone()],
        };

        for pattern in &patterns {
            if let Some(val) = values.get(pattern) {
                return Some(val.clone());
            }
        }
    }

    None
}

fn capitalize_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().to_string() + chars.as_str(),
        None => String::new(),
    }
}

fn url_encode(s: &str) -> String {
    // Simple URL encoding — only encode characters that are problematic in URLs
    s.replace(' ', "%20")
        .replace('&', "%26")
        .replace('=', "%3D")
        .replace('?', "%3F")
        .replace('#', "%23")
}

// ---------------------------------------------------------------------------
// Negative test generation
// ---------------------------------------------------------------------------

/// Generate negative tests from the API model.
///
/// Tests operations that should fail:
/// - Undeclared interactions (operations not in the spec)
/// - Invalid request bodies (missing required fields, wrong types)
/// - Malformed requests (invalid JSON, wrong Content-Type)
fn generate_negative_tests(api: &ApiModel, spec: &NegativeSpec) -> Vec<Step> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        // --- Undeclared interaction tests ---
        if spec.undeclared_interactions {
            let declared: Vec<&str> = resource_model
                .operations
                .iter()
                .map(|op| op.name.as_str())
                .collect();

            // Test each standard interaction that isn't declared
            for &interaction in &["read", "search-type", "create", "update", "delete"] {
                if !declared.contains(&interaction) {
                    let (method, url, body) = match interaction {
                        "read" => ("GET", format!("/{rtype}/nonexistent"), None),
                        "search-type" => ("GET", format!("/{rtype}?nonexistent=true"), None),
                        "create" => (
                            "POST",
                            format!("/{rtype}"),
                            Some(serde_json::json!({"resourceType": rtype})),
                        ),
                        "update" => (
                            "PUT",
                            format!("/{rtype}/nonexistent"),
                            Some(serde_json::json!({"resourceType": rtype})),
                        ),
                        "delete" => ("DELETE", format!("/{rtype}/nonexistent"), None),
                        _ => continue,
                    };

                    let method_enum = match method {
                        "GET" => Method::Get,
                        "POST" => Method::Post,
                        "PUT" => Method::Put,
                        "DELETE" => Method::Delete,
                        _ => Method::Get,
                    };

                    steps.push(Step::Request(RequestStep {
                        name: format!("negative-{rtype_lower}-undeclared-{interaction}"),
                        method: method_enum,
                        url,
                        headers: HashMap::new(),
                        body,
                        // Expected status 0 = sentinel: accept non-2xx or 200+Bundle
                        assert: vec![Assertion::StatusIn(vec![400, 401, 403, 404, 405, 422, 501])],
                        save_as: String::new(),
                        soft_fail: false,
                    }));
                }
            }
        }

        // --- Invalid body tests ---
        if spec.invalid_bodies {
            // Test with empty body
            steps.push(Step::Request(RequestStep {
                name: format!("negative-{rtype_lower}-empty-body"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(serde_json::json!({})),
                assert: vec![Assertion::StatusIn(vec![400, 422])],
                save_as: String::new(),
                soft_fail: false,
            }));

            // Test with wrong resource type
            steps.push(Step::Request(RequestStep {
                name: format!("negative-{rtype_lower}-wrong-type"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(serde_json::json!({"resourceType": "Unknown"})),
                assert: vec![Assertion::StatusIn(vec![400, 422])],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // --- Malformed request tests ---
        if spec.malformed_requests {
            // Test with invalid JSON
            // (This would need to be a raw HTTP request — skip for now)
            // Test with wrong Content-Type
            steps.push(Step::Request(RequestStep {
                name: format!("negative-{rtype_lower}-wrong-content-type"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/xml".to_string());
                    h
                },
                body: Some(serde_json::json!({"resourceType": rtype})),
                assert: vec![Assertion::StatusIn(vec![400, 415, 422])],
                save_as: String::new(),
                soft_fail: false,
            }));
        }
    }

    steps
}

// ---------------------------------------------------------------------------
// Edge case test generation
// ---------------------------------------------------------------------------

/// Generate edge case tests from the API model.
///
/// Tests boundary conditions, special characters, and other edge cases.
fn generate_edge_case_tests(
    api: &ApiModel,
    spec: &EdgeCaseSpec,
    _data: &GeneratedData,
    generator: &dyn ResourceGenerator,
) -> Result<Vec<Step>> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        // --- Special characters test ---
        if spec.special_characters
            && let Ok(mut resource) = generator.generate(rtype)
        {
            generator.vary(&mut resource, &DataVariation::SpecialChars, 99);
            if let Some(obj) = resource.as_object_mut() {
                obj.insert("id".to_string(), serde_json::json!("edge-special-chars"));
            }

            steps.push(Step::Request(RequestStep {
                name: format!("edge-{rtype_lower}-special-chars"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(resource),
                assert: vec![Assertion::Status(201)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // --- Boundary values test ---
        if spec.boundary_values
            && let Ok(mut resource) = generator.generate(rtype)
        {
            generator.vary(
                &mut resource,
                &DataVariation::Boundary {
                    field: String::new(),
                },
                99,
            );
            if let Some(obj) = resource.as_object_mut() {
                obj.insert("id".to_string(), serde_json::json!("edge-boundary"));
            }

            steps.push(Step::Request(RequestStep {
                name: format!("edge-{rtype_lower}-boundary"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(resource),
                assert: vec![Assertion::Status(201)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // --- Dangling reference test ---
        if spec.dangling_references
            && let Ok(mut resource) = generator.generate(rtype)
        {
            // Add a reference to a non-existent resource
            if let Some(obj) = resource.as_object_mut() {
                obj.insert(
                    "subject".to_string(),
                    serde_json::json!({
                        "reference": "Patient/nonexistent-000"
                    }),
                );
                obj.insert("id".to_string(), serde_json::json!("edge-dangling-ref"));
            }

            steps.push(Step::Request(RequestStep {
                name: format!("edge-{rtype_lower}-dangling-ref"),
                method: Method::Post,
                url: format!("/{rtype}"),
                headers: {
                    let mut h = HashMap::new();
                    h.insert("Content-Type".to_string(), "application/json".to_string());
                    h
                },
                body: Some(resource),
                // Server may accept or reject dangling refs — accept either
                assert: vec![Assertion::StatusIn(vec![201, 202, 400, 422])],
                save_as: String::new(),
                soft_fail: false,
            }));
        }
    }

    Ok(steps)
}

/// Generate conformance tests from the API model.
///
/// Validates that responses conform to profile/schema definitions
/// and that mustSupport fields are present.
fn generate_conformance_tests(api: &ApiModel, spec: &ConformanceSpec) -> Vec<Step> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        // Conformance: search with _count=1 and verify profile
        if spec.profile_validation
            && let Some(profile_url) = &resource_model.profile_url
        {
            steps.push(Step::Request(RequestStep {
                name: format!("conformance-{rtype_lower}-profile"),
                method: Method::Get,
                url: format!("/{rtype}?_count=1"),
                headers: HashMap::new(),
                body: None,
                assert: vec![
                    Assertion::Status(200),
                    Assertion::JsonPath {
                        path: "$.entry[0].resource.meta.profile[0]".to_string(),
                        predicate: JsonPredicate::Eq(serde_json::json!(profile_url)),
                    },
                ],
                save_as: String::new(),
                soft_fail: false,
            }));
        }

        // Conformance: mustSupport tests for each supported profile
        if spec.must_support {
            for profile_url in &resource_model.supported_profiles {
                let profile_name = profile_url.rsplit('/').next().unwrap_or(profile_url);
                steps.push(Step::Request(RequestStep {
                    name: format!("conformance-{rtype_lower}-mustsupport-{profile_name}"),
                    method: Method::Get,
                    url: format!("/{rtype}?_count=1"),
                    headers: HashMap::new(),
                    body: None,
                    assert: vec![
                        Assertion::Status(200),
                        Assertion::JsonPath {
                            path: "$.entry[0].resource.meta.profile".to_string(),
                            predicate: JsonPredicate::Every(Box::new(JsonPredicate::Exists)),
                        },
                    ],
                    save_as: String::new(),
                    soft_fail: false,
                }));
            }
        }
    }

    steps
}

// ---------------------------------------------------------------------------
// Operation test generation
// ---------------------------------------------------------------------------

/// Generate operation/action tests from the API model.
fn generate_operation_tests(api: &ApiModel, _spec: &OperationSpec) -> Vec<Step> {
    let mut steps = Vec::new();

    for resource_model in &api.resources {
        let rtype = &resource_model.name;
        let rtype_lower = rtype.to_lowercase();

        for op in &resource_model.operations {
            // Skip standard CRUD/search operations — they're handled elsewhere
            if matches!(
                op.name.as_str(),
                "create" | "read" | "update" | "delete" | "patch" | "search-type"
            ) {
                continue;
            }

            steps.push(Step::Request(RequestStep {
                name: format!("op-{}-{}", rtype_lower, op.name),
                method: Method::Get,
                url: format!("/{rtype}/{name}", rtype = rtype, name = op.name),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }
    }

    steps
}

// ---------------------------------------------------------------------------
// Security test generation
// ---------------------------------------------------------------------------

/// Generate security tests from the API model.
fn generate_security_tests(_api: &ApiModel, _spec: &SecuritySpec) -> Vec<Step> {
    // Security tests are format-specific and require knowledge of auth schemes.
    // This is a placeholder for future implementation.
    Vec::new()
}

// ---------------------------------------------------------------------------
// Performance test generation
// ---------------------------------------------------------------------------

/// Generate performance tests from the API model.
fn generate_performance_tests(api: &ApiModel, spec: &PerformanceSpec) -> Vec<Step> {
    let mut steps = Vec::new();

    if spec.pagination {
        for resource_model in &api.resources {
            let rtype = &resource_model.name;
            let rtype_lower = rtype.to_lowercase();

            // Test _count=1 pagination
            steps.push(Step::Request(RequestStep {
                name: format!("perf-{rtype_lower}-count-1"),
                method: Method::Get,
                url: format!("/{rtype}?_count=1"),
                headers: HashMap::new(),
                body: None,
                assert: vec![Assertion::Status(200)],
                save_as: String::new(),
                soft_fail: false,
            }));
        }
    }

    steps
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// A mock resource generator for testing.
    struct MockGenerator;

    impl ResourceGenerator for MockGenerator {
        fn generate(&self, resource_type: &str) -> Result<serde_json::Value> {
            Ok(serde_json::json!({
                "resourceType": resource_type,
                "name": "Test Resource",
                "status": "active",
                "active": true
            }))
        }

        fn vary(&self, resource: &mut serde_json::Value, variation: &DataVariation, _index: u64) {
            match variation {
                DataVariation::Minimal => {
                    // Remove optional fields
                    if let Some(obj) = resource.as_object_mut() {
                        obj.remove("name");
                    }
                }
                DataVariation::SpecialChars => {
                    if let Some(obj) = resource.as_object_mut() {
                        obj.insert(
                            "name".to_string(),
                            serde_json::json!("<script>alert('xss')</script> & \"'<>"),
                        );
                    }
                }
                DataVariation::Boundary { .. } => {
                    if let Some(obj) = resource.as_object_mut() {
                        obj.insert("name".to_string(), serde_json::json!(""));
                    }
                }
                DataVariation::DuplicateValue { .. } => {}
                DataVariation::MissingField { field } => {
                    if let Some(obj) = resource.as_object_mut() {
                        obj.remove(field);
                    }
                }
                DataVariation::HappyPath | DataVariation::ToBeDeleted => {}
            }
        }

        fn extract_values(
            &self,
            _resource_type: &str,
            resource: &serde_json::Value,
        ) -> HashMap<String, String> {
            let mut values = HashMap::new();
            if let Some(name) = resource.get("name").and_then(|v| v.as_str()) {
                values.insert("name".to_string(), name.to_string());
            }
            if let Some(status) = resource.get("status").and_then(|v| v.as_str()) {
                values.insert("status".to_string(), status.to_string());
            }
            values
        }
    }

    fn make_test_api() -> ApiModel {
        ApiModel {
            name: "Test API".to_string(),
            resources: vec![ResourceModel {
                name: "Patient".to_string(),
                profile_url: Some("http://hl7.org/fhir/StructureDefinition/Patient".to_string()),
                operations: vec![
                    OperationModel {
                        name: "create".to_string(),
                        method: "POST".to_string(),
                        path: "/Patient".to_string(),
                        request_body: None,
                        responses: vec![ResponseModel {
                            status_code: 201,
                            content_type: None,
                            schema: None,
                        }],
                    },
                    OperationModel {
                        name: "read".to_string(),
                        method: "GET".to_string(),
                        path: "/Patient/{id}".to_string(),
                        request_body: None,
                        responses: vec![ResponseModel {
                            status_code: 200,
                            content_type: None,
                            schema: None,
                        }],
                    },
                    OperationModel {
                        name: "update".to_string(),
                        method: "PUT".to_string(),
                        path: "/Patient/{id}".to_string(),
                        request_body: None,
                        responses: vec![ResponseModel {
                            status_code: 200,
                            content_type: None,
                            schema: None,
                        }],
                    },
                    OperationModel {
                        name: "delete".to_string(),
                        method: "DELETE".to_string(),
                        path: "/Patient/{id}".to_string(),
                        request_body: None,
                        responses: vec![ResponseModel {
                            status_code: 204,
                            content_type: None,
                            schema: None,
                        }],
                    },
                    OperationModel {
                        name: "search-type".to_string(),
                        method: "GET".to_string(),
                        path: "/Patient".to_string(),
                        request_body: None,
                        responses: vec![ResponseModel {
                            status_code: 200,
                            content_type: None,
                            schema: None,
                        }],
                    },
                ],
                search_params: vec![
                    SearchParamModel {
                        name: "name".to_string(),
                        param_type: "string".to_string(),
                        modifiers: vec!["exact".to_string(), "contains".to_string()],
                        prefixes: vec![],
                    },
                    SearchParamModel {
                        name: "birthdate".to_string(),
                        param_type: "date".to_string(),
                        modifiers: vec![],
                        prefixes: vec!["eq".to_string(), "gt".to_string(), "lt".to_string()],
                    },
                ],
                search_include: vec![],
                search_revinclude: vec![],
                supported_profiles: vec![],
            }],
        }
    }

    #[test]
    fn test_resolve_spec_all_of() {
        let spec = TestSpec::AllOf(vec![
            TestSpec::Data(DataSpec::default()),
            TestSpec::Crud(CrudSpec::default()),
            TestSpec::Search(SearchSpec::default()),
        ]);

        let resolved = resolve_spec(&spec);
        assert_eq!(resolved.len(), 3);
    }

    #[test]
    fn test_resolve_spec_one_of() {
        let spec = TestSpec::OneOf(vec![
            TestSpec::Crud(CrudSpec::default()),
            TestSpec::Search(SearchSpec::default()),
        ]);

        let resolved = resolve_spec(&spec);
        assert_eq!(resolved.len(), 1);
        assert!(matches!(resolved[0], TestSpec::Crud(_)));
    }

    #[test]
    fn test_resolve_spec_nested() {
        let spec = TestSpec::AllOf(vec![
            TestSpec::Data(DataSpec::default()),
            TestSpec::AllOf(vec![
                TestSpec::Crud(CrudSpec::default()),
                TestSpec::Search(SearchSpec::default()),
            ]),
        ]);

        let resolved = resolve_spec(&spec);
        assert_eq!(resolved.len(), 3);
    }

    #[test]
    fn test_extract_data_spec() {
        let data_spec = TestSpec::Data(DataSpec {
            count: 5,
            variations: vec![DataVariation::HappyPath, DataVariation::Minimal],
        });
        let crud_spec = TestSpec::Crud(CrudSpec::default());
        let specs = vec![&crud_spec as &TestSpec, &data_spec as &TestSpec];

        let ds = extract_data_spec(&specs);
        assert_eq!(ds.count, 5);
        assert_eq!(ds.variations.len(), 2);
    }

    #[test]
    fn test_extract_data_spec_default() {
        let crud_spec = TestSpec::Crud(CrudSpec::default());
        let specs: Vec<&TestSpec> = vec![&crud_spec];
        let ds = extract_data_spec(&specs);
        assert_eq!(ds.count, 3);
    }

    #[test]
    fn test_generate_data() {
        let api = make_test_api();
        let spec = DataSpec::default();
        let generator = MockGenerator;

        let data = generate_data(&api, &spec, &generator).unwrap();

        assert!(data.resources.contains_key("Patient"));
        let patient_resources = data.resources.get("Patient").unwrap();
        assert_eq!(patient_resources.len(), 3);

        // First resource should be happy path
        assert!(matches!(
            patient_resources[0].variation,
            DataVariation::HappyPath
        ));

        // Should have field values
        assert!(data.field_values.contains_key("Patient"));
        assert!(data.created_ids.contains_key("Patient"));
        assert_eq!(data.created_ids.get("Patient").unwrap(), "patient-001");
    }

    #[test]
    fn test_generate_setup_steps() {
        let api = make_test_api();
        let spec = DataSpec::default();
        let generator = MockGenerator;
        let data = generate_data(&api, &spec, &generator).unwrap();

        let steps = generate_setup_steps(&api, &data);
        assert_eq!(steps.len(), 3); // 3 resources

        for step in &steps {
            match step {
                Step::Request(req) => {
                    assert_eq!(req.method, Method::Post);
                    assert!(req.url.starts_with("/Patient"));
                    assert!(req.body.is_some());
                    assert!(!req.save_as.is_empty());
                }
                _ => panic!("Expected Request step"),
            }
        }
    }

    #[test]
    fn test_generate_crud_tests() {
        let api = make_test_api();
        let spec = CrudSpec::default();
        let data = {
            let data_spec = DataSpec::default();
            let generator = MockGenerator;
            generate_data(&api, &data_spec, &generator).unwrap()
        };
        let generator = MockGenerator;

        let steps = generate_crud_tests(&api, &spec, &data, &generator).unwrap();
        assert_eq!(steps.len(), 1); // 1 sequence

        match &steps[0] {
            Step::Sequence(seq) => {
                assert_eq!(seq.name, "patient-crud");
                // Should have create, read, update, delete
                assert_eq!(seq.steps.len(), 4);
            }
            _ => panic!("Expected Sequence step"),
        }
    }

    #[test]
    fn test_generate_search_tests() {
        let api = make_test_api();
        let spec = SearchSpec {
            single_param: true,
            modifiers: true,
            prefixes: true,
            combined_params: false,
            chained: false,
            include: false,
            revinclude: false,
            result_params: vec!["_count=1".to_string()],
            negative_values: vec!["NONEXISTENT".to_string()],
        };
        let data = {
            let data_spec = DataSpec::default();
            let generator = MockGenerator;
            generate_data(&api, &data_spec, &generator).unwrap()
        };

        let steps = generate_search_tests(&api, &spec, &data);
        // name (single + exact + contains + missing:true + missing:false) = 5
        // birthdate (single + eq + gt + lt) = 4
        // _count=1 = 1
        // negative = 1
        assert!(!steps.is_empty());
    }

    #[test]
    fn test_generate_negative_tests() {
        let api = make_test_api();
        let spec = NegativeSpec {
            undeclared_interactions: true,
            invalid_bodies: true,
            malformed_requests: true,
            auth_errors: false,
            version_conflicts: false,
        };

        let steps = generate_negative_tests(&api, &spec);
        // All interactions are declared, so no undeclared tests
        // But we should have invalid body tests
        assert!(!steps.is_empty());
    }

    #[test]
    fn test_generate_full_plan() {
        let api = make_test_api();
        let spec = TestSpec::AllOf(vec![
            TestSpec::Data(DataSpec::default()),
            TestSpec::Crud(CrudSpec::default()),
            TestSpec::Search(SearchSpec {
                single_param: true,
                modifiers: true,
                prefixes: true,
                combined_params: false,
                chained: false,
                include: false,
                revinclude: false,
                result_params: vec![],
                negative_values: vec![],
            }),
            TestSpec::Negative(NegativeSpec {
                undeclared_interactions: true,
                invalid_bodies: true,
                malformed_requests: false,
                auth_errors: false,
                version_conflicts: false,
            }),
        ]);
        let generator = MockGenerator;

        let plan = generate_test_plan(&api, &spec, &generator).unwrap();
        assert_eq!(plan.name, "Test API — generated test plan");
        assert_eq!(plan.setup.len(), 3); // 3 setup steps
        assert!(!plan.steps.is_empty());
    }

    #[test]
    fn test_generate_operation_tests() {
        let api = make_test_api();
        let spec = OperationSpec { enabled: true };
        let steps = generate_operation_tests(&api, &spec);
        // The test API only has standard CRUD/search operations, so no custom ops
        assert!(steps.is_empty());
    }

    #[test]
    fn test_generate_edge_case_tests() {
        let api = make_test_api();
        let spec = EdgeCaseSpec {
            boundary_values: true,
            special_characters: true,
            large_payloads: false,
            concurrent_operations: false,
            dangling_references: false,
        };
        let data = {
            let data_spec = DataSpec::default();
            let generator = MockGenerator;
            generate_data(&api, &data_spec, &generator).unwrap()
        };
        let generator = MockGenerator;
        let steps = generate_edge_case_tests(&api, &spec, &data, &generator).unwrap();
        // Should have special chars + boundary tests
        assert_eq!(steps.len(), 2);
        assert!(steps[0].count_tests() > 0);
    }

    #[test]
    fn test_generate_conformance_tests() {
        let api = make_test_api();
        let spec = ConformanceSpec {
            profile_validation: true,
            must_support: true,
        };
        let steps = generate_conformance_tests(&api, &spec);
        // Patient has a profile_url, so profile_validation should produce 1 step
        // No supported_profiles, so must_support produces 0 steps
        assert_eq!(steps.len(), 1);
        assert!(steps[0].count_tests() > 0);
    }

    #[test]
    fn test_generate_security_tests() {
        let api = make_test_api();
        let spec = SecuritySpec::default();
        let steps = generate_security_tests(&api, &spec);
        // Security tests are a placeholder — returns empty
        assert!(steps.is_empty());
    }

    #[test]
    fn test_generate_performance_tests() {
        let api = make_test_api();
        let spec = PerformanceSpec {
            response_time: false,
            pagination: true,
        };
        let steps = generate_performance_tests(&api, &spec);
        // Should have 1 pagination test for Patient
        assert_eq!(steps.len(), 1);
        assert!(steps[0].count_tests() > 0);
    }

    #[test]
    fn test_generate_performance_tests_disabled() {
        let api = make_test_api();
        let spec = PerformanceSpec::default();
        let steps = generate_performance_tests(&api, &spec);
        assert!(steps.is_empty());
    }

    #[test]
    fn test_generate_data_with_variations() {
        let api = make_test_api();
        let spec = DataSpec {
            count: 8,
            variations: vec![
                DataVariation::HappyPath,
                DataVariation::Minimal,
                DataVariation::SpecialChars,
                DataVariation::Boundary {
                    field: "name".into(),
                },
                DataVariation::DuplicateValue {
                    field: "name".into(),
                },
                DataVariation::MissingField {
                    field: "status".into(),
                },
                DataVariation::ToBeDeleted,
            ],
        };
        let generator = MockGenerator;
        let data = generate_data(&api, &spec, &generator).unwrap();

        let patient_resources = data.resources.get("Patient").unwrap();
        assert_eq!(patient_resources.len(), 8);

        // Verify all variation types are represented
        let has_happy = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::HappyPath));
        let has_minimal = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::Minimal));
        let has_special = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::SpecialChars));
        let has_boundary = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::Boundary { .. }));
        let has_dup = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::DuplicateValue { .. }));
        let has_missing = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::MissingField { .. }));
        let has_deleted = patient_resources
            .iter()
            .any(|r| matches!(r.variation, DataVariation::ToBeDeleted));
        assert!(has_happy, "should have HappyPath variation");
        assert!(has_minimal, "should have Minimal variation");
        assert!(has_special, "should have SpecialChars variation");
        assert!(has_boundary, "should have Boundary variation");
        assert!(has_dup, "should have DuplicateValue variation");
        assert!(has_missing, "should have MissingField variation");
        assert!(has_deleted, "should have ToBeDeleted variation");
    }

    #[test]
    fn test_generate_data_with_duplicate_variation() {
        let api = make_test_api();
        let spec = DataSpec {
            count: 2,
            variations: vec![
                DataVariation::HappyPath,
                DataVariation::DuplicateValue {
                    field: "name".into(),
                },
            ],
        };
        let generator = MockGenerator;
        let data = generate_data(&api, &spec, &generator).unwrap();

        let patient_resources = data.resources.get("Patient").unwrap();
        assert_eq!(patient_resources.len(), 2);
    }

    #[test]
    fn test_generate_data_with_missing_field_variation() {
        let api = make_test_api();
        let spec = DataSpec {
            count: 2,
            variations: vec![
                DataVariation::HappyPath,
                DataVariation::MissingField {
                    field: "status".into(),
                },
            ],
        };
        let generator = MockGenerator;
        let data = generate_data(&api, &spec, &generator).unwrap();

        let patient_resources = data.resources.get("Patient").unwrap();
        assert_eq!(patient_resources.len(), 2);
    }
}