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 response_schemas: std::collections::BTreeMap<u16, serde_json::Value>,
187 pub request_body_schema: Option<Schema>,
193 pub security_schemes: Vec<SecuritySchemeInfo>,
195}
196
197pub struct SpecDrivenConformanceGenerator {
199 config: ConformanceConfig,
200 operations: Vec<AnnotatedOperation>,
201}
202
203impl SpecDrivenConformanceGenerator {
204 pub fn new(config: ConformanceConfig, operations: Vec<AnnotatedOperation>) -> Self {
205 Self { config, operations }
206 }
207
208 pub fn annotate_operations(
210 operations: &[ApiOperation],
211 spec: &OpenAPI,
212 ) -> Vec<AnnotatedOperation> {
213 operations.iter().map(|op| Self::annotate_operation(op, spec)).collect()
214 }
215
216 fn annotate_operation(op: &ApiOperation, spec: &OpenAPI) -> AnnotatedOperation {
218 let mut features = Vec::new();
219 let mut query_params = Vec::new();
220 let mut header_params = Vec::new();
221 let mut path_params = Vec::new();
222
223 match op.method.to_uppercase().as_str() {
225 "GET" => features.push(ConformanceFeature::MethodGet),
226 "POST" => features.push(ConformanceFeature::MethodPost),
227 "PUT" => features.push(ConformanceFeature::MethodPut),
228 "PATCH" => features.push(ConformanceFeature::MethodPatch),
229 "DELETE" => features.push(ConformanceFeature::MethodDelete),
230 "HEAD" => features.push(ConformanceFeature::MethodHead),
231 "OPTIONS" => features.push(ConformanceFeature::MethodOptions),
232 _ => {}
233 }
234
235 for param_ref in &op.operation.parameters {
237 if let Some(param) = ref_resolver::resolve_parameter(param_ref, spec) {
238 Self::annotate_parameter(
239 param,
240 spec,
241 &mut features,
242 &mut query_params,
243 &mut header_params,
244 &mut path_params,
245 );
246 }
247 }
248
249 for segment in op.path.split('/') {
251 if segment.starts_with('{') && segment.ends_with('}') {
252 let name = &segment[1..segment.len() - 1];
253 if !path_params.iter().any(|(n, _)| n == name) {
255 path_params.push((name.to_string(), "test-value".to_string()));
256 if !features.contains(&ConformanceFeature::PathParamString)
258 && !features.contains(&ConformanceFeature::PathParamInteger)
259 {
260 features.push(ConformanceFeature::PathParamString);
261 }
262 }
263 }
264 }
265
266 let mut request_body_content_type = None;
268 let mut sample_body = None;
269 let mut request_body_schema: Option<Schema> = None;
270
271 let resolved_body = op
272 .operation
273 .request_body
274 .as_ref()
275 .and_then(|b| ref_resolver::resolve_request_body(b, spec));
276
277 if let Some(body) = resolved_body {
278 for (content_type, _media) in &body.content {
279 match content_type.as_str() {
280 "application/json" => {
281 features.push(ConformanceFeature::BodyJson);
282 request_body_content_type = Some("application/json".to_string());
283 if let Ok(template) = RequestGenerator::generate_template(op) {
285 if let Some(body_val) = &template.body {
286 sample_body = Some(body_val.to_string());
287 }
288 }
289 }
290 "application/x-www-form-urlencoded" => {
291 features.push(ConformanceFeature::BodyFormUrlencoded);
292 request_body_content_type =
293 Some("application/x-www-form-urlencoded".to_string());
294 }
295 "multipart/form-data" => {
296 features.push(ConformanceFeature::BodyMultipart);
297 request_body_content_type = Some("multipart/form-data".to_string());
298 }
299 _ => {}
300 }
301 }
302
303 if let Some(media) = body.content.get("application/json") {
305 if let Some(schema_ref) = &media.schema {
306 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
307 Self::annotate_schema(schema, spec, &mut features);
308 request_body_schema = Some(schema.clone());
312 }
313 }
314 }
315 }
316
317 Self::annotate_responses(&op.operation, spec, &mut features);
319
320 let response_schema = Self::extract_response_schema(&op.operation, spec);
322 if response_schema.is_some() {
323 features.push(ConformanceFeature::ResponseValidation);
324 }
325 let response_schemas = Self::extract_response_schemas_per_status(&op.operation, spec);
327
328 Self::annotate_content_negotiation(&op.operation, spec, &mut features);
330
331 let mut security_schemes = Vec::new();
333 Self::annotate_security(&op.operation, spec, &mut features, &mut security_schemes);
334
335 features.sort_by_key(|f| f.check_name());
337 features.dedup_by_key(|f| f.check_name());
338
339 AnnotatedOperation {
340 path: op.path.clone(),
341 method: op.method.to_uppercase(),
342 features,
343 request_body_content_type,
344 sample_body,
345 query_params,
346 header_params,
347 path_params,
348 response_schema,
349 response_schemas,
350 request_body_schema,
351 security_schemes,
352 }
353 }
354
355 fn annotate_parameter(
357 param: &Parameter,
358 spec: &OpenAPI,
359 features: &mut Vec<ConformanceFeature>,
360 query_params: &mut Vec<(String, String)>,
361 header_params: &mut Vec<(String, String)>,
362 path_params: &mut Vec<(String, String)>,
363 ) {
364 let (location, data) = match param {
365 Parameter::Query { parameter_data, .. } => ("query", parameter_data),
366 Parameter::Path { parameter_data, .. } => ("path", parameter_data),
367 Parameter::Header { parameter_data, .. } => ("header", parameter_data),
368 Parameter::Cookie { .. } => {
369 features.push(ConformanceFeature::CookieParam);
370 return;
371 }
372 };
373
374 let is_integer = Self::param_schema_is_integer(data, spec);
376 let is_array = Self::param_schema_is_array(data, spec);
377
378 let sample = if is_integer {
380 "42".to_string()
381 } else if is_array {
382 "a,b".to_string()
383 } else {
384 "test-value".to_string()
385 };
386
387 match location {
388 "path" => {
389 if is_integer {
390 features.push(ConformanceFeature::PathParamInteger);
391 } else {
392 features.push(ConformanceFeature::PathParamString);
393 }
394 path_params.push((data.name.clone(), sample));
395 }
396 "query" => {
397 if is_array {
398 features.push(ConformanceFeature::QueryParamArray);
399 } else if is_integer {
400 features.push(ConformanceFeature::QueryParamInteger);
401 } else {
402 features.push(ConformanceFeature::QueryParamString);
403 }
404 query_params.push((data.name.clone(), sample));
405 }
406 "header" => {
407 features.push(ConformanceFeature::HeaderParam);
408 header_params.push((data.name.clone(), sample));
409 }
410 _ => {}
411 }
412
413 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
415 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
416 Self::annotate_schema(schema, spec, features);
417 }
418 }
419
420 if data.required {
422 features.push(ConformanceFeature::ConstraintRequired);
423 } else {
424 features.push(ConformanceFeature::ConstraintOptional);
425 }
426 }
427
428 fn param_schema_is_integer(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
429 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
430 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
431 return matches!(&schema.schema_kind, SchemaKind::Type(Type::Integer(_)));
432 }
433 }
434 false
435 }
436
437 fn param_schema_is_array(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
438 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
439 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
440 return matches!(&schema.schema_kind, SchemaKind::Type(Type::Array(_)));
441 }
442 }
443 false
444 }
445
446 fn annotate_schema(schema: &Schema, spec: &OpenAPI, features: &mut Vec<ConformanceFeature>) {
448 match &schema.schema_kind {
449 SchemaKind::Type(Type::String(s)) => {
450 features.push(ConformanceFeature::SchemaString);
451 match &s.format {
453 VariantOrUnknownOrEmpty::Item(StringFormat::Date) => {
454 features.push(ConformanceFeature::FormatDate);
455 }
456 VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
457 features.push(ConformanceFeature::FormatDateTime);
458 }
459 VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
460 "email" => features.push(ConformanceFeature::FormatEmail),
461 "uuid" => features.push(ConformanceFeature::FormatUuid),
462 "uri" | "url" => features.push(ConformanceFeature::FormatUri),
463 "ipv4" => features.push(ConformanceFeature::FormatIpv4),
464 "ipv6" => features.push(ConformanceFeature::FormatIpv6),
465 _ => {}
466 },
467 _ => {}
468 }
469 if s.pattern.is_some() {
471 features.push(ConformanceFeature::ConstraintPattern);
472 }
473 if !s.enumeration.is_empty() {
474 features.push(ConformanceFeature::ConstraintEnum);
475 }
476 if s.min_length.is_some() || s.max_length.is_some() {
477 features.push(ConformanceFeature::ConstraintMinMax);
478 }
479 }
480 SchemaKind::Type(Type::Integer(i)) => {
481 features.push(ConformanceFeature::SchemaInteger);
482 if i.minimum.is_some() || i.maximum.is_some() {
483 features.push(ConformanceFeature::ConstraintMinMax);
484 }
485 if !i.enumeration.is_empty() {
486 features.push(ConformanceFeature::ConstraintEnum);
487 }
488 }
489 SchemaKind::Type(Type::Number(n)) => {
490 features.push(ConformanceFeature::SchemaNumber);
491 if n.minimum.is_some() || n.maximum.is_some() {
492 features.push(ConformanceFeature::ConstraintMinMax);
493 }
494 }
495 SchemaKind::Type(Type::Boolean(_)) => {
496 features.push(ConformanceFeature::SchemaBoolean);
497 }
498 SchemaKind::Type(Type::Array(arr)) => {
499 features.push(ConformanceFeature::SchemaArray);
500 if let Some(item_ref) = &arr.items {
501 if let Some(item_schema) = ref_resolver::resolve_boxed_schema(item_ref, spec) {
502 Self::annotate_schema(item_schema, spec, features);
503 }
504 }
505 }
506 SchemaKind::Type(Type::Object(obj)) => {
507 features.push(ConformanceFeature::SchemaObject);
508 if !obj.required.is_empty() {
510 features.push(ConformanceFeature::ConstraintRequired);
511 }
512 for (_name, prop_ref) in &obj.properties {
514 if let Some(prop_schema) = ref_resolver::resolve_boxed_schema(prop_ref, spec) {
515 Self::annotate_schema(prop_schema, spec, features);
516 }
517 }
518 }
519 SchemaKind::OneOf { .. } => {
520 features.push(ConformanceFeature::CompositionOneOf);
521 }
522 SchemaKind::AnyOf { .. } => {
523 features.push(ConformanceFeature::CompositionAnyOf);
524 }
525 SchemaKind::AllOf { .. } => {
526 features.push(ConformanceFeature::CompositionAllOf);
527 }
528 _ => {}
529 }
530 }
531
532 fn annotate_responses(
534 operation: &Operation,
535 spec: &OpenAPI,
536 features: &mut Vec<ConformanceFeature>,
537 ) {
538 for (status_code, resp_ref) in &operation.responses.responses {
539 if ref_resolver::resolve_response(resp_ref, spec).is_some() {
541 match status_code {
542 openapiv3::StatusCode::Code(200) => {
543 features.push(ConformanceFeature::Response200)
544 }
545 openapiv3::StatusCode::Code(201) => {
546 features.push(ConformanceFeature::Response201)
547 }
548 openapiv3::StatusCode::Code(204) => {
549 features.push(ConformanceFeature::Response204)
550 }
551 openapiv3::StatusCode::Code(400) => {
552 features.push(ConformanceFeature::Response400)
553 }
554 openapiv3::StatusCode::Code(404) => {
555 features.push(ConformanceFeature::Response404)
556 }
557 _ => {}
558 }
559 }
560 }
561 }
562
563 fn extract_response_schemas_per_status(
569 operation: &Operation,
570 spec: &OpenAPI,
571 ) -> std::collections::BTreeMap<u16, serde_json::Value> {
572 let mut out = std::collections::BTreeMap::new();
573 for (code, resp_ref) in &operation.responses.responses {
574 let openapiv3::StatusCode::Code(n) = code else {
575 continue; };
577 let Some(response) = ref_resolver::resolve_response(resp_ref, spec) else {
578 continue;
579 };
580 let Some(media) = response.content.get("application/json") else {
581 continue;
582 };
583 let Some(schema_ref) = &media.schema else {
584 continue;
585 };
586 let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) else {
587 continue;
588 };
589 if let Ok(value) = serde_json::to_value(schema) {
592 out.insert(*n, value);
593 }
594 }
595 out
596 }
597
598 fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
601 for code in [200u16, 201] {
603 if let Some(resp_ref) =
604 operation.responses.responses.get(&openapiv3::StatusCode::Code(code))
605 {
606 if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
607 if let Some(media) = response.content.get("application/json") {
608 if let Some(schema_ref) = &media.schema {
609 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
610 return Some(schema.clone());
611 }
612 }
613 }
614 }
615 }
616 }
617 None
618 }
619
620 fn annotate_content_negotiation(
622 operation: &Operation,
623 spec: &OpenAPI,
624 features: &mut Vec<ConformanceFeature>,
625 ) {
626 for (_status_code, resp_ref) in &operation.responses.responses {
627 if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
628 if response.content.len() > 1 {
629 features.push(ConformanceFeature::ContentNegotiation);
630 return; }
632 }
633 }
634 }
635
636 fn annotate_security(
640 operation: &Operation,
641 spec: &OpenAPI,
642 features: &mut Vec<ConformanceFeature>,
643 security_schemes: &mut Vec<SecuritySchemeInfo>,
644 ) {
645 let security_reqs = operation.security.as_ref().or(spec.security.as_ref());
647
648 if let Some(security) = security_reqs {
649 for security_req in security {
650 for scheme_name in security_req.keys() {
651 if let Some(resolved) = Self::resolve_security_scheme(scheme_name, spec) {
653 match resolved {
654 SecurityScheme::HTTP { ref scheme, .. } => {
655 if scheme.eq_ignore_ascii_case("bearer") {
656 features.push(ConformanceFeature::SecurityBearer);
657 security_schemes.push(SecuritySchemeInfo::Bearer);
658 } else if scheme.eq_ignore_ascii_case("basic") {
659 features.push(ConformanceFeature::SecurityBasic);
660 security_schemes.push(SecuritySchemeInfo::Basic);
661 }
662 }
663 SecurityScheme::APIKey { location, name, .. } => {
664 features.push(ConformanceFeature::SecurityApiKey);
665 let loc = match location {
666 openapiv3::APIKeyLocation::Query => ApiKeyLocation::Query,
667 openapiv3::APIKeyLocation::Header => ApiKeyLocation::Header,
668 openapiv3::APIKeyLocation::Cookie => ApiKeyLocation::Cookie,
669 };
670 security_schemes.push(SecuritySchemeInfo::ApiKey {
671 location: loc,
672 name: name.clone(),
673 });
674 }
675 _ => {}
677 }
678 } else {
679 let name_lower = scheme_name.to_lowercase();
681 if name_lower.contains("bearer") || name_lower.contains("jwt") {
682 features.push(ConformanceFeature::SecurityBearer);
683 security_schemes.push(SecuritySchemeInfo::Bearer);
684 } else if name_lower.contains("api") && name_lower.contains("key") {
685 features.push(ConformanceFeature::SecurityApiKey);
686 security_schemes.push(SecuritySchemeInfo::ApiKey {
687 location: ApiKeyLocation::Header,
688 name: "X-API-Key".to_string(),
689 });
690 } else if name_lower.contains("basic") {
691 features.push(ConformanceFeature::SecurityBasic);
692 security_schemes.push(SecuritySchemeInfo::Basic);
693 }
694 }
695 }
696 }
697 }
698 }
699
700 fn resolve_security_scheme<'a>(name: &str, spec: &'a OpenAPI) -> Option<&'a SecurityScheme> {
702 let components = spec.components.as_ref()?;
703 match components.security_schemes.get(name)? {
704 ReferenceOr::Item(scheme) => Some(scheme),
705 ReferenceOr::Reference { .. } => None,
706 }
707 }
708
709 pub fn operation_count(&self) -> usize {
711 self.operations.len()
712 }
713
714 pub fn generate(&self) -> Result<(String, usize)> {
717 let mut script = String::with_capacity(16384);
718
719 script.push_str("import http from 'k6/http';\n");
721 script.push_str("import { check, group } from 'k6';\n");
722 if self.config.request_delay_ms > 0 {
723 script.push_str("import { sleep } from 'k6';\n");
724 }
725 script.push('\n');
726
727 script.push_str(
731 "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
732 );
733
734 script.push_str("export const options = {\n");
736 script.push_str(" vus: 1,\n");
737 script.push_str(" iterations: 1,\n");
738 if self.config.skip_tls_verify {
739 script.push_str(" insecureSkipTLSVerify: true,\n");
740 }
741 script.push_str(" thresholds: {\n");
742 script.push_str(" checks: ['rate>0'],\n");
743 script.push_str(" },\n");
744 script.push_str("};\n\n");
745
746 script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
748 script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
749
750 let custom_emit = self.config.generate_custom_group()?;
754 if let Some(emit) = &custom_emit {
755 if !emit.init_code.is_empty() {
756 script.push_str("// Round 39 (#79) — preloaded upload bytes for custom checks\n");
757 script.push_str(&emit.init_code);
758 script.push('\n');
759 }
760 }
761
762 script
765 .push_str("function __captureFailure(checkName, res, expected, schemaViolations) {\n");
766 script.push_str(" let bodyStr = '';\n");
767 script.push_str(" try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
768 script.push_str(" let reqHeaders = {};\n");
769 script.push_str(
770 " if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
771 );
772 script.push_str(" let reqBody = '';\n");
773 script.push_str(" if (res.request && res.request.body) { try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch(e) {} }\n");
774 script.push_str(" let payload = {\n");
775 script.push_str(" check: checkName,\n");
776 script.push_str(" request: {\n");
777 script.push_str(" method: res.request ? res.request.method : 'unknown',\n");
778 script.push_str(" url: res.request ? res.request.url : res.url || 'unknown',\n");
779 script.push_str(" headers: reqHeaders,\n");
780 script.push_str(" body: reqBody,\n");
781 script.push_str(" },\n");
782 script.push_str(" response: {\n");
783 script.push_str(" status: res.status,\n");
784 script.push_str(" headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
785 script.push_str(" body: bodyStr,\n");
786 script.push_str(" },\n");
787 script.push_str(" expected: expected,\n");
788 script.push_str(" };\n");
789 script.push_str(" if (schemaViolations && schemaViolations.length > 0) { payload.schema_violations = schemaViolations; }\n");
790 script.push_str(" console.log('MOCKFORGE_FAILURE:' + JSON.stringify(payload));\n");
791 script.push_str("}\n\n");
792
793 if self.config.export_requests {
802 script.push_str("function __captureExchange(checkName, res) {\n");
803 script.push_str(" try {\n");
804 script.push_str(" let bodyStr = '';\n");
805 script.push_str(" try { if (res.body) { const __n = res.body.length; bodyStr = res.body.substring(0, 65536); if (__n > 65536) bodyStr = bodyStr + ' <truncated at 65536 bytes; full body was ' + __n + ' bytes>'; } else { bodyStr = ''; } } catch(e) { bodyStr = '<unreadable>'; }\n");
806 script.push_str(" let reqHeaders = {};\n");
807 script.push_str(
808 " if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
809 );
810 script.push_str(" let reqBody = '';\n");
814 script.push_str(" {\n");
815 script.push_str(
816 " const ct = (reqHeaders['Content-Type'] || reqHeaders['content-type'] || '').toString();\n",
817 );
818 script.push_str(" const isMultipart = ct.startsWith('multipart/');\n");
819 script.push_str(
820 " if (isMultipart && res.request && res.request.body) {\n\
821 \x20\x20\x20\x20\x20\x20\x20\x20try {\n\
822 \x20\x20\x20\x20\x20\x20\x20\x20 const raw = res.request.body;\n\
823 \x20\x20\x20\x20\x20\x20\x20\x20 let totalBytes = raw.length;\n\
824 \x20\x20\x20\x20\x20\x20\x20\x20 const boundaryMatch = ct.match(/boundary=([^;]+)/);\n\
825 \x20\x20\x20\x20\x20\x20\x20\x20 const boundary = boundaryMatch ? boundaryMatch[1].replace(/^\"|\"$/g, '') : '';\n\
826 \x20\x20\x20\x20\x20\x20\x20\x20 const parts = [];\n\
827 \x20\x20\x20\x20\x20\x20\x20\x20 if (boundary) {\n\
828 \x20\x20\x20\x20\x20\x20\x20\x20 const sep = '--' + boundary;\n\
829 \x20\x20\x20\x20\x20\x20\x20\x20 let cursor = raw.indexOf(sep);\n\
830 \x20\x20\x20\x20\x20\x20\x20\x20 while (cursor !== -1 && parts.length < 100) {\n\
831 \x20\x20\x20\x20\x20\x20\x20\x20 const next = raw.indexOf(sep, cursor + sep.length);\n\
832 \x20\x20\x20\x20\x20\x20\x20\x20 if (next === -1) break;\n\
833 \x20\x20\x20\x20\x20\x20\x20\x20 const slice = raw.substring(cursor + sep.length, next);\n\
834 \x20\x20\x20\x20\x20\x20\x20\x20 const headerEnd = slice.indexOf('\\r\\n\\r\\n');\n\
835 \x20\x20\x20\x20\x20\x20\x20\x20 const partHeaders = headerEnd === -1 ? slice : slice.substring(0, headerEnd);\n\
836 \x20\x20\x20\x20\x20\x20\x20\x20 const partBody = headerEnd === -1 ? '' : slice.substring(headerEnd + 4);\n\
837 \x20\x20\x20\x20\x20\x20\x20\x20 const nameMatch = partHeaders.match(/name=\"([^\"]+)\"/);\n\
838 \x20\x20\x20\x20\x20\x20\x20\x20 const filenameMatch = partHeaders.match(/filename=\"([^\"]+)\"/);\n\
839 \x20\x20\x20\x20\x20\x20\x20\x20 const partCtMatch = partHeaders.match(/Content-Type:\\s*([^\\r\\n]+)/i);\n\
840 \x20\x20\x20\x20\x20\x20\x20\x20 parts.push({\n\
841 \x20\x20\x20\x20\x20\x20\x20\x20 name: nameMatch ? nameMatch[1] : '',\n\
842 \x20\x20\x20\x20\x20\x20\x20\x20 filename: filenameMatch ? filenameMatch[1] : '',\n\
843 \x20\x20\x20\x20\x20\x20\x20\x20 contentType: partCtMatch ? partCtMatch[1].trim() : '',\n\
844 \x20\x20\x20\x20\x20\x20\x20\x20 bytes: Math.max(0, partBody.length - 2),\n\
845 \x20\x20\x20\x20\x20\x20\x20\x20 });\n\
846 \x20\x20\x20\x20\x20\x20\x20\x20 cursor = next;\n\
847 \x20\x20\x20\x20\x20\x20\x20\x20 }\n\
848 \x20\x20\x20\x20\x20\x20\x20\x20 }\n\
849 \x20\x20\x20\x20\x20\x20\x20\x20 // Round 47 #79 — overlay on-disk byte counts (see generator.rs).\n\
850 \x20\x20\x20\x20\x20\x20\x20\x20 const __mfSizes = (globalThis.__mfUploadSizes || {})[checkName] || {};\n\
851 \x20\x20\x20\x20\x20\x20\x20\x20 parts.forEach(function (p) { if (typeof __mfSizes[p.name] === 'number') p.bytes = __mfSizes[p.name]; });\n\
852 \x20\x20\x20\x20\x20\x20\x20\x20 const summary = parts.map(function (p) { return '\\'' + p.name + '\\':\\'' + p.filename + '\\' (' + p.contentType + ', ' + p.bytes + ' bytes)'; }).join(', ');\n\
853 \x20\x20\x20\x20\x20\x20\x20\x20 reqBody = '<multipart/form-data; boundary=' + boundary + '; ' + parts.length + ' part(s); total ' + totalBytes + ' bytes: ' + summary + '>';\n\
854 \x20\x20\x20\x20\x20\x20\x20\x20} catch (e) {\n\
855 \x20\x20\x20\x20\x20\x20\x20\x20 reqBody = '<multipart upload; summary failed: ' + (e && e.message ? e.message : 'unknown') + '>';\n\
856 \x20\x20\x20\x20\x20\x20\x20\x20}\n\
857 \x20\x20\x20\x20\x20\x20} else if (isMultipart) {\n\
858 \x20\x20\x20\x20\x20\x20\x20\x20reqBody = '<multipart upload; body bytes not surfaced by k6 res.request.body>';\n\
859 \x20\x20\x20\x20\x20\x20} else if (res.request && res.request.body) {\n\
860 \x20\x20\x20\x20\x20\x20\x20\x20try { const __m = res.request.body.length; reqBody = res.request.body.substring(0, 65536); if (__m > 65536) reqBody = reqBody + ' <truncated at 65536 bytes; full body was ' + __m + ' bytes>'; } catch (e) {}\n\
861 \x20\x20\x20\x20\x20\x20}\n\
862 \x20\x20\x20\x20}\n",
863 );
864 script.push_str(
866 " if (res && res.status === 0) {\n\
867 \x20\x20\x20\x20\x20\x20const ec = (res.error_code != null) ? res.error_code : 0;\n\
868 \x20\x20\x20\x20\x20\x20const em = (res.error != null) ? String(res.error) : '';\n\
869 \x20\x20\x20\x20\x20\x20let kind = 'other';\n\
870 \x20\x20\x20\x20\x20\x20if (ec >= 1200 && ec < 1300) kind = 'connect';\n\
871 \x20\x20\x20\x20\x20\x20else if (ec >= 1300 && ec < 1400) kind = 'tls';\n\
872 \x20\x20\x20\x20\x20\x20else if (ec >= 1400 && ec < 1500) kind = 'timeout';\n\
873 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('eof') !== -1) kind = 'connect';\n \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('timeout') !== -1) kind = 'timeout';\n\
874 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('tls') !== -1) kind = 'tls';\n\
875 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('connect') !== -1 || em.toLowerCase().indexOf('refused') !== -1) kind = 'connect';\n\
876 \x20\x20\x20\x20\x20\x20console.log('MOCKFORGE_NETWORK_EVENT:' + JSON.stringify({\n\
877 \x20\x20\x20\x20\x20\x20 timestamp: new Date().toISOString(),\n\
878 \x20\x20\x20\x20\x20\x20 check: checkName,\n\
879 \x20\x20\x20\x20\x20\x20 method: res.request ? res.request.method : 'unknown',\n\
880 \x20\x20\x20\x20\x20\x20 url: res.request ? res.request.url : res.url || 'unknown',\n\
881 \x20\x20\x20\x20\x20\x20 kind: kind,\n\
882 \x20\x20\x20\x20\x20\x20 error_code: ec,\n\
883 \x20\x20\x20\x20\x20\x20 message: em,\n\
884 \x20\x20\x20\x20\x20\x20}));\n\
885 \x20\x20\x20\x20}\n",
886 );
887 script.push_str(" console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
888 script.push_str(" check: checkName,\n");
889 script.push_str(" request: {\n");
890 script.push_str(" method: res.request ? res.request.method : 'unknown',\n");
891 script.push_str(" url: res.request ? res.request.url : res.url || 'unknown',\n");
892 script.push_str(" headers: reqHeaders,\n");
893 script.push_str(" body: reqBody,\n");
894 script.push_str(" },\n");
895 script.push_str(" response: {\n");
896 script.push_str(" status: res.status,\n");
897 script.push_str(" headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
898 script.push_str(" body: bodyStr,\n");
899 script.push_str(" },\n");
900 script.push_str(" }));\n");
901 script.push_str(" } catch (e) {\n");
902 script.push_str(" try {\n");
903 script.push_str(" console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
904 script.push_str(" check: checkName,\n");
905 script.push_str(" request: {\n");
906 script.push_str(
907 " method: (res && res.request) ? res.request.method : 'unknown',\n",
908 );
909 script.push_str(" url: (res && res.request) ? res.request.url : (res && res.url) || 'unknown',\n");
910 script.push_str(" headers: {},\n");
911 script.push_str(" body: '<exchange capture failed: ' + (e && e.message ? e.message : 'unknown error') + '>',\n");
912 script.push_str(" },\n");
913 script.push_str(" response: {\n");
914 script.push_str(" status: (res && res.status) || 0,\n");
915 script.push_str(" headers: {},\n");
916 script.push_str(" body: '',\n");
917 script.push_str(" },\n");
918 script.push_str(" _export_error: (e && e.message) ? e.message : String(e),\n");
919 script.push_str(" }));\n");
920 script.push_str(" } catch (e2) {\n");
921 script.push_str(" console.log('MOCKFORGE_EXCHANGE:{\"check\":\"' + checkName + '\",\"request\":{\"method\":\"unknown\",\"url\":\"unknown\",\"headers\":{},\"body\":\"\"},\"response\":{\"status\":0,\"headers\":{},\"body\":\"\"},\"_export_error\":\"double-fault\"}');\n");
922 script.push_str(" }\n");
923 script.push_str(" }\n");
924 script.push_str("}\n\n");
925 }
926
927 script.push_str("export default function () {\n");
929
930 if self.config.has_cookie_header() {
931 script.push_str(
932 " // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
933 );
934 script.push_str(" http.cookieJar().clear(BASE_URL);\n\n");
935 }
936
937 let mut category_ops: std::collections::BTreeMap<
939 &'static str,
940 Vec<(&AnnotatedOperation, &ConformanceFeature)>,
941 > = std::collections::BTreeMap::new();
942
943 for op in &self.operations {
944 for feature in &op.features {
945 let category = feature.category();
946 if self.config.should_include_category(category) {
947 category_ops.entry(category).or_default().push((op, feature));
948 }
949 }
950 }
951
952 let mut total_checks = 0usize;
954 for (category, ops) in &category_ops {
955 script.push_str(&format!(" group('{}', function () {{\n", category));
956
957 if self.config.all_operations {
958 let mut emitted_checks: HashSet<String> = HashSet::new();
960 for (op, feature) in ops {
961 let qualified = format!("{}:{}", feature.check_name(), op.path);
962 if emitted_checks.insert(qualified.clone()) {
963 self.emit_check_named(&mut script, op, feature, &qualified);
964 total_checks += 1;
965 }
966 }
967 } else {
968 let mut emitted_features: HashSet<&str> = HashSet::new();
971 for (op, feature) in ops {
972 if emitted_features.insert(feature.check_name()) {
973 let qualified = format!("{}:{}", feature.check_name(), op.path);
974 self.emit_check_named(&mut script, op, feature, &qualified);
975 total_checks += 1;
976 }
977 }
978 }
979
980 script.push_str(" });\n\n");
981 }
982
983 if let Some(emit) = custom_emit {
987 script.push_str(&emit.group_body);
988 }
989
990 script.push_str("}\n\n");
991
992 self.generate_handle_summary(&mut script);
994
995 Ok((script, total_checks))
996 }
997
998 fn emit_check_named(
1000 &self,
1001 script: &mut String,
1002 op: &AnnotatedOperation,
1003 feature: &ConformanceFeature,
1004 check_name: &str,
1005 ) {
1006 let check_name = check_name.replace('\'', "\\'");
1008 let check_name = check_name.as_str();
1009
1010 script.push_str(" {\n");
1011
1012 let mut url_path = op.path.clone();
1014 for (name, value) in &op.path_params {
1015 url_path = url_path.replace(&format!("{{{}}}", name), value);
1016 }
1017
1018 if !op.query_params.is_empty() {
1020 let qs: Vec<String> =
1021 op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
1022 url_path = format!("{}?{}", url_path, qs.join("&"));
1023 }
1024
1025 let full_url = format!("${{BASE_URL}}{}", url_path);
1026
1027 let mut effective_headers = self.effective_headers(&op.header_params);
1030
1031 if matches!(feature, ConformanceFeature::Response400 | ConformanceFeature::Response404) {
1034 let expected_code = match feature {
1035 ConformanceFeature::Response400 => "400",
1036 ConformanceFeature::Response404 => "404",
1037 _ => unreachable!(),
1038 };
1039 effective_headers
1040 .push(("X-Mockforge-Response-Status".to_string(), expected_code.to_string()));
1041 }
1042
1043 let needs_auth = matches!(
1047 feature,
1048 ConformanceFeature::SecurityBearer
1049 | ConformanceFeature::SecurityBasic
1050 | ConformanceFeature::SecurityApiKey
1051 ) || !op.security_schemes.is_empty();
1052
1053 if needs_auth {
1054 self.inject_security_headers(&op.security_schemes, &mut effective_headers);
1055 }
1056
1057 let has_headers = !effective_headers.is_empty();
1058 let headers_obj = if has_headers {
1059 Self::format_headers(&effective_headers)
1060 } else {
1061 String::new()
1062 };
1063
1064 match op.method.as_str() {
1066 "GET" => {
1067 if has_headers {
1068 script.push_str(&format!(
1069 " let res = http.get(`{}`, {{ headers: {} }});\n",
1070 full_url, headers_obj
1071 ));
1072 } else {
1073 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
1074 }
1075 }
1076 "POST" => {
1077 self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
1078 }
1079 "PUT" => {
1080 self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
1081 }
1082 "PATCH" => {
1083 self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
1084 }
1085 "DELETE" => {
1086 if has_headers {
1087 script.push_str(&format!(
1088 " let res = http.del(`{}`, null, {{ headers: {} }});\n",
1089 full_url, headers_obj
1090 ));
1091 } else {
1092 script.push_str(&format!(" let res = http.del(`{}`);\n", full_url));
1093 }
1094 }
1095 "HEAD" => {
1096 if has_headers {
1097 script.push_str(&format!(
1098 " let res = http.head(`{}`, {{ headers: {} }});\n",
1099 full_url, headers_obj
1100 ));
1101 } else {
1102 script.push_str(&format!(" let res = http.head(`{}`);\n", full_url));
1103 }
1104 }
1105 "OPTIONS" => {
1106 if has_headers {
1107 script.push_str(&format!(
1108 " let res = http.options(`{}`, null, {{ headers: {} }});\n",
1109 full_url, headers_obj
1110 ));
1111 } else {
1112 script.push_str(&format!(" let res = http.options(`{}`);\n", full_url));
1113 }
1114 }
1115 _ => {
1116 if has_headers {
1117 script.push_str(&format!(
1118 " let res = http.get(`{}`, {{ headers: {} }});\n",
1119 full_url, headers_obj
1120 ));
1121 } else {
1122 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
1123 }
1124 }
1125 }
1126
1127 if self.config.export_requests {
1130 script.push_str(&format!(
1131 " if (typeof __captureExchange === 'function') __captureExchange('{}', res);\n",
1132 check_name
1133 ));
1134 }
1135
1136 if matches!(
1138 feature,
1139 ConformanceFeature::Response200
1140 | ConformanceFeature::Response201
1141 | ConformanceFeature::Response204
1142 | ConformanceFeature::Response400
1143 | ConformanceFeature::Response404
1144 ) {
1145 let expected_code = match feature {
1146 ConformanceFeature::Response200 => 200,
1147 ConformanceFeature::Response201 => 201,
1148 ConformanceFeature::Response204 => 204,
1149 ConformanceFeature::Response400 => 400,
1150 ConformanceFeature::Response404 => 404,
1151 _ => 200,
1152 };
1153 script.push_str(&format!(
1154 " {{ let ok = check(res, {{ '{}': (r) => r.status === {} }}); if (!ok) __captureFailure('{}', res, 'status === {}'); }}\n",
1155 check_name, expected_code, check_name, expected_code
1156 ));
1157 } else if matches!(feature, ConformanceFeature::ResponseValidation) {
1158 if let Some(schema) = &op.response_schema {
1163 let validation_js = SchemaValidatorGenerator::generate_validation(schema);
1164 let schema_json = serde_json::to_string(schema).unwrap_or_default();
1165 let schema_json_escaped = schema_json.replace('\\', "\\\\").replace('`', "\\`");
1167 script.push_str(&format!(
1168 concat!(
1169 " try {{\n",
1170 " let body = res.json();\n",
1171 " let ok = check(res, {{ '{check}': (r) => ( {validation} ) }});\n",
1172 " if (!ok) {{\n",
1173 " let __violations = [];\n",
1174 " try {{\n",
1175 " let __schema = JSON.parse(`{schema}`);\n",
1176 " function __collectErrors(schema, data, path) {{\n",
1177 " if (!schema || typeof schema !== 'object') return;\n",
1178 " let st = schema.type || (schema.schema_kind && schema.schema_kind.Type && Object.keys(schema.schema_kind.Type)[0]);\n",
1179 " if (st) {{ st = st.toLowerCase(); }}\n",
1180 " if (st === 'object') {{\n",
1181 " if (typeof data !== 'object' || data === null) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'object', actual: typeof data }}); return; }}\n",
1182 " let props = schema.properties || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.properties) || {{}};\n",
1183 " let req = schema.required || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Object && schema.schema_kind.Type.Object.required) || [];\n",
1184 " for (let f of req) {{ if (!(f in data)) {{ __violations.push({{ field_path: path + '/' + f, violation_type: 'required', expected: 'present', actual: 'missing' }}); }} }}\n",
1185 " for (let [k, v] of Object.entries(props)) {{ if (data[k] !== undefined) {{ let ps = v.Item || v; __collectErrors(ps, data[k], path + '/' + k); }} }}\n",
1186 " }} else if (st === 'array') {{\n",
1187 " if (!Array.isArray(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'array', actual: typeof data }}); return; }}\n",
1188 " let items = schema.items || (schema.schema_kind && schema.schema_kind.Type && schema.schema_kind.Type.Array && schema.schema_kind.Type.Array.items);\n",
1189 " 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",
1190 " }} else if (st === 'string') {{\n",
1191 " if (typeof data !== 'string') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'string', actual: typeof data }}); }}\n",
1192 " }} else if (st === 'integer') {{\n",
1193 " if (typeof data !== 'number' || !Number.isInteger(data)) {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'integer', actual: typeof data }}); }}\n",
1194 " }} else if (st === 'number') {{\n",
1195 " if (typeof data !== 'number') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'number', actual: typeof data }}); }}\n",
1196 " }} else if (st === 'boolean') {{\n",
1197 " if (typeof data !== 'boolean') {{ __violations.push({{ field_path: path || '/', violation_type: 'type', expected: 'boolean', actual: typeof data }}); }}\n",
1198 " }}\n",
1199 " }}\n",
1200 " __collectErrors(__schema, body, '');\n",
1201 " }} catch(_e) {{}}\n",
1202 " __captureFailure('{check}', res, 'schema validation', __violations);\n",
1203 " }}\n",
1204 " }} catch(e) {{ check(res, {{ '{check}': () => false }}); __captureFailure('{check}', res, 'JSON parse failed: ' + e.message); }}\n",
1205 ),
1206 check = check_name,
1207 validation = validation_js,
1208 schema = schema_json_escaped,
1209 ));
1210 }
1211 } else if matches!(
1212 feature,
1213 ConformanceFeature::SecurityBearer
1214 | ConformanceFeature::SecurityBasic
1215 | ConformanceFeature::SecurityApiKey
1216 ) {
1217 script.push_str(&format!(
1219 " {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 400 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 400 (auth accepted)'); }}\n",
1220 check_name, check_name
1221 ));
1222 } else {
1223 script.push_str(&format!(
1224 " {{ let ok = check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }}); if (!ok) __captureFailure('{}', res, 'status >= 200 && status < 500'); }}\n",
1225 check_name, check_name
1226 ));
1227 }
1228
1229 let has_cookie = self.config.has_cookie_header()
1231 || effective_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case("Cookie"));
1232 if has_cookie {
1233 script.push_str(" http.cookieJar().clear(BASE_URL);\n");
1234 }
1235
1236 script.push_str(" }\n");
1237
1238 if self.config.request_delay_ms > 0 {
1240 script.push_str(&format!(
1241 " sleep({:.3});\n",
1242 self.config.request_delay_ms as f64 / 1000.0
1243 ));
1244 }
1245 }
1246
1247 fn emit_request_with_body(
1249 &self,
1250 script: &mut String,
1251 method: &str,
1252 url: &str,
1253 op: &AnnotatedOperation,
1254 effective_headers: &[(String, String)],
1255 ) {
1256 if let Some(body) = &op.sample_body {
1257 let escaped_body = body.replace('\'', "\\'");
1258 let headers = if !effective_headers.is_empty() {
1259 format!(
1260 "Object.assign({{}}, JSON_HEADERS, {})",
1261 Self::format_headers(effective_headers)
1262 )
1263 } else {
1264 "JSON_HEADERS".to_string()
1265 };
1266 script.push_str(&format!(
1267 " let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
1268 method, url, escaped_body, headers
1269 ));
1270 } else if !effective_headers.is_empty() {
1271 script.push_str(&format!(
1272 " let res = http.{}(`{}`, null, {{ headers: {} }});\n",
1273 method,
1274 url,
1275 Self::format_headers(effective_headers)
1276 ));
1277 } else {
1278 script.push_str(&format!(" let res = http.{}(`{}`, null);\n", method, url));
1279 }
1280 }
1281
1282 fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
1286 let custom = &self.config.custom_headers;
1287 if custom.is_empty() {
1288 return spec_headers.to_vec();
1289 }
1290
1291 let mut result: Vec<(String, String)> = Vec::new();
1292
1293 for (name, value) in spec_headers {
1295 if let Some((_, custom_val)) =
1296 custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
1297 {
1298 result.push((name.clone(), custom_val.clone()));
1299 } else {
1300 result.push((name.clone(), value.clone()));
1301 }
1302 }
1303
1304 for (name, value) in custom {
1306 if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
1307 result.push((name.clone(), value.clone()));
1308 }
1309 }
1310
1311 result
1312 }
1313
1314 fn inject_security_headers(
1317 &self,
1318 schemes: &[SecuritySchemeInfo],
1319 headers: &mut Vec<(String, String)>,
1320 ) {
1321 let mut to_add: Vec<(String, String)> = Vec::new();
1322
1323 let has_header = |name: &str, headers: &[(String, String)]| {
1324 headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1325 || self.config.custom_headers.iter().any(|(h, _)| h.eq_ignore_ascii_case(name))
1326 };
1327
1328 let has_cookie_auth = has_header("Cookie", headers);
1330
1331 for scheme in schemes {
1332 match scheme {
1333 SecuritySchemeInfo::Bearer => {
1334 if !has_cookie_auth && !has_header("Authorization", headers) {
1335 to_add.push((
1337 "Authorization".to_string(),
1338 "Bearer mockforge-conformance-test-token".to_string(),
1339 ));
1340 }
1341 }
1342 SecuritySchemeInfo::Basic => {
1343 if !has_cookie_auth && !has_header("Authorization", headers) {
1344 let creds = self.config.basic_auth.as_deref().unwrap_or("test:test");
1345 use base64::Engine;
1346 let encoded =
1347 base64::engine::general_purpose::STANDARD.encode(creds.as_bytes());
1348 to_add.push(("Authorization".to_string(), format!("Basic {}", encoded)));
1349 }
1350 }
1351 SecuritySchemeInfo::ApiKey { location, name } => match location {
1352 ApiKeyLocation::Header => {
1353 if !has_header(name, headers) {
1354 let key = self
1355 .config
1356 .api_key
1357 .as_deref()
1358 .unwrap_or("mockforge-conformance-test-key");
1359 to_add.push((name.clone(), key.to_string()));
1360 }
1361 }
1362 ApiKeyLocation::Cookie => {
1363 if !has_header("Cookie", headers) {
1364 to_add.push((
1365 "Cookie".to_string(),
1366 format!("{}=mockforge-conformance-test-session", name),
1367 ));
1368 }
1369 }
1370 ApiKeyLocation::Query => {
1371 }
1373 },
1374 }
1375 }
1376
1377 headers.extend(to_add);
1378 }
1379
1380 fn format_headers(headers: &[(String, String)]) -> String {
1382 let entries: Vec<String> = headers
1383 .iter()
1384 .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
1385 .collect();
1386 format!("{{ {} }}", entries.join(", "))
1387 }
1388
1389 fn generate_handle_summary(&self, script: &mut String) {
1391 let report_path = match &self.config.output_dir {
1393 Some(dir) => {
1394 let abs = std::fs::canonicalize(dir)
1395 .unwrap_or_else(|_| dir.clone())
1396 .join("conformance-report.json");
1397 abs.to_string_lossy().to_string()
1398 }
1399 None => "conformance-report.json".to_string(),
1400 };
1401
1402 script.push_str("export function handleSummary(data) {\n");
1403 script.push_str(" let checks = {};\n");
1404 script.push_str(" if (data.metrics && data.metrics.checks) {\n");
1405 script.push_str(" checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1406 script.push_str(" }\n");
1407 script.push_str(" let checkResults = {};\n");
1408 script.push_str(" function walkGroups(group) {\n");
1409 script.push_str(" if (group.checks) {\n");
1410 script.push_str(" for (let checkObj of group.checks) {\n");
1411 script.push_str(" checkResults[checkObj.name] = {\n");
1412 script.push_str(" passes: checkObj.passes,\n");
1413 script.push_str(" fails: checkObj.fails,\n");
1414 script.push_str(" };\n");
1415 script.push_str(" }\n");
1416 script.push_str(" }\n");
1417 script.push_str(" if (group.groups) {\n");
1418 script.push_str(" for (let subGroup of group.groups) {\n");
1419 script.push_str(" walkGroups(subGroup);\n");
1420 script.push_str(" }\n");
1421 script.push_str(" }\n");
1422 script.push_str(" }\n");
1423 script.push_str(" if (data.root_group) {\n");
1424 script.push_str(" walkGroups(data.root_group);\n");
1425 script.push_str(" }\n");
1426 script.push_str(" return {\n");
1427 script.push_str(&format!(
1428 " '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1429 report_path
1430 ));
1431 script.push_str(" 'summary.json': JSON.stringify(data),\n");
1432 script.push_str(" stdout: textSummary(data, { indent: ' ', enableColors: true }),\n");
1433 script.push_str(" };\n");
1434 script.push_str("}\n\n");
1435 script.push_str("function textSummary(data, opts) {\n");
1436 script.push_str(" return JSON.stringify(data, null, 2);\n");
1437 script.push_str("}\n");
1438 }
1439}
1440
1441#[cfg(test)]
1442mod tests {
1443 use super::*;
1444 use openapiv3::{
1445 Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
1446 SchemaData, SchemaKind, StringType, Type,
1447 };
1448
1449 fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
1450 ApiOperation {
1451 method: method.to_string(),
1452 path: path.to_string(),
1453 operation,
1454 operation_id: None,
1455 }
1456 }
1457
1458 fn empty_spec() -> OpenAPI {
1459 OpenAPI::default()
1460 }
1461
1462 #[test]
1463 fn test_annotate_get_with_path_param() {
1464 let mut op = Operation::default();
1465 op.parameters.push(ReferenceOr::Item(Parameter::Path {
1466 parameter_data: ParameterData {
1467 name: "id".to_string(),
1468 description: None,
1469 required: true,
1470 deprecated: None,
1471 format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
1472 schema_data: SchemaData::default(),
1473 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1474 })),
1475 example: None,
1476 examples: Default::default(),
1477 explode: None,
1478 extensions: Default::default(),
1479 },
1480 style: PathStyle::Simple,
1481 }));
1482
1483 let api_op = make_op("get", "/users/{id}", op);
1484 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1485
1486 assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
1487 assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
1488 assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
1489 assert_eq!(annotated.path_params.len(), 1);
1490 assert_eq!(annotated.path_params[0].0, "id");
1491 }
1492
1493 #[test]
1494 fn test_annotate_post_with_json_body() {
1495 let mut op = Operation::default();
1496 let mut body = RequestBody {
1497 required: true,
1498 ..Default::default()
1499 };
1500 body.content
1501 .insert("application/json".to_string(), openapiv3::MediaType::default());
1502 op.request_body = Some(ReferenceOr::Item(body));
1503
1504 let api_op = make_op("post", "/items", op);
1505 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1506
1507 assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
1508 assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
1509 }
1510
1511 #[test]
1512 fn test_annotate_response_codes() {
1513 let mut op = Operation::default();
1514 op.responses
1515 .responses
1516 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
1517 op.responses
1518 .responses
1519 .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));
1520
1521 let api_op = make_op("get", "/items", op);
1522 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1523
1524 assert!(annotated.features.contains(&ConformanceFeature::Response200));
1525 assert!(annotated.features.contains(&ConformanceFeature::Response404));
1526 }
1527
1528 #[test]
1529 fn test_generate_spec_driven_script() {
1530 let config = ConformanceConfig {
1531 target_url: "http://localhost:3000".to_string(),
1532 api_key: None,
1533 basic_auth: None,
1534 skip_tls_verify: false,
1535 categories: None,
1536 base_path: None,
1537 custom_headers: vec![],
1538 output_dir: None,
1539 all_operations: false,
1540 custom_checks_file: None,
1541 request_delay_ms: 0,
1542 custom_filter: None,
1543 export_requests: false,
1544 validate_requests: false,
1545 };
1546
1547 let operations = vec![AnnotatedOperation {
1548 path: "/users/{id}".to_string(),
1549 method: "GET".to_string(),
1550 features: vec![
1551 ConformanceFeature::MethodGet,
1552 ConformanceFeature::PathParamString,
1553 ],
1554 request_body_content_type: None,
1555 sample_body: None,
1556 query_params: vec![],
1557 header_params: vec![],
1558 path_params: vec![("id".to_string(), "test-value".to_string())],
1559 response_schema: None,
1560 response_schemas: std::collections::BTreeMap::new(),
1561 request_body_schema: None,
1562 security_schemes: vec![],
1563 }];
1564
1565 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1566 let (script, _check_count) = gen.generate().unwrap();
1567
1568 assert!(script.contains("import http from 'k6/http'"));
1569 assert!(script.contains("/users/test-value"));
1570 assert!(script.contains("param:path:string"));
1571 assert!(script.contains("method:GET"));
1572 assert!(script.contains("handleSummary"));
1573 }
1574
1575 #[test]
1576 fn test_generate_with_category_filter() {
1577 let config = ConformanceConfig {
1578 target_url: "http://localhost:3000".to_string(),
1579 api_key: None,
1580 basic_auth: None,
1581 skip_tls_verify: false,
1582 categories: Some(vec!["Parameters".to_string()]),
1583 base_path: None,
1584 custom_headers: vec![],
1585 output_dir: None,
1586 all_operations: false,
1587 custom_checks_file: None,
1588 request_delay_ms: 0,
1589 custom_filter: None,
1590 export_requests: false,
1591 validate_requests: false,
1592 };
1593
1594 let operations = vec![AnnotatedOperation {
1595 path: "/users/{id}".to_string(),
1596 method: "GET".to_string(),
1597 features: vec![
1598 ConformanceFeature::MethodGet,
1599 ConformanceFeature::PathParamString,
1600 ],
1601 request_body_content_type: None,
1602 sample_body: None,
1603 query_params: vec![],
1604 header_params: vec![],
1605 path_params: vec![("id".to_string(), "1".to_string())],
1606 response_schema: None,
1607 response_schemas: std::collections::BTreeMap::new(),
1608 request_body_schema: None,
1609 security_schemes: vec![],
1610 }];
1611
1612 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1613 let (script, _check_count) = gen.generate().unwrap();
1614
1615 assert!(script.contains("group('Parameters'"));
1616 assert!(!script.contains("group('HTTP Methods'"));
1617 }
1618
1619 #[test]
1620 fn test_annotate_response_validation() {
1621 use openapiv3::ObjectType;
1622
1623 let mut op = Operation::default();
1625 let mut response = Response::default();
1626 let mut media = openapiv3::MediaType::default();
1627 let mut obj_type = ObjectType::default();
1628 obj_type.properties.insert(
1629 "name".to_string(),
1630 ReferenceOr::Item(Box::new(Schema {
1631 schema_data: SchemaData::default(),
1632 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1633 })),
1634 );
1635 obj_type.required = vec!["name".to_string()];
1636 media.schema = Some(ReferenceOr::Item(Schema {
1637 schema_data: SchemaData::default(),
1638 schema_kind: SchemaKind::Type(Type::Object(obj_type)),
1639 }));
1640 response.content.insert("application/json".to_string(), media);
1641 op.responses
1642 .responses
1643 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1644
1645 let api_op = make_op("get", "/users", op);
1646 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1647
1648 assert!(
1649 annotated.features.contains(&ConformanceFeature::ResponseValidation),
1650 "Should detect ResponseValidation when response has a JSON schema"
1651 );
1652 assert!(annotated.response_schema.is_some(), "Should extract the response schema");
1653
1654 let config = ConformanceConfig {
1656 target_url: "http://localhost:3000".to_string(),
1657 api_key: None,
1658 basic_auth: None,
1659 skip_tls_verify: false,
1660 categories: None,
1661 base_path: None,
1662 custom_headers: vec![],
1663 output_dir: None,
1664 all_operations: false,
1665 custom_checks_file: None,
1666 request_delay_ms: 0,
1667 custom_filter: None,
1668 export_requests: false,
1669 validate_requests: false,
1670 };
1671 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1672 let (script, _check_count) = gen.generate().unwrap();
1673
1674 assert!(
1675 script.contains("response:schema:validation"),
1676 "Script should contain the validation check name"
1677 );
1678 assert!(script.contains("try {"), "Script should wrap validation in try-catch");
1679 assert!(script.contains("res.json()"), "Script should parse response as JSON");
1680 }
1681
1682 #[test]
1683 fn test_annotate_global_security() {
1684 let op = Operation::default();
1686 let mut spec = OpenAPI::default();
1687 let mut global_req = openapiv3::SecurityRequirement::new();
1688 global_req.insert("bearerAuth".to_string(), vec![]);
1689 spec.security = Some(vec![global_req]);
1690 let mut components = openapiv3::Components::default();
1692 components.security_schemes.insert(
1693 "bearerAuth".to_string(),
1694 ReferenceOr::Item(SecurityScheme::HTTP {
1695 scheme: "bearer".to_string(),
1696 bearer_format: Some("JWT".to_string()),
1697 description: None,
1698 extensions: Default::default(),
1699 }),
1700 );
1701 spec.components = Some(components);
1702
1703 let api_op = make_op("get", "/protected", op);
1704 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1705
1706 assert!(
1707 annotated.features.contains(&ConformanceFeature::SecurityBearer),
1708 "Should detect SecurityBearer from global security + components"
1709 );
1710 }
1711
1712 #[test]
1713 fn test_annotate_security_scheme_resolution() {
1714 let mut op = Operation::default();
1716 let mut req = openapiv3::SecurityRequirement::new();
1718 req.insert("myAuth".to_string(), vec![]);
1719 op.security = Some(vec![req]);
1720
1721 let mut spec = OpenAPI::default();
1722 let mut components = openapiv3::Components::default();
1723 components.security_schemes.insert(
1724 "myAuth".to_string(),
1725 ReferenceOr::Item(SecurityScheme::APIKey {
1726 location: openapiv3::APIKeyLocation::Header,
1727 name: "X-API-Key".to_string(),
1728 description: None,
1729 extensions: Default::default(),
1730 }),
1731 );
1732 spec.components = Some(components);
1733
1734 let api_op = make_op("get", "/data", op);
1735 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1736
1737 assert!(
1738 annotated.features.contains(&ConformanceFeature::SecurityApiKey),
1739 "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
1740 );
1741 }
1742
1743 #[test]
1744 fn test_annotate_content_negotiation() {
1745 let mut op = Operation::default();
1746 let mut response = Response::default();
1747 response
1749 .content
1750 .insert("application/json".to_string(), openapiv3::MediaType::default());
1751 response
1752 .content
1753 .insert("application/xml".to_string(), openapiv3::MediaType::default());
1754 op.responses
1755 .responses
1756 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1757
1758 let api_op = make_op("get", "/items", op);
1759 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1760
1761 assert!(
1762 annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1763 "Should detect ContentNegotiation when response has multiple content types"
1764 );
1765 }
1766
1767 #[test]
1768 fn test_no_content_negotiation_for_single_type() {
1769 let mut op = Operation::default();
1770 let mut response = Response::default();
1771 response
1772 .content
1773 .insert("application/json".to_string(), openapiv3::MediaType::default());
1774 op.responses
1775 .responses
1776 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1777
1778 let api_op = make_op("get", "/items", op);
1779 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1780
1781 assert!(
1782 !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1783 "Should NOT detect ContentNegotiation for a single content type"
1784 );
1785 }
1786
1787 #[test]
1788 fn test_spec_driven_with_base_path() {
1789 let annotated = AnnotatedOperation {
1790 path: "/users".to_string(),
1791 method: "GET".to_string(),
1792 features: vec![ConformanceFeature::MethodGet],
1793 path_params: vec![],
1794 query_params: vec![],
1795 header_params: vec![],
1796 request_body_content_type: None,
1797 sample_body: None,
1798 response_schema: None,
1799 response_schemas: std::collections::BTreeMap::new(),
1800 request_body_schema: None,
1801 security_schemes: vec![],
1802 };
1803 let config = ConformanceConfig {
1804 target_url: "https://192.168.2.86/".to_string(),
1805 api_key: None,
1806 basic_auth: None,
1807 skip_tls_verify: true,
1808 categories: None,
1809 base_path: Some("/api".to_string()),
1810 custom_headers: vec![],
1811 output_dir: None,
1812 all_operations: false,
1813 custom_checks_file: None,
1814 request_delay_ms: 0,
1815 custom_filter: None,
1816 export_requests: false,
1817 validate_requests: false,
1818 };
1819 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1820 let (script, _check_count) = gen.generate().unwrap();
1821
1822 assert!(
1823 script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
1824 "BASE_URL should include the base_path. Got: {}",
1825 script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
1826 );
1827 }
1828
1829 #[test]
1830 fn test_spec_driven_with_custom_headers() {
1831 let annotated = AnnotatedOperation {
1832 path: "/users".to_string(),
1833 method: "GET".to_string(),
1834 features: vec![ConformanceFeature::MethodGet],
1835 path_params: vec![],
1836 query_params: vec![],
1837 header_params: vec![
1838 ("X-Avi-Tenant".to_string(), "test-value".to_string()),
1839 ("X-CSRFToken".to_string(), "test-value".to_string()),
1840 ],
1841 request_body_content_type: None,
1842 sample_body: None,
1843 response_schema: None,
1844 response_schemas: std::collections::BTreeMap::new(),
1845 request_body_schema: None,
1846 security_schemes: vec![],
1847 };
1848 let config = ConformanceConfig {
1849 target_url: "https://192.168.2.86/".to_string(),
1850 api_key: None,
1851 basic_auth: None,
1852 skip_tls_verify: true,
1853 categories: None,
1854 base_path: Some("/api".to_string()),
1855 custom_headers: vec![
1856 ("X-Avi-Tenant".to_string(), "admin".to_string()),
1857 ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
1858 ("Cookie".to_string(), "sessionid=abc123".to_string()),
1859 ],
1860 output_dir: None,
1861 all_operations: false,
1862 custom_checks_file: None,
1863 request_delay_ms: 0,
1864 custom_filter: None,
1865 export_requests: false,
1866 validate_requests: false,
1867 };
1868 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1869 let (script, _check_count) = gen.generate().unwrap();
1870
1871 assert!(
1873 script.contains("'X-Avi-Tenant': 'admin'"),
1874 "Should use custom value for X-Avi-Tenant, not test-value"
1875 );
1876 assert!(
1877 script.contains("'X-CSRFToken': 'real-csrf-token'"),
1878 "Should use custom value for X-CSRFToken, not test-value"
1879 );
1880 assert!(
1882 script.contains("'Cookie': 'sessionid=abc123'"),
1883 "Should include Cookie header from custom_headers"
1884 );
1885 assert!(
1887 !script.contains("'test-value'"),
1888 "test-value placeholders should be replaced by custom values"
1889 );
1890 }
1891
1892 #[test]
1893 fn test_effective_headers_merging() {
1894 let config = ConformanceConfig {
1895 target_url: "http://localhost".to_string(),
1896 api_key: None,
1897 basic_auth: None,
1898 skip_tls_verify: false,
1899 categories: None,
1900 base_path: None,
1901 custom_headers: vec![
1902 ("X-Auth".to_string(), "real-token".to_string()),
1903 ("Cookie".to_string(), "session=abc".to_string()),
1904 ],
1905 output_dir: None,
1906 all_operations: false,
1907 custom_checks_file: None,
1908 request_delay_ms: 0,
1909 custom_filter: None,
1910 export_requests: false,
1911 validate_requests: false,
1912 };
1913 let gen = SpecDrivenConformanceGenerator::new(config, vec![]);
1914
1915 let spec_headers = vec![
1917 ("X-Auth".to_string(), "test-value".to_string()),
1918 ("X-Other".to_string(), "keep-this".to_string()),
1919 ];
1920 let effective = gen.effective_headers(&spec_headers);
1921
1922 assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
1924 assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
1926 assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
1928 }
1929}