Skip to main content

mockforge_bench/conformance/
spec_driven.rs

1//! Spec-driven conformance testing
2//!
3//! Analyzes the user's OpenAPI spec to determine which features their API uses,
4//! then generates k6 conformance tests against their real endpoints.
5
6use super::generator::ConformanceConfig;
7use super::schema_validator::SchemaValidatorGenerator;
8use super::spec::ConformanceFeature;
9use crate::error::Result;
10use crate::request_gen::RequestGenerator;
11use crate::spec_parser::ApiOperation;
12use openapiv3::{
13    OpenAPI, Operation, Parameter, ParameterSchemaOrContent, ReferenceOr, RequestBody, Response,
14    Schema, SchemaKind, SecurityScheme, StringFormat, Type, VariantOrUnknownOrEmpty,
15};
16use std::collections::HashSet;
17
18/// Resolve `$ref` references against the OpenAPI components
19mod ref_resolver {
20    use super::*;
21
22    pub fn resolve_parameter<'a>(
23        param_ref: &'a ReferenceOr<Parameter>,
24        spec: &'a OpenAPI,
25    ) -> Option<&'a Parameter> {
26        match param_ref {
27            ReferenceOr::Item(param) => Some(param),
28            ReferenceOr::Reference { reference } => {
29                let name = reference.strip_prefix("#/components/parameters/")?;
30                let components = spec.components.as_ref()?;
31                match components.parameters.get(name)? {
32                    ReferenceOr::Item(param) => Some(param),
33                    ReferenceOr::Reference {
34                        reference: inner_ref,
35                    } => {
36                        // One level of recursive resolution
37                        let inner_name = inner_ref.strip_prefix("#/components/parameters/")?;
38                        match components.parameters.get(inner_name)? {
39                            ReferenceOr::Item(param) => Some(param),
40                            ReferenceOr::Reference { .. } => None,
41                        }
42                    }
43                }
44            }
45        }
46    }
47
48    pub fn resolve_request_body<'a>(
49        body_ref: &'a ReferenceOr<RequestBody>,
50        spec: &'a OpenAPI,
51    ) -> Option<&'a RequestBody> {
52        match body_ref {
53            ReferenceOr::Item(body) => Some(body),
54            ReferenceOr::Reference { reference } => {
55                let name = reference.strip_prefix("#/components/requestBodies/")?;
56                let components = spec.components.as_ref()?;
57                match components.request_bodies.get(name)? {
58                    ReferenceOr::Item(body) => Some(body),
59                    ReferenceOr::Reference {
60                        reference: inner_ref,
61                    } => {
62                        // One level of recursive resolution
63                        let inner_name = inner_ref.strip_prefix("#/components/requestBodies/")?;
64                        match components.request_bodies.get(inner_name)? {
65                            ReferenceOr::Item(body) => Some(body),
66                            ReferenceOr::Reference { .. } => None,
67                        }
68                    }
69                }
70            }
71        }
72    }
73
74    pub fn resolve_schema<'a>(
75        schema_ref: &'a ReferenceOr<Schema>,
76        spec: &'a OpenAPI,
77    ) -> Option<&'a Schema> {
78        resolve_schema_with_visited(schema_ref, spec, &mut HashSet::new())
79    }
80
81    fn resolve_schema_with_visited<'a>(
82        schema_ref: &'a ReferenceOr<Schema>,
83        spec: &'a OpenAPI,
84        visited: &mut HashSet<String>,
85    ) -> Option<&'a Schema> {
86        match schema_ref {
87            ReferenceOr::Item(schema) => Some(schema),
88            ReferenceOr::Reference { reference } => {
89                if !visited.insert(reference.clone()) {
90                    return None; // Cycle detected
91                }
92                let name = reference.strip_prefix("#/components/schemas/")?;
93                let components = spec.components.as_ref()?;
94                let nested = components.schemas.get(name)?;
95                resolve_schema_with_visited(nested, spec, visited)
96            }
97        }
98    }
99
100    /// Resolve a boxed schema reference (used by array items and object properties)
101    pub fn resolve_boxed_schema<'a>(
102        schema_ref: &'a ReferenceOr<Box<Schema>>,
103        spec: &'a OpenAPI,
104    ) -> Option<&'a Schema> {
105        match schema_ref {
106            ReferenceOr::Item(schema) => Some(schema.as_ref()),
107            ReferenceOr::Reference { reference } => {
108                // Delegate to the regular schema resolver
109                let name = reference.strip_prefix("#/components/schemas/")?;
110                let components = spec.components.as_ref()?;
111                let nested = components.schemas.get(name)?;
112                resolve_schema_with_visited(nested, spec, &mut HashSet::new())
113            }
114        }
115    }
116
117    pub fn resolve_response<'a>(
118        resp_ref: &'a ReferenceOr<Response>,
119        spec: &'a OpenAPI,
120    ) -> Option<&'a Response> {
121        match resp_ref {
122            ReferenceOr::Item(resp) => Some(resp),
123            ReferenceOr::Reference { reference } => {
124                let name = reference.strip_prefix("#/components/responses/")?;
125                let components = spec.components.as_ref()?;
126                match components.responses.get(name)? {
127                    ReferenceOr::Item(resp) => Some(resp),
128                    ReferenceOr::Reference {
129                        reference: inner_ref,
130                    } => {
131                        // One level of recursive resolution
132                        let inner_name = inner_ref.strip_prefix("#/components/responses/")?;
133                        match components.responses.get(inner_name)? {
134                            ReferenceOr::Item(resp) => Some(resp),
135                            ReferenceOr::Reference { .. } => None,
136                        }
137                    }
138                }
139            }
140        }
141    }
142}
143
144/// Resolved security scheme details for an operation
145#[derive(Debug, Clone)]
146pub enum SecuritySchemeInfo {
147    /// HTTP Bearer token
148    Bearer,
149    /// HTTP Basic auth
150    Basic,
151    /// API Key in header, query, or cookie
152    ApiKey {
153        location: ApiKeyLocation,
154        name: String,
155    },
156}
157
158/// Where an API key is transmitted
159#[derive(Debug, Clone, PartialEq)]
160pub enum ApiKeyLocation {
161    Header,
162    Query,
163    Cookie,
164}
165
166/// An API operation annotated with the conformance features it exercises
167#[derive(Debug, Clone)]
168pub struct AnnotatedOperation {
169    pub path: String,
170    pub method: String,
171    pub features: Vec<ConformanceFeature>,
172    pub request_body_content_type: Option<String>,
173    pub sample_body: Option<String>,
174    pub query_params: Vec<(String, String)>,
175    pub header_params: Vec<(String, String)>,
176    pub path_params: Vec<(String, String)>,
177    /// Response schema for validation (JSON string of the schema)
178    pub response_schema: Option<Schema>,
179    /// Security scheme details resolved from the OpenAPI spec
180    pub security_schemes: Vec<SecuritySchemeInfo>,
181}
182
183/// Generates spec-driven conformance k6 scripts
184pub struct SpecDrivenConformanceGenerator {
185    config: ConformanceConfig,
186    operations: Vec<AnnotatedOperation>,
187}
188
189impl SpecDrivenConformanceGenerator {
190    pub fn new(config: ConformanceConfig, operations: Vec<AnnotatedOperation>) -> Self {
191        Self { config, operations }
192    }
193
194    /// Annotate a list of API operations with conformance features
195    pub fn annotate_operations(
196        operations: &[ApiOperation],
197        spec: &OpenAPI,
198    ) -> Vec<AnnotatedOperation> {
199        operations.iter().map(|op| Self::annotate_operation(op, spec)).collect()
200    }
201
202    /// Analyze an operation and determine which conformance features it exercises
203    fn annotate_operation(op: &ApiOperation, spec: &OpenAPI) -> AnnotatedOperation {
204        let mut features = Vec::new();
205        let mut query_params = Vec::new();
206        let mut header_params = Vec::new();
207        let mut path_params = Vec::new();
208
209        // Detect HTTP method feature
210        match op.method.to_uppercase().as_str() {
211            "GET" => features.push(ConformanceFeature::MethodGet),
212            "POST" => features.push(ConformanceFeature::MethodPost),
213            "PUT" => features.push(ConformanceFeature::MethodPut),
214            "PATCH" => features.push(ConformanceFeature::MethodPatch),
215            "DELETE" => features.push(ConformanceFeature::MethodDelete),
216            "HEAD" => features.push(ConformanceFeature::MethodHead),
217            "OPTIONS" => features.push(ConformanceFeature::MethodOptions),
218            _ => {}
219        }
220
221        // Detect parameter features (resolves $ref)
222        for param_ref in &op.operation.parameters {
223            if let Some(param) = ref_resolver::resolve_parameter(param_ref, spec) {
224                Self::annotate_parameter(
225                    param,
226                    spec,
227                    &mut features,
228                    &mut query_params,
229                    &mut header_params,
230                    &mut path_params,
231                );
232            }
233        }
234
235        // Detect path parameters from the path template itself
236        for segment in op.path.split('/') {
237            if segment.starts_with('{') && segment.ends_with('}') {
238                let name = &segment[1..segment.len() - 1];
239                // Only add if not already found from parameters
240                if !path_params.iter().any(|(n, _)| n == name) {
241                    path_params.push((name.to_string(), "test-value".to_string()));
242                    // Determine type from path params we didn't already handle
243                    if !features.contains(&ConformanceFeature::PathParamString)
244                        && !features.contains(&ConformanceFeature::PathParamInteger)
245                    {
246                        features.push(ConformanceFeature::PathParamString);
247                    }
248                }
249            }
250        }
251
252        // Detect request body features (resolves $ref)
253        let mut request_body_content_type = None;
254        let mut sample_body = None;
255
256        let resolved_body = op
257            .operation
258            .request_body
259            .as_ref()
260            .and_then(|b| ref_resolver::resolve_request_body(b, spec));
261
262        if let Some(body) = resolved_body {
263            for (content_type, _media) in &body.content {
264                match content_type.as_str() {
265                    "application/json" => {
266                        features.push(ConformanceFeature::BodyJson);
267                        request_body_content_type = Some("application/json".to_string());
268                        // Generate sample body from schema
269                        if let Ok(template) = RequestGenerator::generate_template(op) {
270                            if let Some(body_val) = &template.body {
271                                sample_body = Some(body_val.to_string());
272                            }
273                        }
274                    }
275                    "application/x-www-form-urlencoded" => {
276                        features.push(ConformanceFeature::BodyFormUrlencoded);
277                        request_body_content_type =
278                            Some("application/x-www-form-urlencoded".to_string());
279                    }
280                    "multipart/form-data" => {
281                        features.push(ConformanceFeature::BodyMultipart);
282                        request_body_content_type = Some("multipart/form-data".to_string());
283                    }
284                    _ => {}
285                }
286            }
287
288            // Detect schema features in request body (resolves $ref in schema)
289            if let Some(media) = body.content.get("application/json") {
290                if let Some(schema_ref) = &media.schema {
291                    if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
292                        Self::annotate_schema(schema, spec, &mut features);
293                    }
294                }
295            }
296        }
297
298        // Detect response code features
299        Self::annotate_responses(&op.operation, spec, &mut features);
300
301        // Extract response schema for validation (resolves $ref)
302        let response_schema = Self::extract_response_schema(&op.operation, spec);
303        if response_schema.is_some() {
304            features.push(ConformanceFeature::ResponseValidation);
305        }
306
307        // Detect content negotiation (response with multiple content types)
308        Self::annotate_content_negotiation(&op.operation, spec, &mut features);
309
310        // Detect security features and resolve scheme details
311        let mut security_schemes = Vec::new();
312        Self::annotate_security(&op.operation, spec, &mut features, &mut security_schemes);
313
314        // Deduplicate features
315        features.sort_by_key(|f| f.check_name());
316        features.dedup_by_key(|f| f.check_name());
317
318        AnnotatedOperation {
319            path: op.path.clone(),
320            method: op.method.to_uppercase(),
321            features,
322            request_body_content_type,
323            sample_body,
324            query_params,
325            header_params,
326            path_params,
327            response_schema,
328            security_schemes,
329        }
330    }
331
332    /// Annotate parameter features
333    fn annotate_parameter(
334        param: &Parameter,
335        spec: &OpenAPI,
336        features: &mut Vec<ConformanceFeature>,
337        query_params: &mut Vec<(String, String)>,
338        header_params: &mut Vec<(String, String)>,
339        path_params: &mut Vec<(String, String)>,
340    ) {
341        let (location, data) = match param {
342            Parameter::Query { parameter_data, .. } => ("query", parameter_data),
343            Parameter::Path { parameter_data, .. } => ("path", parameter_data),
344            Parameter::Header { parameter_data, .. } => ("header", parameter_data),
345            Parameter::Cookie { .. } => {
346                features.push(ConformanceFeature::CookieParam);
347                return;
348            }
349        };
350
351        // Detect type from schema
352        let is_integer = Self::param_schema_is_integer(data, spec);
353        let is_array = Self::param_schema_is_array(data, spec);
354
355        // Generate sample value
356        let sample = if is_integer {
357            "42".to_string()
358        } else if is_array {
359            "a,b".to_string()
360        } else {
361            "test-value".to_string()
362        };
363
364        match location {
365            "path" => {
366                if is_integer {
367                    features.push(ConformanceFeature::PathParamInteger);
368                } else {
369                    features.push(ConformanceFeature::PathParamString);
370                }
371                path_params.push((data.name.clone(), sample));
372            }
373            "query" => {
374                if is_array {
375                    features.push(ConformanceFeature::QueryParamArray);
376                } else if is_integer {
377                    features.push(ConformanceFeature::QueryParamInteger);
378                } else {
379                    features.push(ConformanceFeature::QueryParamString);
380                }
381                query_params.push((data.name.clone(), sample));
382            }
383            "header" => {
384                features.push(ConformanceFeature::HeaderParam);
385                header_params.push((data.name.clone(), sample));
386            }
387            _ => {}
388        }
389
390        // Check for constraint features on the parameter (resolves $ref)
391        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
392            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
393                Self::annotate_schema(schema, spec, features);
394            }
395        }
396
397        // Required/optional
398        if data.required {
399            features.push(ConformanceFeature::ConstraintRequired);
400        } else {
401            features.push(ConformanceFeature::ConstraintOptional);
402        }
403    }
404
405    fn param_schema_is_integer(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
406        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
407            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
408                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Integer(_)));
409            }
410        }
411        false
412    }
413
414    fn param_schema_is_array(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
415        if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
416            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
417                return matches!(&schema.schema_kind, SchemaKind::Type(Type::Array(_)));
418            }
419        }
420        false
421    }
422
423    /// Annotate schema-level features (types, composition, formats, constraints)
424    fn annotate_schema(schema: &Schema, spec: &OpenAPI, features: &mut Vec<ConformanceFeature>) {
425        match &schema.schema_kind {
426            SchemaKind::Type(Type::String(s)) => {
427                features.push(ConformanceFeature::SchemaString);
428                // Check format
429                match &s.format {
430                    VariantOrUnknownOrEmpty::Item(StringFormat::Date) => {
431                        features.push(ConformanceFeature::FormatDate);
432                    }
433                    VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
434                        features.push(ConformanceFeature::FormatDateTime);
435                    }
436                    VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
437                        "email" => features.push(ConformanceFeature::FormatEmail),
438                        "uuid" => features.push(ConformanceFeature::FormatUuid),
439                        "uri" | "url" => features.push(ConformanceFeature::FormatUri),
440                        "ipv4" => features.push(ConformanceFeature::FormatIpv4),
441                        "ipv6" => features.push(ConformanceFeature::FormatIpv6),
442                        _ => {}
443                    },
444                    _ => {}
445                }
446                // Check constraints
447                if s.pattern.is_some() {
448                    features.push(ConformanceFeature::ConstraintPattern);
449                }
450                if !s.enumeration.is_empty() {
451                    features.push(ConformanceFeature::ConstraintEnum);
452                }
453                if s.min_length.is_some() || s.max_length.is_some() {
454                    features.push(ConformanceFeature::ConstraintMinMax);
455                }
456            }
457            SchemaKind::Type(Type::Integer(i)) => {
458                features.push(ConformanceFeature::SchemaInteger);
459                if i.minimum.is_some() || i.maximum.is_some() {
460                    features.push(ConformanceFeature::ConstraintMinMax);
461                }
462                if !i.enumeration.is_empty() {
463                    features.push(ConformanceFeature::ConstraintEnum);
464                }
465            }
466            SchemaKind::Type(Type::Number(n)) => {
467                features.push(ConformanceFeature::SchemaNumber);
468                if n.minimum.is_some() || n.maximum.is_some() {
469                    features.push(ConformanceFeature::ConstraintMinMax);
470                }
471            }
472            SchemaKind::Type(Type::Boolean(_)) => {
473                features.push(ConformanceFeature::SchemaBoolean);
474            }
475            SchemaKind::Type(Type::Array(arr)) => {
476                features.push(ConformanceFeature::SchemaArray);
477                if let Some(item_ref) = &arr.items {
478                    if let Some(item_schema) = ref_resolver::resolve_boxed_schema(item_ref, spec) {
479                        Self::annotate_schema(item_schema, spec, features);
480                    }
481                }
482            }
483            SchemaKind::Type(Type::Object(obj)) => {
484                features.push(ConformanceFeature::SchemaObject);
485                // Check required fields
486                if !obj.required.is_empty() {
487                    features.push(ConformanceFeature::ConstraintRequired);
488                }
489                // Walk properties (resolves $ref)
490                for (_name, prop_ref) in &obj.properties {
491                    if let Some(prop_schema) = ref_resolver::resolve_boxed_schema(prop_ref, spec) {
492                        Self::annotate_schema(prop_schema, spec, features);
493                    }
494                }
495            }
496            SchemaKind::OneOf { .. } => {
497                features.push(ConformanceFeature::CompositionOneOf);
498            }
499            SchemaKind::AnyOf { .. } => {
500                features.push(ConformanceFeature::CompositionAnyOf);
501            }
502            SchemaKind::AllOf { .. } => {
503                features.push(ConformanceFeature::CompositionAllOf);
504            }
505            _ => {}
506        }
507    }
508
509    /// Detect response code features (resolves $ref in responses)
510    fn annotate_responses(
511        operation: &Operation,
512        spec: &OpenAPI,
513        features: &mut Vec<ConformanceFeature>,
514    ) {
515        for (status_code, resp_ref) in &operation.responses.responses {
516            // Only count features for responses that actually resolve
517            if ref_resolver::resolve_response(resp_ref, spec).is_some() {
518                match status_code {
519                    openapiv3::StatusCode::Code(200) => {
520                        features.push(ConformanceFeature::Response200)
521                    }
522                    openapiv3::StatusCode::Code(201) => {
523                        features.push(ConformanceFeature::Response201)
524                    }
525                    openapiv3::StatusCode::Code(204) => {
526                        features.push(ConformanceFeature::Response204)
527                    }
528                    openapiv3::StatusCode::Code(400) => {
529                        features.push(ConformanceFeature::Response400)
530                    }
531                    openapiv3::StatusCode::Code(404) => {
532                        features.push(ConformanceFeature::Response404)
533                    }
534                    _ => {}
535                }
536            }
537        }
538    }
539
540    /// Extract the response schema for the primary success response (200 or 201)
541    /// Resolves $ref for both the response and the schema within it.
542    fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
543        // Try 200 first, then 201
544        for code in [200u16, 201] {
545            if let Some(resp_ref) =
546                operation.responses.responses.get(&openapiv3::StatusCode::Code(code))
547            {
548                if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
549                    if let Some(media) = response.content.get("application/json") {
550                        if let Some(schema_ref) = &media.schema {
551                            if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
552                                return Some(schema.clone());
553                            }
554                        }
555                    }
556                }
557            }
558        }
559        None
560    }
561
562    /// Detect content negotiation: response supports multiple content types
563    fn annotate_content_negotiation(
564        operation: &Operation,
565        spec: &OpenAPI,
566        features: &mut Vec<ConformanceFeature>,
567    ) {
568        for (_status_code, resp_ref) in &operation.responses.responses {
569            if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
570                if response.content.len() > 1 {
571                    features.push(ConformanceFeature::ContentNegotiation);
572                    return; // Only need to detect once per operation
573                }
574            }
575        }
576    }
577
578    /// Detect security scheme features.
579    /// Checks operation-level security first, falling back to global security requirements.
580    /// Resolves scheme names against SecurityScheme definitions in components.
581    fn annotate_security(
582        operation: &Operation,
583        spec: &OpenAPI,
584        features: &mut Vec<ConformanceFeature>,
585        security_schemes: &mut Vec<SecuritySchemeInfo>,
586    ) {
587        // Use operation-level security if present, otherwise fall back to global
588        let security_reqs = operation.security.as_ref().or(spec.security.as_ref());
589
590        if let Some(security) = security_reqs {
591            for security_req in security {
592                for scheme_name in security_req.keys() {
593                    // Try to resolve the scheme from components for accurate type detection
594                    if let Some(resolved) = Self::resolve_security_scheme(scheme_name, spec) {
595                        match resolved {
596                            SecurityScheme::HTTP { ref scheme, .. } => {
597                                if scheme.eq_ignore_ascii_case("bearer") {
598                                    features.push(ConformanceFeature::SecurityBearer);
599                                    security_schemes.push(SecuritySchemeInfo::Bearer);
600                                } else if scheme.eq_ignore_ascii_case("basic") {
601                                    features.push(ConformanceFeature::SecurityBasic);
602                                    security_schemes.push(SecuritySchemeInfo::Basic);
603                                }
604                            }
605                            SecurityScheme::APIKey { location, name, .. } => {
606                                features.push(ConformanceFeature::SecurityApiKey);
607                                let loc = match location {
608                                    openapiv3::APIKeyLocation::Query => ApiKeyLocation::Query,
609                                    openapiv3::APIKeyLocation::Header => ApiKeyLocation::Header,
610                                    openapiv3::APIKeyLocation::Cookie => ApiKeyLocation::Cookie,
611                                };
612                                security_schemes.push(SecuritySchemeInfo::ApiKey {
613                                    location: loc,
614                                    name: name.clone(),
615                                });
616                            }
617                            // OAuth2 and OpenIDConnect don't map to our current feature set
618                            _ => {}
619                        }
620                    } else {
621                        // Fallback: heuristic name matching for unresolvable schemes
622                        let name_lower = scheme_name.to_lowercase();
623                        if name_lower.contains("bearer") || name_lower.contains("jwt") {
624                            features.push(ConformanceFeature::SecurityBearer);
625                            security_schemes.push(SecuritySchemeInfo::Bearer);
626                        } else if name_lower.contains("api") && name_lower.contains("key") {
627                            features.push(ConformanceFeature::SecurityApiKey);
628                            security_schemes.push(SecuritySchemeInfo::ApiKey {
629                                location: ApiKeyLocation::Header,
630                                name: "X-API-Key".to_string(),
631                            });
632                        } else if name_lower.contains("basic") {
633                            features.push(ConformanceFeature::SecurityBasic);
634                            security_schemes.push(SecuritySchemeInfo::Basic);
635                        }
636                    }
637                }
638            }
639        }
640    }
641
642    /// Resolve a security scheme name to its SecurityScheme definition
643    fn resolve_security_scheme<'a>(name: &str, spec: &'a OpenAPI) -> Option<&'a SecurityScheme> {
644        let components = spec.components.as_ref()?;
645        match components.security_schemes.get(name)? {
646            ReferenceOr::Item(scheme) => Some(scheme),
647            ReferenceOr::Reference { .. } => None,
648        }
649    }
650
651    /// Returns the number of operations being tested
652    pub fn operation_count(&self) -> usize {
653        self.operations.len()
654    }
655
656    /// Generate the k6 conformance script.
657    /// Returns (script, check_count) where check_count is the number of unique checks emitted.
658    pub fn generate(&self) -> Result<(String, usize)> {
659        let mut script = String::with_capacity(16384);
660
661        // Imports
662        script.push_str("import http from 'k6/http';\n");
663        script.push_str("import { check, group } from 'k6';\n");
664        if self.config.request_delay_ms > 0 {
665            script.push_str("import { sleep } from 'k6';\n");
666        }
667        script.push('\n');
668
669        // Tell k6 that all HTTP status codes are "expected" in conformance mode.
670        // Without this, k6 counts 4xx responses (e.g. intentional 404 tests) as
671        // http_req_failed errors, producing a misleading error rate percentage.
672        script.push_str(
673            "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
674        );
675
676        // Options
677        script.push_str("export const options = {\n");
678        script.push_str("  vus: 1,\n");
679        script.push_str("  iterations: 1,\n");
680        if self.config.skip_tls_verify {
681            script.push_str("  insecureSkipTLSVerify: true,\n");
682        }
683        script.push_str("  thresholds: {\n");
684        script.push_str("    checks: ['rate>0'],\n");
685        script.push_str("  },\n");
686        script.push_str("};\n\n");
687
688        // Base URL (includes base_path if configured)
689        script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
690        script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
691
692        // Failure detail collector — logs req/res info for failed checks via console.log
693        // (k6's handleSummary runs in a separate JS context, so we can't use module-level arrays)
694        script
695            .push_str("function __captureFailure(checkName, res, expected, schemaViolations) {\n");
696        script.push_str("  let bodyStr = '';\n");
697        script.push_str("  try { bodyStr = res.body ? res.body.substring(0, 2000) : ''; } catch(e) { bodyStr = '<unreadable>'; }\n");
698        script.push_str("  let reqHeaders = {};\n");
699        script.push_str(
700            "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
701        );
702        script.push_str("  let reqBody = '';\n");
703        script.push_str("  if (res.request && res.request.body) { try { reqBody = res.request.body.substring(0, 2000); } catch(e) {} }\n");
704        script.push_str("  let payload = {\n");
705        script.push_str("    check: checkName,\n");
706        script.push_str("    request: {\n");
707        script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
708        script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
709        script.push_str("      headers: reqHeaders,\n");
710        script.push_str("      body: reqBody,\n");
711        script.push_str("    },\n");
712        script.push_str("    response: {\n");
713        script.push_str("      status: res.status,\n");
714        script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
715        script.push_str("      body: bodyStr,\n");
716        script.push_str("    },\n");
717        script.push_str("    expected: expected,\n");
718        script.push_str("  };\n");
719        script.push_str("  if (schemaViolations && schemaViolations.length > 0) { payload.schema_violations = schemaViolations; }\n");
720        script.push_str("  console.log('MOCKFORGE_FAILURE:' + JSON.stringify(payload));\n");
721        script.push_str("}\n\n");
722
723        // Default function
724        script.push_str("export default function () {\n");
725
726        if self.config.has_cookie_header() {
727            script.push_str(
728                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
729            );
730            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
731        }
732
733        // Group operations by category
734        let mut category_ops: std::collections::BTreeMap<
735            &'static str,
736            Vec<(&AnnotatedOperation, &ConformanceFeature)>,
737        > = std::collections::BTreeMap::new();
738
739        for op in &self.operations {
740            for feature in &op.features {
741                let category = feature.category();
742                if self.config.should_include_category(category) {
743                    category_ops.entry(category).or_default().push((op, feature));
744                }
745            }
746        }
747
748        // Emit grouped tests
749        let mut total_checks = 0usize;
750        for (category, ops) in &category_ops {
751            script.push_str(&format!("  group('{}', function () {{\n", category));
752
753            if self.config.all_operations {
754                // All-operations mode: test every operation, using path-qualified check names
755                let mut emitted_checks: HashSet<String> = HashSet::new();
756                for (op, feature) in ops {
757                    let qualified = format!("{}:{}", feature.check_name(), op.path);
758                    if emitted_checks.insert(qualified.clone()) {
759                        self.emit_check_named(&mut script, op, feature, &qualified);
760                        total_checks += 1;
761                    }
762                }
763            } else {
764                // Default: one representative operation per feature, with path-qualified
765                // check names so failures identify which endpoint was tested.
766                let mut emitted_features: HashSet<&str> = HashSet::new();
767                for (op, feature) in ops {
768                    if emitted_features.insert(feature.check_name()) {
769                        let qualified = format!("{}:{}", feature.check_name(), op.path);
770                        self.emit_check_named(&mut script, op, feature, &qualified);
771                        total_checks += 1;
772                    }
773                }
774            }
775
776            script.push_str("  });\n\n");
777        }
778
779        // Custom checks from YAML file
780        if let Some(custom_group) = self.config.generate_custom_group()? {
781            script.push_str(&custom_group);
782        }
783
784        script.push_str("}\n\n");
785
786        // handleSummary
787        self.generate_handle_summary(&mut script);
788
789        Ok((script, total_checks))
790    }
791
792    /// Emit a single k6 check for an operation + feature with a custom check name
793    fn emit_check_named(
794        &self,
795        script: &mut String,
796        op: &AnnotatedOperation,
797        feature: &ConformanceFeature,
798        check_name: &str,
799    ) {
800        // Escape single quotes in check name since it's embedded in JS single-quoted strings
801        let check_name = check_name.replace('\'', "\\'");
802        let check_name = check_name.as_str();
803
804        script.push_str("    {\n");
805
806        // Build the URL path with parameters substituted
807        let mut url_path = op.path.clone();
808        for (name, value) in &op.path_params {
809            url_path = url_path.replace(&format!("{{{}}}", name), value);
810        }
811
812        // Build query string
813        if !op.query_params.is_empty() {
814            let qs: Vec<String> =
815                op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
816            url_path = format!("{}?{}", url_path, qs.join("&"));
817        }
818
819        let full_url = format!("${{BASE_URL}}{}", url_path);
820
821        // Build effective headers: merge spec-derived headers with custom headers.
822        // Custom headers override spec-derived ones with the same name.
823        let mut effective_headers = self.effective_headers(&op.header_params);
824
825        // For non-default response code checks, add header to tell the mock server
826        // which status code to return (the server defaults to the first declared status)
827        if matches!(feature, ConformanceFeature::Response400 | ConformanceFeature::Response404) {
828            let expected_code = match feature {
829                ConformanceFeature::Response400 => "400",
830                ConformanceFeature::Response404 => "404",
831                _ => unreachable!(),
832            };
833            effective_headers
834                .push(("X-Mockforge-Response-Status".to_string(), expected_code.to_string()));
835        }
836
837        // For security checks AND for all requests on endpoints with security requirements,
838        // inject auth credentials so the server doesn't reject with 401.
839        // Only inject if the user hasn't already provided the header via --custom-headers.
840        let needs_auth = matches!(
841            feature,
842            ConformanceFeature::SecurityBearer
843                | ConformanceFeature::SecurityBasic
844                | ConformanceFeature::SecurityApiKey
845        ) || !op.security_schemes.is_empty();
846
847        if needs_auth {
848            self.inject_security_headers(&op.security_schemes, &mut effective_headers);
849        }
850
851        let has_headers = !effective_headers.is_empty();
852        let headers_obj = if has_headers {
853            Self::format_headers(&effective_headers)
854        } else {
855            String::new()
856        };
857
858        // Determine HTTP method and emit request
859        match op.method.as_str() {
860            "GET" => {
861                if has_headers {
862                    script.push_str(&format!(
863                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
864                        full_url, headers_obj
865                    ));
866                } else {
867                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
868                }
869            }
870            "POST" => {
871                self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
872            }
873            "PUT" => {
874                self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
875            }
876            "PATCH" => {
877                self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
878            }
879            "DELETE" => {
880                if has_headers {
881                    script.push_str(&format!(
882                        "      let res = http.del(`{}`, null, {{ headers: {} }});\n",
883                        full_url, headers_obj
884                    ));
885                } else {
886                    script.push_str(&format!("      let res = http.del(`{}`);\n", full_url));
887                }
888            }
889            "HEAD" => {
890                if has_headers {
891                    script.push_str(&format!(
892                        "      let res = http.head(`{}`, {{ headers: {} }});\n",
893                        full_url, headers_obj
894                    ));
895                } else {
896                    script.push_str(&format!("      let res = http.head(`{}`);\n", full_url));
897                }
898            }
899            "OPTIONS" => {
900                if has_headers {
901                    script.push_str(&format!(
902                        "      let res = http.options(`{}`, null, {{ headers: {} }});\n",
903                        full_url, headers_obj
904                    ));
905                } else {
906                    script.push_str(&format!("      let res = http.options(`{}`);\n", full_url));
907                }
908            }
909            _ => {
910                if has_headers {
911                    script.push_str(&format!(
912                        "      let res = http.get(`{}`, {{ headers: {} }});\n",
913                        full_url, headers_obj
914                    ));
915                } else {
916                    script.push_str(&format!("      let res = http.get(`{}`);\n", full_url));
917                }
918            }
919        }
920
921        // Check: emit assertion based on feature type, with failure detail capture
922        if matches!(
923            feature,
924            ConformanceFeature::Response200
925                | ConformanceFeature::Response201
926                | ConformanceFeature::Response204
927                | ConformanceFeature::Response400
928                | ConformanceFeature::Response404
929        ) {
930            let expected_code = match feature {
931                ConformanceFeature::Response200 => 200,
932                ConformanceFeature::Response201 => 201,
933                ConformanceFeature::Response204 => 204,
934                ConformanceFeature::Response400 => 400,
935                ConformanceFeature::Response404 => 404,
936                _ => 200,
937            };
938            script.push_str(&format!(
939                "      {{ let ok = check(res, {{ '{}': (r) => r.status === {} }}); if (!ok) __captureFailure('{}', res, 'status === {}'); }}\n",
940                check_name, expected_code, check_name, expected_code
941            ));
942        } else if matches!(feature, ConformanceFeature::ResponseValidation) {
943            // Response schema validation — validate the response body against the schema
944            // Uses inline field-level error collection so failure details include
945            // which specific fields violated the schema (field_path, violation_type,
946            // expected, actual) — matching the Ajv `errors` array structure.
947            if let Some(schema) = &op.response_schema {
948                let validation_js = SchemaValidatorGenerator::generate_validation(schema);
949                let schema_json = serde_json::to_string(schema).unwrap_or_default();
950                // Escape backticks and backslashes for JS template literal safety
951                let schema_json_escaped = schema_json.replace('\\', "\\\\").replace('`', "\\`");
952                script.push_str(&format!(
953                    concat!(
954                        "      try {{\n",
955                        "        let body = res.json();\n",
956                        "        let ok = check(res, {{ '{check}': (r) => ( {validation} ) }});\n",
957                        "        if (!ok) {{\n",
958                        "          let __violations = [];\n",
959                        "          try {{\n",
960                        "            let __schema = JSON.parse(`{schema}`);\n",
961                        "            function __collectErrors(schema, data, path) {{\n",
962                        "              if (!schema || typeof schema !== 'object') return;\n",
963                        "              let st = schema.type || (schema.schema_kind && schema.schema_kind.Type && Object.keys(schema.schema_kind.Type)[0]);\n",
964                        "              if (st) {{ st = st.toLowerCase(); }}\n",
965                        "              if (st === 'object') {{\n",
966                        "                if (typeof data !== 'object' || data === null) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'object', actual: typeof data }}); return; }}\n",
967                        "                let props = schema.properties || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.properties) || {{}};\n",
968                        "                let req = schema.required || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.required) || [];\n",
969                        "                for (let f of req) {{ if (!(f in data)) {{ __violations.push({{ field_path: path + '/' + f, violation_type: 'required', expected: 'present', actual: 'missing' }}); }} }}\n",
970                        "                for (let [k, v] of Object.entries(props)) {{ if (data[k] !== undefined) {{ let ps = v.Item || v; __collectErrors(ps, data[k], path + '/' + k); }} }}\n",
971                        "              }} else if (st === 'array') {{\n",
972                        "                if (!Array.isArray(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'array', actual: typeof data }}); return; }}\n",
973                        "                let items = schema.items || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Array && schema.schema_kind.Type.Array.items);\n",
974                        "                if (items) {{ let is = items.Item || items; for (let i = 0; i < Math.min(data.length, 5); i++) {{ __collectErrors(is, data[i], path + '/' + i); }} }}\n",
975                        "              }} else if (st === 'string') {{\n",
976                        "                if (typeof data !== 'string') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'string', actual: typeof data }}); }}\n",
977                        "              }} else if (st === 'integer') {{\n",
978                        "                if (typeof data !== 'number' || !Number.isInteger(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'integer', actual: typeof data }}); }}\n",
979                        "              }} else if (st === 'number') {{\n",
980                        "                if (typeof data !== 'number') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'number', actual: typeof data }}); }}\n",
981                        "              }} else if (st === 'boolean') {{\n",
982                        "                if (typeof data !== 'boolean') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'boolean', actual: typeof data }}); }}\n",
983                        "              }}\n",
984                        "            }}\n",
985                        "            __collectErrors(__schema, body, '');\n",
986                        "          }} catch(_e) {{}}\n",
987                        "          __captureFailure('{check}', res, 'schema validation', __violations);\n",
988                        "        }}\n",
989                        "      }} catch(e) {{ check(res, {{ '{check}': () => false }}); __captureFailure('{check}', res, 'JSON parse failed: ' + e.message); }}\n",
990                    ),
991                    check = check_name,
992                    validation = validation_js,
993                    schema = schema_json_escaped,
994                ));
995            }
996        } else if matches!(
997            feature,
998            ConformanceFeature::SecurityBearer
999                | ConformanceFeature::SecurityBasic
1000                | ConformanceFeature::SecurityApiKey
1001        ) {
1002            // Security checks verify the server accepts the auth credentials (not 401/403)
1003            script.push_str(&format!(
1004                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 400 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 400 (auth accepted)'); }}\n",
1005                check_name, check_name
1006            ));
1007        } else {
1008            script.push_str(&format!(
1009                "      {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 500'); }}\n",
1010                check_name, check_name
1011            ));
1012        }
1013
1014        // Clear cookie jar after each request to prevent Set-Cookie leaking
1015        let has_cookie = self.config.has_cookie_header()
1016            || effective_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case("Cookie"));
1017        if has_cookie {
1018            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
1019        }
1020
1021        script.push_str("    }\n");
1022
1023        // Rate-limit delay between checks (to avoid 429 from target API)
1024        if self.config.request_delay_ms > 0 {
1025            script.push_str(&format!(
1026                "    sleep({:.3});\n",
1027                self.config.request_delay_ms as f64 / 1000.0
1028            ));
1029        }
1030    }
1031
1032    /// Emit an HTTP request with a body
1033    fn emit_request_with_body(
1034        &self,
1035        script: &mut String,
1036        method: &str,
1037        url: &str,
1038        op: &AnnotatedOperation,
1039        effective_headers: &[(String, String)],
1040    ) {
1041        if let Some(body) = &op.sample_body {
1042            let escaped_body = body.replace('\'', "\\'");
1043            let headers = if !effective_headers.is_empty() {
1044                format!(
1045                    "Object.assign({{}}, JSON_HEADERS, {})",
1046                    Self::format_headers(effective_headers)
1047                )
1048            } else {
1049                "JSON_HEADERS".to_string()
1050            };
1051            script.push_str(&format!(
1052                "      let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
1053                method, url, escaped_body, headers
1054            ));
1055        } else if !effective_headers.is_empty() {
1056            script.push_str(&format!(
1057                "      let res = http.{}(`{}`, null, {{ headers: {} }});\n",
1058                method,
1059                url,
1060                Self::format_headers(effective_headers)
1061            ));
1062        } else {
1063            script.push_str(&format!("      let res = http.{}(`{}`, null);\n", method, url));
1064        }
1065    }
1066
1067    /// Build effective headers by merging spec-derived headers with custom headers.
1068    /// Custom headers override spec-derived ones with the same name (case-insensitive).
1069    /// Custom headers not in the spec are appended.
1070    fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
1071        let custom = &self.config.custom_headers;
1072        if custom.is_empty() {
1073            return spec_headers.to_vec();
1074        }
1075
1076        let mut result: Vec<(String, String)> = Vec::new();
1077
1078        // Start with spec headers, replacing values if a custom header matches
1079        for (name, value) in spec_headers {
1080            if let Some((_, custom_val)) =
1081                custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
1082            {
1083                result.push((name.clone(), custom_val.clone()));
1084            } else {
1085                result.push((name.clone(), value.clone()));
1086            }
1087        }
1088
1089        // Append custom headers that aren't already in spec headers
1090        for (name, value) in custom {
1091            if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
1092                result.push((name.clone(), value.clone()));
1093            }
1094        }
1095
1096        result
1097    }
1098
1099    /// Inject security headers based on resolved security scheme details.
1100    /// Respects user-provided custom headers (won't overwrite if already set).
1101    fn inject_security_headers(
1102        &self,
1103        schemes: &[SecuritySchemeInfo],
1104        headers: &mut Vec<(String, String)>,
1105    ) {
1106        let mut to_add: Vec<(String, String)> = Vec::new();
1107
1108        let has_header = |name: &str, headers: &[(String, String)]| {
1109            headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1110                || self.config.custom_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1111        };
1112
1113        // If user provides Cookie header, they're using session-based auth — skip auto auth
1114        let has_cookie_auth = has_header("Cookie", headers);
1115
1116        for scheme in schemes {
1117            match scheme {
1118                SecuritySchemeInfo::Bearer => {
1119                    if !has_cookie_auth && !has_header("Authorization", headers) {
1120                        // MockForge mock server accepts any Bearer token
1121                        to_add.push((
1122                            "Authorization".to_string(),
1123                            "Bearer mockforge-conformance-test-token".to_string(),
1124                        ));
1125                    }
1126                }
1127                SecuritySchemeInfo::Basic => {
1128                    if !has_cookie_auth && !has_header("Authorization", headers) {
1129                        let creds = self.config.basic_auth.as_deref().unwrap_or("test:test");
1130                        use base64::Engine;
1131                        let encoded =
1132                            base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
1133                        to_add.push(("Authorization".to_string(), format!("Basic {}", encoded)));
1134                    }
1135                }
1136                SecuritySchemeInfo::ApiKey { location, name } => match location {
1137                    ApiKeyLocation::Header => {
1138                        if !has_header(name, headers) {
1139                            let key = self
1140                                .config
1141                                .api_key
1142                                .as_deref()
1143                                .unwrap_or("mockforge-conformance-test-key");
1144                            to_add.push((name.clone(), key.to_string()));
1145                        }
1146                    }
1147                    ApiKeyLocation::Cookie => {
1148                        if !has_header("Cookie", headers) {
1149                            to_add.push((
1150                                "Cookie".to_string(),
1151                                format!("{}=mockforge-conformance-test-session", name),
1152                            ));
1153                        }
1154                    }
1155                    ApiKeyLocation::Query => {
1156                        // Query params are handled via URL, not headers — skip here
1157                    }
1158                },
1159            }
1160        }
1161
1162        headers.extend(to_add);
1163    }
1164
1165    /// Format header params as a JS object literal
1166    fn format_headers(headers: &[(String, String)]) -> String {
1167        let entries: Vec<String> = headers
1168            .iter()
1169            .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
1170            .collect();
1171        format!("{{ {} }}", entries.join(", "))
1172    }
1173
1174    /// handleSummary — same format as reference mode for report compatibility
1175    fn generate_handle_summary(&self, script: &mut String) {
1176        // Use absolute path for report output so k6 writes where the CLI expects
1177        let report_path = match &self.config.output_dir {
1178            Some(dir) => {
1179                let abs = std::fs::canonicalize(dir)
1180                    .unwrap_or_else(|_| dir.clone())
1181                    .join("conformance-report.json");
1182                abs.to_string_lossy().to_string()
1183            }
1184            None => "conformance-report.json".to_string(),
1185        };
1186
1187        script.push_str("export function handleSummary(data) {\n");
1188        script.push_str("  let checks = {};\n");
1189        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
1190        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1191        script.push_str("  }\n");
1192        script.push_str("  let checkResults = {};\n");
1193        script.push_str("  function walkGroups(group) {\n");
1194        script.push_str("    if (group.checks) {\n");
1195        script.push_str("      for (let checkObj of group.checks) {\n");
1196        script.push_str("        checkResults[checkObj.name] = {\n");
1197        script.push_str("          passes: checkObj.passes,\n");
1198        script.push_str("          fails: checkObj.fails,\n");
1199        script.push_str("        };\n");
1200        script.push_str("      }\n");
1201        script.push_str("    }\n");
1202        script.push_str("    if (group.groups) {\n");
1203        script.push_str("      for (let subGroup of group.groups) {\n");
1204        script.push_str("        walkGroups(subGroup);\n");
1205        script.push_str("      }\n");
1206        script.push_str("    }\n");
1207        script.push_str("  }\n");
1208        script.push_str("  if (data.root_group) {\n");
1209        script.push_str("    walkGroups(data.root_group);\n");
1210        script.push_str("  }\n");
1211        script.push_str("  return {\n");
1212        script.push_str(&format!(
1213            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1214            report_path
1215        ));
1216        script.push_str("    'summary.json': JSON.stringify(data),\n");
1217        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
1218        script.push_str("  };\n");
1219        script.push_str("}\n\n");
1220        script.push_str("function textSummary(data, opts) {\n");
1221        script.push_str("  return JSON.stringify(data, null, 2);\n");
1222        script.push_str("}\n");
1223    }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228    use super::*;
1229    use openapiv3::{
1230        Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
1231        SchemaData, SchemaKind, StringType, Type,
1232    };
1233
1234    fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
1235        ApiOperation {
1236            method: method.to_string(),
1237            path: path.to_string(),
1238            operation,
1239            operation_id: None,
1240        }
1241    }
1242
1243    fn empty_spec() -> OpenAPI {
1244        OpenAPI::default()
1245    }
1246
1247    #[test]
1248    fn test_annotate_get_with_path_param() {
1249        let mut op = Operation::default();
1250        op.parameters.push(ReferenceOr::Item(Parameter::Path {
1251            parameter_data: ParameterData {
1252                name: "id".to_string(),
1253                description: None,
1254                required: true,
1255                deprecated: None,
1256                format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
1257                    schema_data: SchemaData::default(),
1258                    schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1259                })),
1260                example: None,
1261                examples: Default::default(),
1262                explode: None,
1263                extensions: Default::default(),
1264            },
1265            style: PathStyle::Simple,
1266        }));
1267
1268        let api_op = make_op("get", "/users/{id}", op);
1269        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1270
1271        assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
1272        assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
1273        assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
1274        assert_eq!(annotated.path_params.len(), 1);
1275        assert_eq!(annotated.path_params[0].0, "id");
1276    }
1277
1278    #[test]
1279    fn test_annotate_post_with_json_body() {
1280        let mut op = Operation::default();
1281        let mut body = openapiv3::RequestBody {
1282            required: true,
1283            ..Default::default()
1284        };
1285        body.content
1286            .insert("application/json".to_string(), openapiv3::MediaType::default());
1287        op.request_body = Some(ReferenceOr::Item(body));
1288
1289        let api_op = make_op("post", "/items", op);
1290        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1291
1292        assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
1293        assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
1294    }
1295
1296    #[test]
1297    fn test_annotate_response_codes() {
1298        let mut op = Operation::default();
1299        op.responses
1300            .responses
1301            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
1302        op.responses
1303            .responses
1304            .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));
1305
1306        let api_op = make_op("get", "/items", op);
1307        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1308
1309        assert!(annotated.features.contains(&ConformanceFeature::Response200));
1310        assert!(annotated.features.contains(&ConformanceFeature::Response404));
1311    }
1312
1313    #[test]
1314    fn test_generate_spec_driven_script() {
1315        let config = ConformanceConfig {
1316            target_url: "http://localhost:3000".to_string(),
1317            api_key: None,
1318            basic_auth: None,
1319            skip_tls_verify: false,
1320            categories: None,
1321            base_path: None,
1322            custom_headers: vec![],
1323            output_dir: None,
1324            all_operations: false,
1325            custom_checks_file: None,
1326            request_delay_ms: 0,
1327            custom_filter: None,
1328            export_requests: false,
1329        };
1330
1331        let operations = vec![AnnotatedOperation {
1332            path: "/users/{id}".to_string(),
1333            method: "GET".to_string(),
1334            features: vec![
1335                ConformanceFeature::MethodGet,
1336                ConformanceFeature::PathParamString,
1337            ],
1338            request_body_content_type: None,
1339            sample_body: None,
1340            query_params: vec![],
1341            header_params: vec![],
1342            path_params: vec![("id".to_string(), "test-value".to_string())],
1343            response_schema: None,
1344            security_schemes: vec![],
1345        }];
1346
1347        let gen = SpecDrivenConformanceGenerator::new(config, operations);
1348        let (script, _check_count) = gen.generate().unwrap();
1349
1350        assert!(script.contains("import http from 'k6/http'"));
1351        assert!(script.contains("/users/test-value"));
1352        assert!(script.contains("param:path:string"));
1353        assert!(script.contains("method:GET"));
1354        assert!(script.contains("handleSummary"));
1355    }
1356
1357    #[test]
1358    fn test_generate_with_category_filter() {
1359        let config = ConformanceConfig {
1360            target_url: "http://localhost:3000".to_string(),
1361            api_key: None,
1362            basic_auth: None,
1363            skip_tls_verify: false,
1364            categories: Some(vec!["Parameters".to_string()]),
1365            base_path: None,
1366            custom_headers: vec![],
1367            output_dir: None,
1368            all_operations: false,
1369            custom_checks_file: None,
1370            request_delay_ms: 0,
1371            custom_filter: None,
1372            export_requests: false,
1373        };
1374
1375        let operations = vec![AnnotatedOperation {
1376            path: "/users/{id}".to_string(),
1377            method: "GET".to_string(),
1378            features: vec![
1379                ConformanceFeature::MethodGet,
1380                ConformanceFeature::PathParamString,
1381            ],
1382            request_body_content_type: None,
1383            sample_body: None,
1384            query_params: vec![],
1385            header_params: vec![],
1386            path_params: vec![("id".to_string(), "1".to_string())],
1387            response_schema: None,
1388            security_schemes: vec![],
1389        }];
1390
1391        let gen = SpecDrivenConformanceGenerator::new(config, operations);
1392        let (script, _check_count) = gen.generate().unwrap();
1393
1394        assert!(script.contains("group('Parameters'"));
1395        assert!(!script.contains("group('HTTP Methods'"));
1396    }
1397
1398    #[test]
1399    fn test_annotate_response_validation() {
1400        use openapiv3::ObjectType;
1401
1402        // Operation with a 200 response that has a JSON schema
1403        let mut op = Operation::default();
1404        let mut response = Response::default();
1405        let mut media = openapiv3::MediaType::default();
1406        let mut obj_type = ObjectType::default();
1407        obj_type.properties.insert(
1408            "name".to_string(),
1409            ReferenceOr::Item(Box::new(Schema {
1410                schema_data: SchemaData::default(),
1411                schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1412            })),
1413        );
1414        obj_type.required = vec!["name".to_string()];
1415        media.schema = Some(ReferenceOr::Item(Schema {
1416            schema_data: SchemaData::default(),
1417            schema_kind: SchemaKind::Type(Type::Object(obj_type)),
1418        }));
1419        response.content.insert("application/json".to_string(), media);
1420        op.responses
1421            .responses
1422            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1423
1424        let api_op = make_op("get", "/users", op);
1425        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1426
1427        assert!(
1428            annotated.features.contains(&ConformanceFeature::ResponseValidation),
1429            "Should detect ResponseValidation when response has a JSON schema"
1430        );
1431        assert!(annotated.response_schema.is_some(), "Should extract the response schema");
1432
1433        // Verify generated script includes schema validation with try-catch
1434        let config = ConformanceConfig {
1435            target_url: "http://localhost:3000".to_string(),
1436            api_key: None,
1437            basic_auth: None,
1438            skip_tls_verify: false,
1439            categories: None,
1440            base_path: None,
1441            custom_headers: vec![],
1442            output_dir: None,
1443            all_operations: false,
1444            custom_checks_file: None,
1445            request_delay_ms: 0,
1446            custom_filter: None,
1447            export_requests: false,
1448        };
1449        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1450        let (script, _check_count) = gen.generate().unwrap();
1451
1452        assert!(
1453            script.contains("response:schema:validation"),
1454            "Script should contain the validation check name"
1455        );
1456        assert!(script.contains("try {"), "Script should wrap validation in try-catch");
1457        assert!(script.contains("res.json()"), "Script should parse response as JSON");
1458    }
1459
1460    #[test]
1461    fn test_annotate_global_security() {
1462        // Spec with global security requirement, operation without its own security
1463        let op = Operation::default();
1464        let mut spec = OpenAPI::default();
1465        let mut global_req = openapiv3::SecurityRequirement::new();
1466        global_req.insert("bearerAuth".to_string(), vec![]);
1467        spec.security = Some(vec![global_req]);
1468        // Define the security scheme in components
1469        let mut components = openapiv3::Components::default();
1470        components.security_schemes.insert(
1471            "bearerAuth".to_string(),
1472            ReferenceOr::Item(SecurityScheme::HTTP {
1473                scheme: "bearer".to_string(),
1474                bearer_format: Some("JWT".to_string()),
1475                description: None,
1476                extensions: Default::default(),
1477            }),
1478        );
1479        spec.components = Some(components);
1480
1481        let api_op = make_op("get", "/protected", op);
1482        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1483
1484        assert!(
1485            annotated.features.contains(&ConformanceFeature::SecurityBearer),
1486            "Should detect SecurityBearer from global security + components"
1487        );
1488    }
1489
1490    #[test]
1491    fn test_annotate_security_scheme_resolution() {
1492        // Test that security scheme type is resolved from components, not just name heuristic
1493        let mut op = Operation::default();
1494        // Use a generic name that wouldn't match name heuristics
1495        let mut req = openapiv3::SecurityRequirement::new();
1496        req.insert("myAuth".to_string(), vec![]);
1497        op.security = Some(vec![req]);
1498
1499        let mut spec = OpenAPI::default();
1500        let mut components = openapiv3::Components::default();
1501        components.security_schemes.insert(
1502            "myAuth".to_string(),
1503            ReferenceOr::Item(SecurityScheme::APIKey {
1504                location: openapiv3::APIKeyLocation::Header,
1505                name: "X-API-Key".to_string(),
1506                description: None,
1507                extensions: Default::default(),
1508            }),
1509        );
1510        spec.components = Some(components);
1511
1512        let api_op = make_op("get", "/data", op);
1513        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1514
1515        assert!(
1516            annotated.features.contains(&ConformanceFeature::SecurityApiKey),
1517            "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
1518        );
1519    }
1520
1521    #[test]
1522    fn test_annotate_content_negotiation() {
1523        let mut op = Operation::default();
1524        let mut response = Response::default();
1525        // Response with multiple content types
1526        response
1527            .content
1528            .insert("application/json".to_string(), openapiv3::MediaType::default());
1529        response
1530            .content
1531            .insert("application/xml".to_string(), openapiv3::MediaType::default());
1532        op.responses
1533            .responses
1534            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1535
1536        let api_op = make_op("get", "/items", op);
1537        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1538
1539        assert!(
1540            annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1541            "Should detect ContentNegotiation when response has multiple content types"
1542        );
1543    }
1544
1545    #[test]
1546    fn test_no_content_negotiation_for_single_type() {
1547        let mut op = Operation::default();
1548        let mut response = Response::default();
1549        response
1550            .content
1551            .insert("application/json".to_string(), openapiv3::MediaType::default());
1552        op.responses
1553            .responses
1554            .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1555
1556        let api_op = make_op("get", "/items", op);
1557        let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1558
1559        assert!(
1560            !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1561            "Should NOT detect ContentNegotiation for a single content type"
1562        );
1563    }
1564
1565    #[test]
1566    fn test_spec_driven_with_base_path() {
1567        let annotated = AnnotatedOperation {
1568            path: "/users".to_string(),
1569            method: "GET".to_string(),
1570            features: vec![ConformanceFeature::MethodGet],
1571            path_params: vec![],
1572            query_params: vec![],
1573            header_params: vec![],
1574            request_body_content_type: None,
1575            sample_body: None,
1576            response_schema: None,
1577            security_schemes: vec![],
1578        };
1579        let config = ConformanceConfig {
1580            target_url: "https://192.168.2.86/".to_string(),
1581            api_key: None,
1582            basic_auth: None,
1583            skip_tls_verify: true,
1584            categories: None,
1585            base_path: Some("/api".to_string()),
1586            custom_headers: vec![],
1587            output_dir: None,
1588            all_operations: false,
1589            custom_checks_file: None,
1590            request_delay_ms: 0,
1591            custom_filter: None,
1592            export_requests: false,
1593        };
1594        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1595        let (script, _check_count) = gen.generate().unwrap();
1596
1597        assert!(
1598            script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
1599            "BASE_URL should include the base_path. Got: {}",
1600            script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
1601        );
1602    }
1603
1604    #[test]
1605    fn test_spec_driven_with_custom_headers() {
1606        let annotated = AnnotatedOperation {
1607            path: "/users".to_string(),
1608            method: "GET".to_string(),
1609            features: vec![ConformanceFeature::MethodGet],
1610            path_params: vec![],
1611            query_params: vec![],
1612            header_params: vec![
1613                ("X-Avi-Tenant".to_string(), "test-value".to_string()),
1614                ("X-CSRFToken".to_string(), "test-value".to_string()),
1615            ],
1616            request_body_content_type: None,
1617            sample_body: None,
1618            response_schema: None,
1619            security_schemes: vec![],
1620        };
1621        let config = ConformanceConfig {
1622            target_url: "https://192.168.2.86/".to_string(),
1623            api_key: None,
1624            basic_auth: None,
1625            skip_tls_verify: true,
1626            categories: None,
1627            base_path: Some("/api".to_string()),
1628            custom_headers: vec![
1629                ("X-Avi-Tenant".to_string(), "admin".to_string()),
1630                ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
1631                ("Cookie".to_string(), "sessionid=abc123".to_string()),
1632            ],
1633            output_dir: None,
1634            all_operations: false,
1635            custom_checks_file: None,
1636            request_delay_ms: 0,
1637            custom_filter: None,
1638            export_requests: false,
1639        };
1640        let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1641        let (script, _check_count) = gen.generate().unwrap();
1642
1643        // Custom headers should override spec-derived test-value placeholders
1644        assert!(
1645            script.contains("'X-Avi-Tenant': 'admin'"),
1646            "Should use custom value for X-Avi-Tenant, not test-value"
1647        );
1648        assert!(
1649            script.contains("'X-CSRFToken': 'real-csrf-token'"),
1650            "Should use custom value for X-CSRFToken, not test-value"
1651        );
1652        // Custom headers not in spec should be appended
1653        assert!(
1654            script.contains("'Cookie': 'sessionid=abc123'"),
1655            "Should include Cookie header from custom_headers"
1656        );
1657        // test-value should NOT appear
1658        assert!(
1659            !script.contains("'test-value'"),
1660            "test-value placeholders should be replaced by custom values"
1661        );
1662    }
1663
1664    #[test]
1665    fn test_effective_headers_merging() {
1666        let config = ConformanceConfig {
1667            target_url: "http://localhost".to_string(),
1668            api_key: None,
1669            basic_auth: None,
1670            skip_tls_verify: false,
1671            categories: None,
1672            base_path: None,
1673            custom_headers: vec![
1674                ("X-Auth".to_string(), "real-token".to_string()),
1675                ("Cookie".to_string(), "session=abc".to_string()),
1676            ],
1677            output_dir: None,
1678            all_operations: false,
1679            custom_checks_file: None,
1680            request_delay_ms: 0,
1681            custom_filter: None,
1682            export_requests: false,
1683        };
1684        let gen = SpecDrivenConformanceGenerator::new(config, vec![]);
1685
1686        // Spec headers with a matching custom header
1687        let spec_headers = vec![
1688            ("X-Auth".to_string(), "test-value".to_string()),
1689            ("X-Other".to_string(), "keep-this".to_string()),
1690        ];
1691        let effective = gen.effective_headers(&spec_headers);
1692
1693        // X-Auth should be overridden
1694        assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
1695        // X-Other should be kept as-is
1696        assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
1697        // Cookie should be appended
1698        assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
1699    }
1700}