1use 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
18mod 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 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 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; }
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 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 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 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#[derive(Debug, Clone)]
146pub enum SecuritySchemeInfo {
147 Bearer,
149 Basic,
151 ApiKey {
153 location: ApiKeyLocation,
154 name: String,
155 },
156}
157
158#[derive(Debug, Clone, PartialEq)]
160pub enum ApiKeyLocation {
161 Header,
162 Query,
163 Cookie,
164}
165
166#[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 pub response_schema: Option<Schema>,
179 pub security_schemes: Vec<SecuritySchemeInfo>,
181}
182
183pub 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 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 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 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 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 for segment in op.path.split('/') {
237 if segment.starts_with('{') && segment.ends_with('}') {
238 let name = &segment[1..segment.len() - 1];
239 if !path_params.iter().any(|(n, _)| n == name) {
241 path_params.push((name.to_string(), "test-value".to_string()));
242 if !features.contains(&ConformanceFeature::PathParamString)
244 && !features.contains(&ConformanceFeature::PathParamInteger)
245 {
246 features.push(ConformanceFeature::PathParamString);
247 }
248 }
249 }
250 }
251
252 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 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 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 Self::annotate_responses(&op.operation, spec, &mut features);
300
301 let response_schema = Self::extract_response_schema(&op.operation, spec);
303 if response_schema.is_some() {
304 features.push(ConformanceFeature::ResponseValidation);
305 }
306
307 Self::annotate_content_negotiation(&op.operation, spec, &mut features);
309
310 let mut security_schemes = Vec::new();
312 Self::annotate_security(&op.operation, spec, &mut features, &mut security_schemes);
313
314 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 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 let is_integer = Self::param_schema_is_integer(data, spec);
353 let is_array = Self::param_schema_is_array(data, spec);
354
355 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 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 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 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 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 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 if !obj.required.is_empty() {
487 features.push(ConformanceFeature::ConstraintRequired);
488 }
489 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 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 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 fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
543 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 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; }
574 }
575 }
576 }
577
578 fn annotate_security(
582 operation: &Operation,
583 spec: &OpenAPI,
584 features: &mut Vec<ConformanceFeature>,
585 security_schemes: &mut Vec<SecuritySchemeInfo>,
586 ) {
587 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 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 _ => {}
619 }
620 } else {
621 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 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 pub fn operation_count(&self) -> usize {
653 self.operations.len()
654 }
655
656 pub fn generate(&self) -> Result<(String, usize)> {
659 let mut script = String::with_capacity(16384);
660
661 script.push_str("import http from 'k6/http';\n");
663 script.push_str("import { check, group } from 'k6';\n\n");
664
665 script.push_str("export const options = {\n");
667 script.push_str(" vus: 1,\n");
668 script.push_str(" iterations: 1,\n");
669 if self.config.skip_tls_verify {
670 script.push_str(" insecureSkipTLSVerify: true,\n");
671 }
672 script.push_str(" thresholds: {\n");
673 script.push_str(" checks: ['rate>0'],\n");
674 script.push_str(" },\n");
675 script.push_str("};\n\n");
676
677 script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
679 script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
680
681 script.push_str("function __captureFailure(checkName, res, expected) {\n");
684 script.push_str(" let bodyStr = '';\n");
685 script.push_str(" try { bodyStr = res.body ? res.body.substring(0, 2000) : ''; } catch(e) { bodyStr = '<unreadable>'; }\n");
686 script.push_str(" let reqHeaders = {};\n");
687 script.push_str(
688 " if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
689 );
690 script.push_str(" let reqBody = '';\n");
691 script.push_str(" if (res.request && res.request.body) { try { reqBody = res.request.body.substring(0, 2000); } catch(e) {} }\n");
692 script.push_str(" console.log('MOCKFORGE_FAILURE:' + JSON.stringify({\n");
693 script.push_str(" check: checkName,\n");
694 script.push_str(" request: {\n");
695 script.push_str(" method: res.request ? res.request.method : 'unknown',\n");
696 script.push_str(" url: res.request ? res.request.url : res.url || 'unknown',\n");
697 script.push_str(" headers: reqHeaders,\n");
698 script.push_str(" body: reqBody,\n");
699 script.push_str(" },\n");
700 script.push_str(" response: {\n");
701 script.push_str(" status: res.status,\n");
702 script.push_str(" headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
703 script.push_str(" body: bodyStr,\n");
704 script.push_str(" },\n");
705 script.push_str(" expected: expected,\n");
706 script.push_str(" }));\n");
707 script.push_str("}\n\n");
708
709 script.push_str("export default function () {\n");
711
712 if self.config.has_cookie_header() {
713 script.push_str(
714 " // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
715 );
716 script.push_str(" http.cookieJar().clear(BASE_URL);\n\n");
717 }
718
719 let mut category_ops: std::collections::BTreeMap<
721 &'static str,
722 Vec<(&AnnotatedOperation, &ConformanceFeature)>,
723 > = std::collections::BTreeMap::new();
724
725 for op in &self.operations {
726 for feature in &op.features {
727 let category = feature.category();
728 if self.config.should_include_category(category) {
729 category_ops.entry(category).or_default().push((op, feature));
730 }
731 }
732 }
733
734 let mut total_checks = 0usize;
736 for (category, ops) in &category_ops {
737 script.push_str(&format!(" group('{}', function () {{\n", category));
738
739 if self.config.all_operations {
740 let mut emitted_checks: HashSet<String> = HashSet::new();
742 for (op, feature) in ops {
743 let qualified = format!("{}:{}", feature.check_name(), op.path);
744 if emitted_checks.insert(qualified.clone()) {
745 self.emit_check_named(&mut script, op, feature, &qualified);
746 total_checks += 1;
747 }
748 }
749 } else {
750 let mut emitted_features: HashSet<&str> = HashSet::new();
753 for (op, feature) in ops {
754 if emitted_features.insert(feature.check_name()) {
755 let qualified = format!("{}:{}", feature.check_name(), op.path);
756 self.emit_check_named(&mut script, op, feature, &qualified);
757 total_checks += 1;
758 }
759 }
760 }
761
762 script.push_str(" });\n\n");
763 }
764
765 script.push_str("}\n\n");
766
767 self.generate_handle_summary(&mut script);
769
770 Ok((script, total_checks))
771 }
772
773 fn emit_check_named(
775 &self,
776 script: &mut String,
777 op: &AnnotatedOperation,
778 feature: &ConformanceFeature,
779 check_name: &str,
780 ) {
781 let check_name = check_name.replace('\'', "\\'");
783 let check_name = check_name.as_str();
784
785 script.push_str(" {\n");
786
787 let mut url_path = op.path.clone();
789 for (name, value) in &op.path_params {
790 url_path = url_path.replace(&format!("{{{}}}", name), value);
791 }
792
793 if !op.query_params.is_empty() {
795 let qs: Vec<String> =
796 op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
797 url_path = format!("{}?{}", url_path, qs.join("&"));
798 }
799
800 let full_url = format!("${{BASE_URL}}{}", url_path);
801
802 let mut effective_headers = self.effective_headers(&op.header_params);
805
806 if matches!(feature, ConformanceFeature::Response400 | ConformanceFeature::Response404) {
809 let expected_code = match feature {
810 ConformanceFeature::Response400 => "400",
811 ConformanceFeature::Response404 => "404",
812 _ => unreachable!(),
813 };
814 effective_headers
815 .push(("X-Mockforge-Response-Status".to_string(), expected_code.to_string()));
816 }
817
818 let needs_auth = matches!(
822 feature,
823 ConformanceFeature::SecurityBearer
824 | ConformanceFeature::SecurityBasic
825 | ConformanceFeature::SecurityApiKey
826 ) || !op.security_schemes.is_empty();
827
828 if needs_auth {
829 self.inject_security_headers(&op.security_schemes, &mut effective_headers);
830 }
831
832 let has_headers = !effective_headers.is_empty();
833 let headers_obj = if has_headers {
834 Self::format_headers(&effective_headers)
835 } else {
836 String::new()
837 };
838
839 match op.method.as_str() {
841 "GET" => {
842 if has_headers {
843 script.push_str(&format!(
844 " let res = http.get(`{}`, {{ headers: {} }});\n",
845 full_url, headers_obj
846 ));
847 } else {
848 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
849 }
850 }
851 "POST" => {
852 self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
853 }
854 "PUT" => {
855 self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
856 }
857 "PATCH" => {
858 self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
859 }
860 "DELETE" => {
861 if has_headers {
862 script.push_str(&format!(
863 " let res = http.del(`{}`, null, {{ headers: {} }});\n",
864 full_url, headers_obj
865 ));
866 } else {
867 script.push_str(&format!(" let res = http.del(`{}`);\n", full_url));
868 }
869 }
870 "HEAD" => {
871 if has_headers {
872 script.push_str(&format!(
873 " let res = http.head(`{}`, {{ headers: {} }});\n",
874 full_url, headers_obj
875 ));
876 } else {
877 script.push_str(&format!(" let res = http.head(`{}`);\n", full_url));
878 }
879 }
880 "OPTIONS" => {
881 if has_headers {
882 script.push_str(&format!(
883 " let res = http.options(`{}`, null, {{ headers: {} }});\n",
884 full_url, headers_obj
885 ));
886 } else {
887 script.push_str(&format!(" let res = http.options(`{}`);\n", full_url));
888 }
889 }
890 _ => {
891 if has_headers {
892 script.push_str(&format!(
893 " let res = http.get(`{}`, {{ headers: {} }});\n",
894 full_url, headers_obj
895 ));
896 } else {
897 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
898 }
899 }
900 }
901
902 if matches!(
904 feature,
905 ConformanceFeature::Response200
906 | ConformanceFeature::Response201
907 | ConformanceFeature::Response204
908 | ConformanceFeature::Response400
909 | ConformanceFeature::Response404
910 ) {
911 let expected_code = match feature {
912 ConformanceFeature::Response200 => 200,
913 ConformanceFeature::Response201 => 201,
914 ConformanceFeature::Response204 => 204,
915 ConformanceFeature::Response400 => 400,
916 ConformanceFeature::Response404 => 404,
917 _ => 200,
918 };
919 script.push_str(&format!(
920 " {{ let ok = check(res, {{ '{}': (r) => r.status === {} }}); if (!ok) __captureFailure('{}', res, 'status === {}'); }}\n",
921 check_name, expected_code, check_name, expected_code
922 ));
923 } else if matches!(feature, ConformanceFeature::ResponseValidation) {
924 if let Some(schema) = &op.response_schema {
926 let validation_js = SchemaValidatorGenerator::generate_validation(schema);
927 script.push_str(&format!(
928 " try {{ let body = res.json(); {{ let ok = check(res, {{ '{}': (r) => ( {} ) }}); if (!ok) __captureFailure('{}', res, 'schema validation'); }} }} catch(e) {{ check(res, {{ '{}': () => false }}); __captureFailure('{}', res, 'JSON parse failed: ' + e.message); }}\n",
929 check_name, validation_js, check_name, check_name, check_name
930 ));
931 }
932 } else if matches!(
933 feature,
934 ConformanceFeature::SecurityBearer
935 | ConformanceFeature::SecurityBasic
936 | ConformanceFeature::SecurityApiKey
937 ) {
938 script.push_str(&format!(
940 " {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 400 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 400 (auth accepted)'); }}\n",
941 check_name, check_name
942 ));
943 } else {
944 script.push_str(&format!(
945 " {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 500'); }}\n",
946 check_name, check_name
947 ));
948 }
949
950 let has_cookie = self.config.has_cookie_header()
952 || effective_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case("Cookie"));
953 if has_cookie {
954 script.push_str(" http.cookieJar().clear(BASE_URL);\n");
955 }
956
957 script.push_str(" }\n");
958 }
959
960 fn emit_request_with_body(
962 &self,
963 script: &mut String,
964 method: &str,
965 url: &str,
966 op: &AnnotatedOperation,
967 effective_headers: &[(String, String)],
968 ) {
969 if let Some(body) = &op.sample_body {
970 let escaped_body = body.replace('\'', "\\'");
971 let headers = if !effective_headers.is_empty() {
972 format!(
973 "Object.assign({{}}, JSON_HEADERS, {})",
974 Self::format_headers(effective_headers)
975 )
976 } else {
977 "JSON_HEADERS".to_string()
978 };
979 script.push_str(&format!(
980 " let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
981 method, url, escaped_body, headers
982 ));
983 } else if !effective_headers.is_empty() {
984 script.push_str(&format!(
985 " let res = http.{}(`{}`, null, {{ headers: {} }});\n",
986 method,
987 url,
988 Self::format_headers(effective_headers)
989 ));
990 } else {
991 script.push_str(&format!(" let res = http.{}(`{}`, null);\n", method, url));
992 }
993 }
994
995 fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
999 let custom = &self.config.custom_headers;
1000 if custom.is_empty() {
1001 return spec_headers.to_vec();
1002 }
1003
1004 let mut result: Vec<(String, String)> = Vec::new();
1005
1006 for (name, value) in spec_headers {
1008 if let Some((_, custom_val)) =
1009 custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
1010 {
1011 result.push((name.clone(), custom_val.clone()));
1012 } else {
1013 result.push((name.clone(), value.clone()));
1014 }
1015 }
1016
1017 for (name, value) in custom {
1019 if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
1020 result.push((name.clone(), value.clone()));
1021 }
1022 }
1023
1024 result
1025 }
1026
1027 fn inject_security_headers(
1030 &self,
1031 schemes: &[SecuritySchemeInfo],
1032 headers: &mut Vec<(String, String)>,
1033 ) {
1034 let mut to_add: Vec<(String, String)> = Vec::new();
1035
1036 let has_header = |name: &str, headers: &[(String, String)]| {
1037 headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1038 || self.config.custom_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1039 };
1040
1041 for scheme in schemes {
1042 match scheme {
1043 SecuritySchemeInfo::Bearer => {
1044 if !has_header("Authorization", headers) {
1045 to_add.push((
1047 "Authorization".to_string(),
1048 "Bearer mockforge-conformance-test-token".to_string(),
1049 ));
1050 }
1051 }
1052 SecuritySchemeInfo::Basic => {
1053 if !has_header("Authorization", headers) {
1054 let creds = self.config.basic_auth.as_deref().unwrap_or("test:test");
1055 use base64::Engine;
1056 let encoded =
1057 base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
1058 to_add.push(("Authorization".to_string(), format!("Basic {}", encoded)));
1059 }
1060 }
1061 SecuritySchemeInfo::ApiKey { location, name } => match location {
1062 ApiKeyLocation::Header => {
1063 if !has_header(name, headers) {
1064 let key = self
1065 .config
1066 .api_key
1067 .as_deref()
1068 .unwrap_or("mockforge-conformance-test-key");
1069 to_add.push((name.clone(), key.to_string()));
1070 }
1071 }
1072 ApiKeyLocation::Cookie => {
1073 if !has_header("Cookie", headers) {
1074 to_add.push((
1075 "Cookie".to_string(),
1076 format!("{}=mockforge-conformance-test-session", name),
1077 ));
1078 }
1079 }
1080 ApiKeyLocation::Query => {
1081 }
1083 },
1084 }
1085 }
1086
1087 headers.extend(to_add);
1088 }
1089
1090 fn format_headers(headers: &[(String, String)]) -> String {
1092 let entries: Vec<String> = headers
1093 .iter()
1094 .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
1095 .collect();
1096 format!("{{ {} }}", entries.join(", "))
1097 }
1098
1099 fn generate_handle_summary(&self, script: &mut String) {
1101 let report_path = match &self.config.output_dir {
1103 Some(dir) => {
1104 let abs = std::fs::canonicalize(dir)
1105 .unwrap_or_else(|_| dir.clone())
1106 .join("conformance-report.json");
1107 abs.to_string_lossy().to_string()
1108 }
1109 None => "conformance-report.json".to_string(),
1110 };
1111
1112 script.push_str("export function handleSummary(data) {\n");
1113 script.push_str(" let checks = {};\n");
1114 script.push_str(" if (data.metrics && data.metrics.checks) {\n");
1115 script.push_str(" checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1116 script.push_str(" }\n");
1117 script.push_str(" let checkResults = {};\n");
1118 script.push_str(" function walkGroups(group) {\n");
1119 script.push_str(" if (group.checks) {\n");
1120 script.push_str(" for (let checkObj of group.checks) {\n");
1121 script.push_str(" checkResults[checkObj.name] = {\n");
1122 script.push_str(" passes: checkObj.passes,\n");
1123 script.push_str(" fails: checkObj.fails,\n");
1124 script.push_str(" };\n");
1125 script.push_str(" }\n");
1126 script.push_str(" }\n");
1127 script.push_str(" if (group.groups) {\n");
1128 script.push_str(" for (let subGroup of group.groups) {\n");
1129 script.push_str(" walkGroups(subGroup);\n");
1130 script.push_str(" }\n");
1131 script.push_str(" }\n");
1132 script.push_str(" }\n");
1133 script.push_str(" if (data.root_group) {\n");
1134 script.push_str(" walkGroups(data.root_group);\n");
1135 script.push_str(" }\n");
1136 script.push_str(" return {\n");
1137 script.push_str(&format!(
1138 " '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1139 report_path
1140 ));
1141 script.push_str(" stdout: textSummary(data, { indent: ' ', enableColors: true }),\n");
1142 script.push_str(" };\n");
1143 script.push_str("}\n\n");
1144 script.push_str("function textSummary(data, opts) {\n");
1145 script.push_str(" return JSON.stringify(data, null, 2);\n");
1146 script.push_str("}\n");
1147 }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152 use super::*;
1153 use openapiv3::{
1154 Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
1155 SchemaData, SchemaKind, StringType, Type,
1156 };
1157
1158 fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
1159 ApiOperation {
1160 method: method.to_string(),
1161 path: path.to_string(),
1162 operation,
1163 operation_id: None,
1164 }
1165 }
1166
1167 fn empty_spec() -> OpenAPI {
1168 OpenAPI::default()
1169 }
1170
1171 #[test]
1172 fn test_annotate_get_with_path_param() {
1173 let mut op = Operation::default();
1174 op.parameters.push(ReferenceOr::Item(Parameter::Path {
1175 parameter_data: ParameterData {
1176 name: "id".to_string(),
1177 description: None,
1178 required: true,
1179 deprecated: None,
1180 format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
1181 schema_data: SchemaData::default(),
1182 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1183 })),
1184 example: None,
1185 examples: Default::default(),
1186 explode: None,
1187 extensions: Default::default(),
1188 },
1189 style: PathStyle::Simple,
1190 }));
1191
1192 let api_op = make_op("get", "/users/{id}", op);
1193 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1194
1195 assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
1196 assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
1197 assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
1198 assert_eq!(annotated.path_params.len(), 1);
1199 assert_eq!(annotated.path_params[0].0, "id");
1200 }
1201
1202 #[test]
1203 fn test_annotate_post_with_json_body() {
1204 let mut op = Operation::default();
1205 let mut body = openapiv3::RequestBody {
1206 required: true,
1207 ..Default::default()
1208 };
1209 body.content
1210 .insert("application/json".to_string(), openapiv3::MediaType::default());
1211 op.request_body = Some(ReferenceOr::Item(body));
1212
1213 let api_op = make_op("post", "/items", op);
1214 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1215
1216 assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
1217 assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
1218 }
1219
1220 #[test]
1221 fn test_annotate_response_codes() {
1222 let mut op = Operation::default();
1223 op.responses
1224 .responses
1225 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
1226 op.responses
1227 .responses
1228 .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));
1229
1230 let api_op = make_op("get", "/items", op);
1231 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1232
1233 assert!(annotated.features.contains(&ConformanceFeature::Response200));
1234 assert!(annotated.features.contains(&ConformanceFeature::Response404));
1235 }
1236
1237 #[test]
1238 fn test_generate_spec_driven_script() {
1239 let config = ConformanceConfig {
1240 target_url: "http://localhost:3000".to_string(),
1241 api_key: None,
1242 basic_auth: None,
1243 skip_tls_verify: false,
1244 categories: None,
1245 base_path: None,
1246 custom_headers: vec![],
1247 output_dir: None,
1248 all_operations: false,
1249 };
1250
1251 let operations = vec![AnnotatedOperation {
1252 path: "/users/{id}".to_string(),
1253 method: "GET".to_string(),
1254 features: vec![
1255 ConformanceFeature::MethodGet,
1256 ConformanceFeature::PathParamString,
1257 ],
1258 request_body_content_type: None,
1259 sample_body: None,
1260 query_params: vec![],
1261 header_params: vec![],
1262 path_params: vec![("id".to_string(), "test-value".to_string())],
1263 response_schema: None,
1264 security_schemes: vec![],
1265 }];
1266
1267 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1268 let (script, _check_count) = gen.generate().unwrap();
1269
1270 assert!(script.contains("import http from 'k6/http'"));
1271 assert!(script.contains("/users/test-value"));
1272 assert!(script.contains("param:path:string"));
1273 assert!(script.contains("method:GET"));
1274 assert!(script.contains("handleSummary"));
1275 }
1276
1277 #[test]
1278 fn test_generate_with_category_filter() {
1279 let config = ConformanceConfig {
1280 target_url: "http://localhost:3000".to_string(),
1281 api_key: None,
1282 basic_auth: None,
1283 skip_tls_verify: false,
1284 categories: Some(vec!["Parameters".to_string()]),
1285 base_path: None,
1286 custom_headers: vec![],
1287 output_dir: None,
1288 all_operations: false,
1289 };
1290
1291 let operations = vec![AnnotatedOperation {
1292 path: "/users/{id}".to_string(),
1293 method: "GET".to_string(),
1294 features: vec![
1295 ConformanceFeature::MethodGet,
1296 ConformanceFeature::PathParamString,
1297 ],
1298 request_body_content_type: None,
1299 sample_body: None,
1300 query_params: vec![],
1301 header_params: vec![],
1302 path_params: vec![("id".to_string(), "1".to_string())],
1303 response_schema: None,
1304 security_schemes: vec![],
1305 }];
1306
1307 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1308 let (script, _check_count) = gen.generate().unwrap();
1309
1310 assert!(script.contains("group('Parameters'"));
1311 assert!(!script.contains("group('HTTP Methods'"));
1312 }
1313
1314 #[test]
1315 fn test_annotate_response_validation() {
1316 use openapiv3::ObjectType;
1317
1318 let mut op = Operation::default();
1320 let mut response = Response::default();
1321 let mut media = openapiv3::MediaType::default();
1322 let mut obj_type = ObjectType::default();
1323 obj_type.properties.insert(
1324 "name".to_string(),
1325 ReferenceOr::Item(Box::new(Schema {
1326 schema_data: SchemaData::default(),
1327 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1328 })),
1329 );
1330 obj_type.required = vec!["name".to_string()];
1331 media.schema = Some(ReferenceOr::Item(Schema {
1332 schema_data: SchemaData::default(),
1333 schema_kind: SchemaKind::Type(Type::Object(obj_type)),
1334 }));
1335 response.content.insert("application/json".to_string(), media);
1336 op.responses
1337 .responses
1338 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1339
1340 let api_op = make_op("get", "/users", op);
1341 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1342
1343 assert!(
1344 annotated.features.contains(&ConformanceFeature::ResponseValidation),
1345 "Should detect ResponseValidation when response has a JSON schema"
1346 );
1347 assert!(annotated.response_schema.is_some(), "Should extract the response schema");
1348
1349 let config = ConformanceConfig {
1351 target_url: "http://localhost:3000".to_string(),
1352 api_key: None,
1353 basic_auth: None,
1354 skip_tls_verify: false,
1355 categories: None,
1356 base_path: None,
1357 custom_headers: vec![],
1358 output_dir: None,
1359 all_operations: false,
1360 };
1361 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1362 let (script, _check_count) = gen.generate().unwrap();
1363
1364 assert!(
1365 script.contains("response:schema:validation"),
1366 "Script should contain the validation check name"
1367 );
1368 assert!(script.contains("try {"), "Script should wrap validation in try-catch");
1369 assert!(script.contains("res.json()"), "Script should parse response as JSON");
1370 }
1371
1372 #[test]
1373 fn test_annotate_global_security() {
1374 let op = Operation::default();
1376 let mut spec = OpenAPI::default();
1377 let mut global_req = openapiv3::SecurityRequirement::new();
1378 global_req.insert("bearerAuth".to_string(), vec![]);
1379 spec.security = Some(vec![global_req]);
1380 let mut components = openapiv3::Components::default();
1382 components.security_schemes.insert(
1383 "bearerAuth".to_string(),
1384 ReferenceOr::Item(SecurityScheme::HTTP {
1385 scheme: "bearer".to_string(),
1386 bearer_format: Some("JWT".to_string()),
1387 description: None,
1388 extensions: Default::default(),
1389 }),
1390 );
1391 spec.components = Some(components);
1392
1393 let api_op = make_op("get", "/protected", op);
1394 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1395
1396 assert!(
1397 annotated.features.contains(&ConformanceFeature::SecurityBearer),
1398 "Should detect SecurityBearer from global security + components"
1399 );
1400 }
1401
1402 #[test]
1403 fn test_annotate_security_scheme_resolution() {
1404 let mut op = Operation::default();
1406 let mut req = openapiv3::SecurityRequirement::new();
1408 req.insert("myAuth".to_string(), vec![]);
1409 op.security = Some(vec![req]);
1410
1411 let mut spec = OpenAPI::default();
1412 let mut components = openapiv3::Components::default();
1413 components.security_schemes.insert(
1414 "myAuth".to_string(),
1415 ReferenceOr::Item(SecurityScheme::APIKey {
1416 location: openapiv3::APIKeyLocation::Header,
1417 name: "X-API-Key".to_string(),
1418 description: None,
1419 extensions: Default::default(),
1420 }),
1421 );
1422 spec.components = Some(components);
1423
1424 let api_op = make_op("get", "/data", op);
1425 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1426
1427 assert!(
1428 annotated.features.contains(&ConformanceFeature::SecurityApiKey),
1429 "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
1430 );
1431 }
1432
1433 #[test]
1434 fn test_annotate_content_negotiation() {
1435 let mut op = Operation::default();
1436 let mut response = Response::default();
1437 response
1439 .content
1440 .insert("application/json".to_string(), openapiv3::MediaType::default());
1441 response
1442 .content
1443 .insert("application/xml".to_string(), openapiv3::MediaType::default());
1444 op.responses
1445 .responses
1446 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1447
1448 let api_op = make_op("get", "/items", op);
1449 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1450
1451 assert!(
1452 annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1453 "Should detect ContentNegotiation when response has multiple content types"
1454 );
1455 }
1456
1457 #[test]
1458 fn test_no_content_negotiation_for_single_type() {
1459 let mut op = Operation::default();
1460 let mut response = Response::default();
1461 response
1462 .content
1463 .insert("application/json".to_string(), openapiv3::MediaType::default());
1464 op.responses
1465 .responses
1466 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1467
1468 let api_op = make_op("get", "/items", op);
1469 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1470
1471 assert!(
1472 !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1473 "Should NOT detect ContentNegotiation for a single content type"
1474 );
1475 }
1476
1477 #[test]
1478 fn test_spec_driven_with_base_path() {
1479 let annotated = AnnotatedOperation {
1480 path: "/users".to_string(),
1481 method: "GET".to_string(),
1482 features: vec![ConformanceFeature::MethodGet],
1483 path_params: vec![],
1484 query_params: vec![],
1485 header_params: vec![],
1486 request_body_content_type: None,
1487 sample_body: None,
1488 response_schema: None,
1489 security_schemes: vec![],
1490 };
1491 let config = ConformanceConfig {
1492 target_url: "https://192.168.2.86/".to_string(),
1493 api_key: None,
1494 basic_auth: None,
1495 skip_tls_verify: true,
1496 categories: None,
1497 base_path: Some("/api".to_string()),
1498 custom_headers: vec![],
1499 output_dir: None,
1500 all_operations: false,
1501 };
1502 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1503 let (script, _check_count) = gen.generate().unwrap();
1504
1505 assert!(
1506 script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
1507 "BASE_URL should include the base_path. Got: {}",
1508 script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
1509 );
1510 }
1511
1512 #[test]
1513 fn test_spec_driven_with_custom_headers() {
1514 let annotated = AnnotatedOperation {
1515 path: "/users".to_string(),
1516 method: "GET".to_string(),
1517 features: vec![ConformanceFeature::MethodGet],
1518 path_params: vec![],
1519 query_params: vec![],
1520 header_params: vec![
1521 ("X-Avi-Tenant".to_string(), "test-value".to_string()),
1522 ("X-CSRFToken".to_string(), "test-value".to_string()),
1523 ],
1524 request_body_content_type: None,
1525 sample_body: None,
1526 response_schema: None,
1527 security_schemes: vec![],
1528 };
1529 let config = ConformanceConfig {
1530 target_url: "https://192.168.2.86/".to_string(),
1531 api_key: None,
1532 basic_auth: None,
1533 skip_tls_verify: true,
1534 categories: None,
1535 base_path: Some("/api".to_string()),
1536 custom_headers: vec![
1537 ("X-Avi-Tenant".to_string(), "admin".to_string()),
1538 ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
1539 ("Cookie".to_string(), "sessionid=abc123".to_string()),
1540 ],
1541 output_dir: None,
1542 all_operations: false,
1543 };
1544 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1545 let (script, _check_count) = gen.generate().unwrap();
1546
1547 assert!(
1549 script.contains("'X-Avi-Tenant': 'admin'"),
1550 "Should use custom value for X-Avi-Tenant, not test-value"
1551 );
1552 assert!(
1553 script.contains("'X-CSRFToken': 'real-csrf-token'"),
1554 "Should use custom value for X-CSRFToken, not test-value"
1555 );
1556 assert!(
1558 script.contains("'Cookie': 'sessionid=abc123'"),
1559 "Should include Cookie header from custom_headers"
1560 );
1561 assert!(
1563 !script.contains("'test-value'"),
1564 "test-value placeholders should be replaced by custom values"
1565 );
1566 }
1567
1568 #[test]
1569 fn test_effective_headers_merging() {
1570 let config = ConformanceConfig {
1571 target_url: "http://localhost".to_string(),
1572 api_key: None,
1573 basic_auth: None,
1574 skip_tls_verify: false,
1575 categories: None,
1576 base_path: None,
1577 custom_headers: vec![
1578 ("X-Auth".to_string(), "real-token".to_string()),
1579 ("Cookie".to_string(), "session=abc".to_string()),
1580 ],
1581 output_dir: None,
1582 all_operations: false,
1583 };
1584 let gen = SpecDrivenConformanceGenerator::new(config, vec![]);
1585
1586 let spec_headers = vec![
1588 ("X-Auth".to_string(), "test-value".to_string()),
1589 ("X-Other".to_string(), "keep-this".to_string()),
1590 ];
1591 let effective = gen.effective_headers(&spec_headers);
1592
1593 assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
1595 assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
1597 assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
1599 }
1600}