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 { .. } => None, }
35 }
36 }
37 }
38
39 pub fn resolve_request_body<'a>(
40 body_ref: &'a ReferenceOr<RequestBody>,
41 spec: &'a OpenAPI,
42 ) -> Option<&'a RequestBody> {
43 match body_ref {
44 ReferenceOr::Item(body) => Some(body),
45 ReferenceOr::Reference { reference } => {
46 let name = reference.strip_prefix("#/components/requestBodies/")?;
47 let components = spec.components.as_ref()?;
48 match components.request_bodies.get(name)? {
49 ReferenceOr::Item(body) => Some(body),
50 ReferenceOr::Reference { .. } => None,
51 }
52 }
53 }
54 }
55
56 pub fn resolve_schema<'a>(
57 schema_ref: &'a ReferenceOr<Schema>,
58 spec: &'a OpenAPI,
59 ) -> Option<&'a Schema> {
60 resolve_schema_with_visited(schema_ref, spec, &mut HashSet::new())
61 }
62
63 fn resolve_schema_with_visited<'a>(
64 schema_ref: &'a ReferenceOr<Schema>,
65 spec: &'a OpenAPI,
66 visited: &mut HashSet<String>,
67 ) -> Option<&'a Schema> {
68 match schema_ref {
69 ReferenceOr::Item(schema) => Some(schema),
70 ReferenceOr::Reference { reference } => {
71 if !visited.insert(reference.clone()) {
72 return None; }
74 let name = reference.strip_prefix("#/components/schemas/")?;
75 let components = spec.components.as_ref()?;
76 let nested = components.schemas.get(name)?;
77 resolve_schema_with_visited(nested, spec, visited)
78 }
79 }
80 }
81
82 pub fn resolve_boxed_schema<'a>(
84 schema_ref: &'a ReferenceOr<Box<Schema>>,
85 spec: &'a OpenAPI,
86 ) -> Option<&'a Schema> {
87 match schema_ref {
88 ReferenceOr::Item(schema) => Some(schema.as_ref()),
89 ReferenceOr::Reference { reference } => {
90 let name = reference.strip_prefix("#/components/schemas/")?;
92 let components = spec.components.as_ref()?;
93 let nested = components.schemas.get(name)?;
94 resolve_schema_with_visited(nested, spec, &mut HashSet::new())
95 }
96 }
97 }
98
99 pub fn resolve_response<'a>(
100 resp_ref: &'a ReferenceOr<Response>,
101 spec: &'a OpenAPI,
102 ) -> Option<&'a Response> {
103 match resp_ref {
104 ReferenceOr::Item(resp) => Some(resp),
105 ReferenceOr::Reference { reference } => {
106 let name = reference.strip_prefix("#/components/responses/")?;
107 let components = spec.components.as_ref()?;
108 match components.responses.get(name)? {
109 ReferenceOr::Item(resp) => Some(resp),
110 ReferenceOr::Reference { .. } => None,
111 }
112 }
113 }
114 }
115}
116
117#[derive(Debug, Clone)]
119pub struct AnnotatedOperation {
120 pub path: String,
121 pub method: String,
122 pub features: Vec<ConformanceFeature>,
123 pub request_body_content_type: Option<String>,
124 pub sample_body: Option<String>,
125 pub query_params: Vec<(String, String)>,
126 pub header_params: Vec<(String, String)>,
127 pub path_params: Vec<(String, String)>,
128 pub response_schema: Option<Schema>,
130}
131
132pub struct SpecDrivenConformanceGenerator {
134 config: ConformanceConfig,
135 operations: Vec<AnnotatedOperation>,
136}
137
138impl SpecDrivenConformanceGenerator {
139 pub fn new(config: ConformanceConfig, operations: Vec<AnnotatedOperation>) -> Self {
140 Self { config, operations }
141 }
142
143 pub fn annotate_operations(
145 operations: &[ApiOperation],
146 spec: &OpenAPI,
147 ) -> Vec<AnnotatedOperation> {
148 operations.iter().map(|op| Self::annotate_operation(op, spec)).collect()
149 }
150
151 fn annotate_operation(op: &ApiOperation, spec: &OpenAPI) -> AnnotatedOperation {
153 let mut features = Vec::new();
154 let mut query_params = Vec::new();
155 let mut header_params = Vec::new();
156 let mut path_params = Vec::new();
157
158 match op.method.to_uppercase().as_str() {
160 "GET" => features.push(ConformanceFeature::MethodGet),
161 "POST" => features.push(ConformanceFeature::MethodPost),
162 "PUT" => features.push(ConformanceFeature::MethodPut),
163 "PATCH" => features.push(ConformanceFeature::MethodPatch),
164 "DELETE" => features.push(ConformanceFeature::MethodDelete),
165 "HEAD" => features.push(ConformanceFeature::MethodHead),
166 "OPTIONS" => features.push(ConformanceFeature::MethodOptions),
167 _ => {}
168 }
169
170 for param_ref in &op.operation.parameters {
172 if let Some(param) = ref_resolver::resolve_parameter(param_ref, spec) {
173 Self::annotate_parameter(
174 param,
175 spec,
176 &mut features,
177 &mut query_params,
178 &mut header_params,
179 &mut path_params,
180 );
181 }
182 }
183
184 for segment in op.path.split('/') {
186 if segment.starts_with('{') && segment.ends_with('}') {
187 let name = &segment[1..segment.len() - 1];
188 if !path_params.iter().any(|(n, _)| n == name) {
190 path_params.push((name.to_string(), "test-value".to_string()));
191 if !features.contains(&ConformanceFeature::PathParamString)
193 && !features.contains(&ConformanceFeature::PathParamInteger)
194 {
195 features.push(ConformanceFeature::PathParamString);
196 }
197 }
198 }
199 }
200
201 let mut request_body_content_type = None;
203 let mut sample_body = None;
204
205 let resolved_body = op
206 .operation
207 .request_body
208 .as_ref()
209 .and_then(|b| ref_resolver::resolve_request_body(b, spec));
210
211 if let Some(body) = resolved_body {
212 for (content_type, _media) in &body.content {
213 match content_type.as_str() {
214 "application/json" => {
215 features.push(ConformanceFeature::BodyJson);
216 request_body_content_type = Some("application/json".to_string());
217 if let Ok(template) = RequestGenerator::generate_template(op) {
219 if let Some(body_val) = &template.body {
220 sample_body = Some(body_val.to_string());
221 }
222 }
223 }
224 "application/x-www-form-urlencoded" => {
225 features.push(ConformanceFeature::BodyFormUrlencoded);
226 request_body_content_type =
227 Some("application/x-www-form-urlencoded".to_string());
228 }
229 "multipart/form-data" => {
230 features.push(ConformanceFeature::BodyMultipart);
231 request_body_content_type = Some("multipart/form-data".to_string());
232 }
233 _ => {}
234 }
235 }
236
237 if let Some(media) = body.content.get("application/json") {
239 if let Some(schema_ref) = &media.schema {
240 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
241 Self::annotate_schema(schema, spec, &mut features);
242 }
243 }
244 }
245 }
246
247 Self::annotate_responses(&op.operation, spec, &mut features);
249
250 let response_schema = Self::extract_response_schema(&op.operation, spec);
252 if response_schema.is_some() {
253 features.push(ConformanceFeature::ResponseValidation);
254 }
255
256 Self::annotate_content_negotiation(&op.operation, spec, &mut features);
258
259 Self::annotate_security(&op.operation, spec, &mut features);
261
262 features.sort_by_key(|f| f.check_name());
264 features.dedup_by_key(|f| f.check_name());
265
266 AnnotatedOperation {
267 path: op.path.clone(),
268 method: op.method.to_uppercase(),
269 features,
270 request_body_content_type,
271 sample_body,
272 query_params,
273 header_params,
274 path_params,
275 response_schema,
276 }
277 }
278
279 fn annotate_parameter(
281 param: &Parameter,
282 spec: &OpenAPI,
283 features: &mut Vec<ConformanceFeature>,
284 query_params: &mut Vec<(String, String)>,
285 header_params: &mut Vec<(String, String)>,
286 path_params: &mut Vec<(String, String)>,
287 ) {
288 let (location, data) = match param {
289 Parameter::Query { parameter_data, .. } => ("query", parameter_data),
290 Parameter::Path { parameter_data, .. } => ("path", parameter_data),
291 Parameter::Header { parameter_data, .. } => ("header", parameter_data),
292 Parameter::Cookie { .. } => {
293 features.push(ConformanceFeature::CookieParam);
294 return;
295 }
296 };
297
298 let is_integer = Self::param_schema_is_integer(data, spec);
300 let is_array = Self::param_schema_is_array(data, spec);
301
302 let sample = if is_integer {
304 "42".to_string()
305 } else if is_array {
306 "a,b".to_string()
307 } else {
308 "test-value".to_string()
309 };
310
311 match location {
312 "path" => {
313 if is_integer {
314 features.push(ConformanceFeature::PathParamInteger);
315 } else {
316 features.push(ConformanceFeature::PathParamString);
317 }
318 path_params.push((data.name.clone(), sample));
319 }
320 "query" => {
321 if is_array {
322 features.push(ConformanceFeature::QueryParamArray);
323 } else if is_integer {
324 features.push(ConformanceFeature::QueryParamInteger);
325 } else {
326 features.push(ConformanceFeature::QueryParamString);
327 }
328 query_params.push((data.name.clone(), sample));
329 }
330 "header" => {
331 features.push(ConformanceFeature::HeaderParam);
332 header_params.push((data.name.clone(), sample));
333 }
334 _ => {}
335 }
336
337 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
339 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
340 Self::annotate_schema(schema, spec, features);
341 }
342 }
343
344 if data.required {
346 features.push(ConformanceFeature::ConstraintRequired);
347 } else {
348 features.push(ConformanceFeature::ConstraintOptional);
349 }
350 }
351
352 fn param_schema_is_integer(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
353 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
354 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
355 return matches!(&schema.schema_kind, SchemaKind::Type(Type::Integer(_)));
356 }
357 }
358 false
359 }
360
361 fn param_schema_is_array(data: &openapiv3::ParameterData, spec: &OpenAPI) -> bool {
362 if let ParameterSchemaOrContent::Schema(schema_ref) = &data.format {
363 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
364 return matches!(&schema.schema_kind, SchemaKind::Type(Type::Array(_)));
365 }
366 }
367 false
368 }
369
370 fn annotate_schema(schema: &Schema, spec: &OpenAPI, features: &mut Vec<ConformanceFeature>) {
372 match &schema.schema_kind {
373 SchemaKind::Type(Type::String(s)) => {
374 features.push(ConformanceFeature::SchemaString);
375 match &s.format {
377 VariantOrUnknownOrEmpty::Item(StringFormat::Date) => {
378 features.push(ConformanceFeature::FormatDate);
379 }
380 VariantOrUnknownOrEmpty::Item(StringFormat::DateTime) => {
381 features.push(ConformanceFeature::FormatDateTime);
382 }
383 VariantOrUnknownOrEmpty::Unknown(fmt) => match fmt.as_str() {
384 "email" => features.push(ConformanceFeature::FormatEmail),
385 "uuid" => features.push(ConformanceFeature::FormatUuid),
386 "uri" | "url" => features.push(ConformanceFeature::FormatUri),
387 "ipv4" => features.push(ConformanceFeature::FormatIpv4),
388 "ipv6" => features.push(ConformanceFeature::FormatIpv6),
389 _ => {}
390 },
391 _ => {}
392 }
393 if s.pattern.is_some() {
395 features.push(ConformanceFeature::ConstraintPattern);
396 }
397 if !s.enumeration.is_empty() {
398 features.push(ConformanceFeature::ConstraintEnum);
399 }
400 if s.min_length.is_some() || s.max_length.is_some() {
401 features.push(ConformanceFeature::ConstraintMinMax);
402 }
403 }
404 SchemaKind::Type(Type::Integer(i)) => {
405 features.push(ConformanceFeature::SchemaInteger);
406 if i.minimum.is_some() || i.maximum.is_some() {
407 features.push(ConformanceFeature::ConstraintMinMax);
408 }
409 if !i.enumeration.is_empty() {
410 features.push(ConformanceFeature::ConstraintEnum);
411 }
412 }
413 SchemaKind::Type(Type::Number(n)) => {
414 features.push(ConformanceFeature::SchemaNumber);
415 if n.minimum.is_some() || n.maximum.is_some() {
416 features.push(ConformanceFeature::ConstraintMinMax);
417 }
418 }
419 SchemaKind::Type(Type::Boolean(_)) => {
420 features.push(ConformanceFeature::SchemaBoolean);
421 }
422 SchemaKind::Type(Type::Array(arr)) => {
423 features.push(ConformanceFeature::SchemaArray);
424 if let Some(item_ref) = &arr.items {
425 if let Some(item_schema) = ref_resolver::resolve_boxed_schema(item_ref, spec) {
426 Self::annotate_schema(item_schema, spec, features);
427 }
428 }
429 }
430 SchemaKind::Type(Type::Object(obj)) => {
431 features.push(ConformanceFeature::SchemaObject);
432 if !obj.required.is_empty() {
434 features.push(ConformanceFeature::ConstraintRequired);
435 }
436 for (_name, prop_ref) in &obj.properties {
438 if let Some(prop_schema) = ref_resolver::resolve_boxed_schema(prop_ref, spec) {
439 Self::annotate_schema(prop_schema, spec, features);
440 }
441 }
442 }
443 SchemaKind::OneOf { .. } => {
444 features.push(ConformanceFeature::CompositionOneOf);
445 }
446 SchemaKind::AnyOf { .. } => {
447 features.push(ConformanceFeature::CompositionAnyOf);
448 }
449 SchemaKind::AllOf { .. } => {
450 features.push(ConformanceFeature::CompositionAllOf);
451 }
452 _ => {}
453 }
454 }
455
456 fn annotate_responses(
458 operation: &Operation,
459 spec: &OpenAPI,
460 features: &mut Vec<ConformanceFeature>,
461 ) {
462 for (status_code, resp_ref) in &operation.responses.responses {
463 if ref_resolver::resolve_response(resp_ref, spec).is_some() {
465 match status_code {
466 openapiv3::StatusCode::Code(200) => {
467 features.push(ConformanceFeature::Response200)
468 }
469 openapiv3::StatusCode::Code(201) => {
470 features.push(ConformanceFeature::Response201)
471 }
472 openapiv3::StatusCode::Code(204) => {
473 features.push(ConformanceFeature::Response204)
474 }
475 openapiv3::StatusCode::Code(400) => {
476 features.push(ConformanceFeature::Response400)
477 }
478 openapiv3::StatusCode::Code(404) => {
479 features.push(ConformanceFeature::Response404)
480 }
481 _ => {}
482 }
483 }
484 }
485 }
486
487 fn extract_response_schema(operation: &Operation, spec: &OpenAPI) -> Option<Schema> {
490 for code in [200u16, 201] {
492 if let Some(resp_ref) =
493 operation.responses.responses.get(&openapiv3::StatusCode::Code(code))
494 {
495 if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
496 if let Some(media) = response.content.get("application/json") {
497 if let Some(schema_ref) = &media.schema {
498 if let Some(schema) = ref_resolver::resolve_schema(schema_ref, spec) {
499 return Some(schema.clone());
500 }
501 }
502 }
503 }
504 }
505 }
506 None
507 }
508
509 fn annotate_content_negotiation(
511 operation: &Operation,
512 spec: &OpenAPI,
513 features: &mut Vec<ConformanceFeature>,
514 ) {
515 for (_status_code, resp_ref) in &operation.responses.responses {
516 if let Some(response) = ref_resolver::resolve_response(resp_ref, spec) {
517 if response.content.len() > 1 {
518 features.push(ConformanceFeature::ContentNegotiation);
519 return; }
521 }
522 }
523 }
524
525 fn annotate_security(
529 operation: &Operation,
530 spec: &OpenAPI,
531 features: &mut Vec<ConformanceFeature>,
532 ) {
533 let security_reqs = operation.security.as_ref().or(spec.security.as_ref());
535
536 if let Some(security) = security_reqs {
537 for security_req in security {
538 for scheme_name in security_req.keys() {
539 if let Some(resolved) = Self::resolve_security_scheme(scheme_name, spec) {
541 match resolved {
542 SecurityScheme::HTTP { ref scheme, .. } => {
543 if scheme.eq_ignore_ascii_case("bearer") {
544 features.push(ConformanceFeature::SecurityBearer);
545 } else if scheme.eq_ignore_ascii_case("basic") {
546 features.push(ConformanceFeature::SecurityBasic);
547 }
548 }
549 SecurityScheme::APIKey { .. } => {
550 features.push(ConformanceFeature::SecurityApiKey);
551 }
552 _ => {}
554 }
555 } else {
556 let name_lower = scheme_name.to_lowercase();
558 if name_lower.contains("bearer") || name_lower.contains("jwt") {
559 features.push(ConformanceFeature::SecurityBearer);
560 } else if name_lower.contains("api") && name_lower.contains("key") {
561 features.push(ConformanceFeature::SecurityApiKey);
562 } else if name_lower.contains("basic") {
563 features.push(ConformanceFeature::SecurityBasic);
564 }
565 }
566 }
567 }
568 }
569 }
570
571 fn resolve_security_scheme<'a>(name: &str, spec: &'a OpenAPI) -> Option<&'a SecurityScheme> {
573 let components = spec.components.as_ref()?;
574 match components.security_schemes.get(name)? {
575 ReferenceOr::Item(scheme) => Some(scheme),
576 ReferenceOr::Reference { .. } => None,
577 }
578 }
579
580 pub fn operation_count(&self) -> usize {
582 self.operations.len()
583 }
584
585 pub fn generate(&self) -> Result<(String, usize)> {
588 let mut script = String::with_capacity(16384);
589
590 script.push_str("import http from 'k6/http';\n");
592 script.push_str("import { check, group } from 'k6';\n\n");
593
594 script.push_str("export const options = {\n");
596 script.push_str(" vus: 1,\n");
597 script.push_str(" iterations: 1,\n");
598 if self.config.skip_tls_verify {
599 script.push_str(" insecureSkipTLSVerify: true,\n");
600 }
601 if self.config.has_cookie_header() {
602 script.push_str(" noCookies: true,\n");
603 }
604 script.push_str(" thresholds: {\n");
605 script.push_str(" checks: ['rate>0'],\n");
606 script.push_str(" },\n");
607 script.push_str("};\n\n");
608
609 script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
611 script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
612
613 script.push_str("export default function () {\n");
615
616 let mut category_ops: std::collections::BTreeMap<
618 &'static str,
619 Vec<(&AnnotatedOperation, &ConformanceFeature)>,
620 > = std::collections::BTreeMap::new();
621
622 for op in &self.operations {
623 for feature in &op.features {
624 let category = feature.category();
625 if self.config.should_include_category(category) {
626 category_ops.entry(category).or_default().push((op, feature));
627 }
628 }
629 }
630
631 let mut total_checks = 0usize;
633 for (category, ops) in &category_ops {
634 script.push_str(&format!(" group('{}', function () {{\n", category));
635
636 if self.config.all_operations {
637 let mut emitted_checks: HashSet<String> = HashSet::new();
639 for (op, feature) in ops {
640 let qualified = format!("{}:{}", feature.check_name(), op.path);
641 if emitted_checks.insert(qualified.clone()) {
642 self.emit_check_named(&mut script, op, feature, &qualified);
643 total_checks += 1;
644 }
645 }
646 } else {
647 let mut emitted_checks: HashSet<&str> = HashSet::new();
649 for (op, feature) in ops {
650 if emitted_checks.insert(feature.check_name()) {
651 self.emit_check(&mut script, op, feature);
652 total_checks += 1;
653 }
654 }
655 }
656
657 script.push_str(" });\n\n");
658 }
659
660 script.push_str("}\n\n");
661
662 self.generate_handle_summary(&mut script);
664
665 Ok((script, total_checks))
666 }
667
668 fn emit_check(
670 &self,
671 script: &mut String,
672 op: &AnnotatedOperation,
673 feature: &ConformanceFeature,
674 ) {
675 self.emit_check_named(script, op, feature, feature.check_name());
676 }
677
678 fn emit_check_named(
680 &self,
681 script: &mut String,
682 op: &AnnotatedOperation,
683 feature: &ConformanceFeature,
684 check_name: &str,
685 ) {
686 script.push_str(" {\n");
687
688 let mut url_path = op.path.clone();
690 for (name, value) in &op.path_params {
691 url_path = url_path.replace(&format!("{{{}}}", name), value);
692 }
693
694 if !op.query_params.is_empty() {
696 let qs: Vec<String> =
697 op.query_params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
698 url_path = format!("{}?{}", url_path, qs.join("&"));
699 }
700
701 let full_url = format!("${{BASE_URL}}{}", url_path);
702
703 let effective_headers = self.effective_headers(&op.header_params);
706 let has_headers = !effective_headers.is_empty();
707 let headers_obj = if has_headers {
708 Self::format_headers(&effective_headers)
709 } else {
710 String::new()
711 };
712
713 match op.method.as_str() {
715 "GET" => {
716 if has_headers {
717 script.push_str(&format!(
718 " let res = http.get(`{}`, {{ headers: {} }});\n",
719 full_url, headers_obj
720 ));
721 } else {
722 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
723 }
724 }
725 "POST" => {
726 self.emit_request_with_body(script, "post", &full_url, op, &effective_headers);
727 }
728 "PUT" => {
729 self.emit_request_with_body(script, "put", &full_url, op, &effective_headers);
730 }
731 "PATCH" => {
732 self.emit_request_with_body(script, "patch", &full_url, op, &effective_headers);
733 }
734 "DELETE" => {
735 if has_headers {
736 script.push_str(&format!(
737 " let res = http.del(`{}`, null, {{ headers: {} }});\n",
738 full_url, headers_obj
739 ));
740 } else {
741 script.push_str(&format!(" let res = http.del(`{}`);\n", full_url));
742 }
743 }
744 "HEAD" => {
745 if has_headers {
746 script.push_str(&format!(
747 " let res = http.head(`{}`, {{ headers: {} }});\n",
748 full_url, headers_obj
749 ));
750 } else {
751 script.push_str(&format!(" let res = http.head(`{}`);\n", full_url));
752 }
753 }
754 "OPTIONS" => {
755 if has_headers {
756 script.push_str(&format!(
757 " let res = http.options(`{}`, null, {{ headers: {} }});\n",
758 full_url, headers_obj
759 ));
760 } else {
761 script.push_str(&format!(" let res = http.options(`{}`);\n", full_url));
762 }
763 }
764 _ => {
765 if has_headers {
766 script.push_str(&format!(
767 " let res = http.get(`{}`, {{ headers: {} }});\n",
768 full_url, headers_obj
769 ));
770 } else {
771 script.push_str(&format!(" let res = http.get(`{}`);\n", full_url));
772 }
773 }
774 }
775
776 if matches!(
778 feature,
779 ConformanceFeature::Response200
780 | ConformanceFeature::Response201
781 | ConformanceFeature::Response204
782 | ConformanceFeature::Response400
783 | ConformanceFeature::Response404
784 ) {
785 let expected_code = match feature {
786 ConformanceFeature::Response200 => 200,
787 ConformanceFeature::Response201 => 201,
788 ConformanceFeature::Response204 => 204,
789 ConformanceFeature::Response400 => 400,
790 ConformanceFeature::Response404 => 404,
791 _ => 200,
792 };
793 script.push_str(&format!(
794 " check(res, {{ '{}': (r) => r.status === {} }});\n",
795 check_name, expected_code
796 ));
797 } else if matches!(feature, ConformanceFeature::ResponseValidation) {
798 if let Some(schema) = &op.response_schema {
800 let validation_js = SchemaValidatorGenerator::generate_validation(schema);
801 script.push_str(&format!(
802 " try {{ let body = res.json(); check(res, {{ '{}': (r) => {{ {} }} }}); }} catch(e) {{ check(res, {{ '{}': () => false }}); }}\n",
803 check_name, validation_js, check_name
804 ));
805 }
806 } else {
807 script.push_str(&format!(
808 " check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
809 check_name
810 ));
811 }
812
813 script.push_str(" }\n");
814 }
815
816 fn emit_request_with_body(
818 &self,
819 script: &mut String,
820 method: &str,
821 url: &str,
822 op: &AnnotatedOperation,
823 effective_headers: &[(String, String)],
824 ) {
825 if let Some(body) = &op.sample_body {
826 let escaped_body = body.replace('\'', "\\'");
827 let headers = if !effective_headers.is_empty() {
828 format!(
829 "Object.assign({{}}, JSON_HEADERS, {})",
830 Self::format_headers(effective_headers)
831 )
832 } else {
833 "JSON_HEADERS".to_string()
834 };
835 script.push_str(&format!(
836 " let res = http.{}(`{}`, '{}', {{ headers: {} }});\n",
837 method, url, escaped_body, headers
838 ));
839 } else if !effective_headers.is_empty() {
840 script.push_str(&format!(
841 " let res = http.{}(`{}`, null, {{ headers: {} }});\n",
842 method,
843 url,
844 Self::format_headers(effective_headers)
845 ));
846 } else {
847 script.push_str(&format!(" let res = http.{}(`{}`, null);\n", method, url));
848 }
849 }
850
851 fn effective_headers(&self, spec_headers: &[(String, String)]) -> Vec<(String, String)> {
855 let custom = &self.config.custom_headers;
856 if custom.is_empty() {
857 return spec_headers.to_vec();
858 }
859
860 let mut result: Vec<(String, String)> = Vec::new();
861
862 for (name, value) in spec_headers {
864 if let Some((_, custom_val)) =
865 custom.iter().find(|(cn, _)| cn.eq_ignore_ascii_case(name))
866 {
867 result.push((name.clone(), custom_val.clone()));
868 } else {
869 result.push((name.clone(), value.clone()));
870 }
871 }
872
873 for (name, value) in custom {
875 if !spec_headers.iter().any(|(sn, _)| sn.eq_ignore_ascii_case(name)) {
876 result.push((name.clone(), value.clone()));
877 }
878 }
879
880 result
881 }
882
883 fn format_headers(headers: &[(String, String)]) -> String {
885 let entries: Vec<String> =
886 headers.iter().map(|(k, v)| format!("'{}': '{}'", k, v)).collect();
887 format!("{{ {} }}", entries.join(", "))
888 }
889
890 fn generate_handle_summary(&self, script: &mut String) {
892 let report_path = match &self.config.output_dir {
894 Some(dir) => {
895 let abs = std::fs::canonicalize(dir)
896 .unwrap_or_else(|_| dir.clone())
897 .join("conformance-report.json");
898 abs.to_string_lossy().to_string()
899 }
900 None => "conformance-report.json".to_string(),
901 };
902
903 script.push_str("export function handleSummary(data) {\n");
904 script.push_str(" let checks = {};\n");
905 script.push_str(" if (data.metrics && data.metrics.checks) {\n");
906 script.push_str(" checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
907 script.push_str(" }\n");
908 script.push_str(" let checkResults = {};\n");
909 script.push_str(" function walkGroups(group) {\n");
910 script.push_str(" if (group.checks) {\n");
911 script.push_str(" for (let checkObj of group.checks) {\n");
912 script.push_str(" checkResults[checkObj.name] = {\n");
913 script.push_str(" passes: checkObj.passes,\n");
914 script.push_str(" fails: checkObj.fails,\n");
915 script.push_str(" };\n");
916 script.push_str(" }\n");
917 script.push_str(" }\n");
918 script.push_str(" if (group.groups) {\n");
919 script.push_str(" for (let subGroup of group.groups) {\n");
920 script.push_str(" walkGroups(subGroup);\n");
921 script.push_str(" }\n");
922 script.push_str(" }\n");
923 script.push_str(" }\n");
924 script.push_str(" if (data.root_group) {\n");
925 script.push_str(" walkGroups(data.root_group);\n");
926 script.push_str(" }\n");
927 script.push_str(" return {\n");
928 script.push_str(&format!(
929 " '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
930 report_path
931 ));
932 script.push_str(" stdout: textSummary(data, { indent: ' ', enableColors: true }),\n");
933 script.push_str(" };\n");
934 script.push_str("}\n\n");
935 script.push_str("function textSummary(data, opts) {\n");
936 script.push_str(" return JSON.stringify(data, null, 2);\n");
937 script.push_str("}\n");
938 }
939}
940
941#[cfg(test)]
942mod tests {
943 use super::*;
944 use openapiv3::{
945 Operation, ParameterData, ParameterSchemaOrContent, PathStyle, Response, Schema,
946 SchemaData, SchemaKind, StringType, Type,
947 };
948
949 fn make_op(method: &str, path: &str, operation: Operation) -> ApiOperation {
950 ApiOperation {
951 method: method.to_string(),
952 path: path.to_string(),
953 operation,
954 operation_id: None,
955 }
956 }
957
958 fn empty_spec() -> OpenAPI {
959 OpenAPI::default()
960 }
961
962 #[test]
963 fn test_annotate_get_with_path_param() {
964 let mut op = Operation::default();
965 op.parameters.push(ReferenceOr::Item(Parameter::Path {
966 parameter_data: ParameterData {
967 name: "id".to_string(),
968 description: None,
969 required: true,
970 deprecated: None,
971 format: ParameterSchemaOrContent::Schema(ReferenceOr::Item(Schema {
972 schema_data: SchemaData::default(),
973 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
974 })),
975 example: None,
976 examples: Default::default(),
977 explode: None,
978 extensions: Default::default(),
979 },
980 style: PathStyle::Simple,
981 }));
982
983 let api_op = make_op("get", "/users/{id}", op);
984 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
985
986 assert!(annotated.features.contains(&ConformanceFeature::MethodGet));
987 assert!(annotated.features.contains(&ConformanceFeature::PathParamString));
988 assert!(annotated.features.contains(&ConformanceFeature::ConstraintRequired));
989 assert_eq!(annotated.path_params.len(), 1);
990 assert_eq!(annotated.path_params[0].0, "id");
991 }
992
993 #[test]
994 fn test_annotate_post_with_json_body() {
995 let mut op = Operation::default();
996 let mut body = openapiv3::RequestBody::default();
997 body.required = true;
998 body.content
999 .insert("application/json".to_string(), openapiv3::MediaType::default());
1000 op.request_body = Some(ReferenceOr::Item(body));
1001
1002 let api_op = make_op("post", "/items", op);
1003 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1004
1005 assert!(annotated.features.contains(&ConformanceFeature::MethodPost));
1006 assert!(annotated.features.contains(&ConformanceFeature::BodyJson));
1007 }
1008
1009 #[test]
1010 fn test_annotate_response_codes() {
1011 let mut op = Operation::default();
1012 op.responses
1013 .responses
1014 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(Response::default()));
1015 op.responses
1016 .responses
1017 .insert(openapiv3::StatusCode::Code(404), ReferenceOr::Item(Response::default()));
1018
1019 let api_op = make_op("get", "/items", op);
1020 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1021
1022 assert!(annotated.features.contains(&ConformanceFeature::Response200));
1023 assert!(annotated.features.contains(&ConformanceFeature::Response404));
1024 }
1025
1026 #[test]
1027 fn test_generate_spec_driven_script() {
1028 let config = ConformanceConfig {
1029 target_url: "http://localhost:3000".to_string(),
1030 api_key: None,
1031 basic_auth: None,
1032 skip_tls_verify: false,
1033 categories: None,
1034 base_path: None,
1035 custom_headers: vec![],
1036 output_dir: None,
1037 all_operations: false,
1038 };
1039
1040 let operations = vec![AnnotatedOperation {
1041 path: "/users/{id}".to_string(),
1042 method: "GET".to_string(),
1043 features: vec![
1044 ConformanceFeature::MethodGet,
1045 ConformanceFeature::PathParamString,
1046 ],
1047 request_body_content_type: None,
1048 sample_body: None,
1049 query_params: vec![],
1050 header_params: vec![],
1051 path_params: vec![("id".to_string(), "test-value".to_string())],
1052 response_schema: None,
1053 }];
1054
1055 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1056 let (script, _check_count) = gen.generate().unwrap();
1057
1058 assert!(script.contains("import http from 'k6/http'"));
1059 assert!(script.contains("/users/test-value"));
1060 assert!(script.contains("param:path:string"));
1061 assert!(script.contains("method:GET"));
1062 assert!(script.contains("handleSummary"));
1063 }
1064
1065 #[test]
1066 fn test_generate_with_category_filter() {
1067 let config = ConformanceConfig {
1068 target_url: "http://localhost:3000".to_string(),
1069 api_key: None,
1070 basic_auth: None,
1071 skip_tls_verify: false,
1072 categories: Some(vec!["Parameters".to_string()]),
1073 base_path: None,
1074 custom_headers: vec![],
1075 output_dir: None,
1076 all_operations: false,
1077 };
1078
1079 let operations = vec![AnnotatedOperation {
1080 path: "/users/{id}".to_string(),
1081 method: "GET".to_string(),
1082 features: vec![
1083 ConformanceFeature::MethodGet,
1084 ConformanceFeature::PathParamString,
1085 ],
1086 request_body_content_type: None,
1087 sample_body: None,
1088 query_params: vec![],
1089 header_params: vec![],
1090 path_params: vec![("id".to_string(), "1".to_string())],
1091 response_schema: None,
1092 }];
1093
1094 let gen = SpecDrivenConformanceGenerator::new(config, operations);
1095 let (script, _check_count) = gen.generate().unwrap();
1096
1097 assert!(script.contains("group('Parameters'"));
1098 assert!(!script.contains("group('HTTP Methods'"));
1099 }
1100
1101 #[test]
1102 fn test_annotate_response_validation() {
1103 use openapiv3::ObjectType;
1104
1105 let mut op = Operation::default();
1107 let mut response = Response::default();
1108 let mut media = openapiv3::MediaType::default();
1109 let mut obj_type = ObjectType::default();
1110 obj_type.properties.insert(
1111 "name".to_string(),
1112 ReferenceOr::Item(Box::new(Schema {
1113 schema_data: SchemaData::default(),
1114 schema_kind: SchemaKind::Type(Type::String(StringType::default())),
1115 })),
1116 );
1117 obj_type.required = vec!["name".to_string()];
1118 media.schema = Some(ReferenceOr::Item(Schema {
1119 schema_data: SchemaData::default(),
1120 schema_kind: SchemaKind::Type(Type::Object(obj_type)),
1121 }));
1122 response.content.insert("application/json".to_string(), media);
1123 op.responses
1124 .responses
1125 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1126
1127 let api_op = make_op("get", "/users", op);
1128 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1129
1130 assert!(
1131 annotated.features.contains(&ConformanceFeature::ResponseValidation),
1132 "Should detect ResponseValidation when response has a JSON schema"
1133 );
1134 assert!(annotated.response_schema.is_some(), "Should extract the response schema");
1135
1136 let config = ConformanceConfig {
1138 target_url: "http://localhost:3000".to_string(),
1139 api_key: None,
1140 basic_auth: None,
1141 skip_tls_verify: false,
1142 categories: None,
1143 base_path: None,
1144 custom_headers: vec![],
1145 output_dir: None,
1146 all_operations: false,
1147 };
1148 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1149 let (script, _check_count) = gen.generate().unwrap();
1150
1151 assert!(
1152 script.contains("response:schema:validation"),
1153 "Script should contain the validation check name"
1154 );
1155 assert!(script.contains("try {"), "Script should wrap validation in try-catch");
1156 assert!(script.contains("res.json()"), "Script should parse response as JSON");
1157 }
1158
1159 #[test]
1160 fn test_annotate_global_security() {
1161 let op = Operation::default();
1163 let mut spec = OpenAPI::default();
1164 let mut global_req = openapiv3::SecurityRequirement::new();
1165 global_req.insert("bearerAuth".to_string(), vec![]);
1166 spec.security = Some(vec![global_req]);
1167 let mut components = openapiv3::Components::default();
1169 components.security_schemes.insert(
1170 "bearerAuth".to_string(),
1171 ReferenceOr::Item(SecurityScheme::HTTP {
1172 scheme: "bearer".to_string(),
1173 bearer_format: Some("JWT".to_string()),
1174 description: None,
1175 extensions: Default::default(),
1176 }),
1177 );
1178 spec.components = Some(components);
1179
1180 let api_op = make_op("get", "/protected", op);
1181 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1182
1183 assert!(
1184 annotated.features.contains(&ConformanceFeature::SecurityBearer),
1185 "Should detect SecurityBearer from global security + components"
1186 );
1187 }
1188
1189 #[test]
1190 fn test_annotate_security_scheme_resolution() {
1191 let mut op = Operation::default();
1193 let mut req = openapiv3::SecurityRequirement::new();
1195 req.insert("myAuth".to_string(), vec![]);
1196 op.security = Some(vec![req]);
1197
1198 let mut spec = OpenAPI::default();
1199 let mut components = openapiv3::Components::default();
1200 components.security_schemes.insert(
1201 "myAuth".to_string(),
1202 ReferenceOr::Item(SecurityScheme::APIKey {
1203 location: openapiv3::APIKeyLocation::Header,
1204 name: "X-API-Key".to_string(),
1205 description: None,
1206 extensions: Default::default(),
1207 }),
1208 );
1209 spec.components = Some(components);
1210
1211 let api_op = make_op("get", "/data", op);
1212 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &spec);
1213
1214 assert!(
1215 annotated.features.contains(&ConformanceFeature::SecurityApiKey),
1216 "Should detect SecurityApiKey from SecurityScheme::APIKey, not name heuristic"
1217 );
1218 }
1219
1220 #[test]
1221 fn test_annotate_content_negotiation() {
1222 let mut op = Operation::default();
1223 let mut response = Response::default();
1224 response
1226 .content
1227 .insert("application/json".to_string(), openapiv3::MediaType::default());
1228 response
1229 .content
1230 .insert("application/xml".to_string(), openapiv3::MediaType::default());
1231 op.responses
1232 .responses
1233 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1234
1235 let api_op = make_op("get", "/items", op);
1236 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1237
1238 assert!(
1239 annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1240 "Should detect ContentNegotiation when response has multiple content types"
1241 );
1242 }
1243
1244 #[test]
1245 fn test_no_content_negotiation_for_single_type() {
1246 let mut op = Operation::default();
1247 let mut response = Response::default();
1248 response
1249 .content
1250 .insert("application/json".to_string(), openapiv3::MediaType::default());
1251 op.responses
1252 .responses
1253 .insert(openapiv3::StatusCode::Code(200), ReferenceOr::Item(response));
1254
1255 let api_op = make_op("get", "/items", op);
1256 let annotated = SpecDrivenConformanceGenerator::annotate_operation(&api_op, &empty_spec());
1257
1258 assert!(
1259 !annotated.features.contains(&ConformanceFeature::ContentNegotiation),
1260 "Should NOT detect ContentNegotiation for a single content type"
1261 );
1262 }
1263
1264 #[test]
1265 fn test_spec_driven_with_base_path() {
1266 let annotated = AnnotatedOperation {
1267 path: "/users".to_string(),
1268 method: "GET".to_string(),
1269 features: vec![ConformanceFeature::MethodGet],
1270 path_params: vec![],
1271 query_params: vec![],
1272 header_params: vec![],
1273 request_body_content_type: None,
1274 sample_body: None,
1275 response_schema: None,
1276 };
1277 let config = ConformanceConfig {
1278 target_url: "https://192.168.2.86/".to_string(),
1279 api_key: None,
1280 basic_auth: None,
1281 skip_tls_verify: true,
1282 categories: None,
1283 base_path: Some("/api".to_string()),
1284 custom_headers: vec![],
1285 output_dir: None,
1286 all_operations: false,
1287 };
1288 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1289 let (script, _check_count) = gen.generate().unwrap();
1290
1291 assert!(
1292 script.contains("const BASE_URL = 'https://192.168.2.86/api'"),
1293 "BASE_URL should include the base_path. Got: {}",
1294 script.lines().find(|l| l.contains("BASE_URL")).unwrap_or("not found")
1295 );
1296 }
1297
1298 #[test]
1299 fn test_spec_driven_with_custom_headers() {
1300 let annotated = AnnotatedOperation {
1301 path: "/users".to_string(),
1302 method: "GET".to_string(),
1303 features: vec![ConformanceFeature::MethodGet],
1304 path_params: vec![],
1305 query_params: vec![],
1306 header_params: vec![
1307 ("X-Avi-Tenant".to_string(), "test-value".to_string()),
1308 ("X-CSRFToken".to_string(), "test-value".to_string()),
1309 ],
1310 request_body_content_type: None,
1311 sample_body: None,
1312 response_schema: None,
1313 };
1314 let config = ConformanceConfig {
1315 target_url: "https://192.168.2.86/".to_string(),
1316 api_key: None,
1317 basic_auth: None,
1318 skip_tls_verify: true,
1319 categories: None,
1320 base_path: Some("/api".to_string()),
1321 custom_headers: vec![
1322 ("X-Avi-Tenant".to_string(), "admin".to_string()),
1323 ("X-CSRFToken".to_string(), "real-csrf-token".to_string()),
1324 ("Cookie".to_string(), "sessionid=abc123".to_string()),
1325 ],
1326 output_dir: None,
1327 all_operations: false,
1328 };
1329 let gen = SpecDrivenConformanceGenerator::new(config, vec![annotated]);
1330 let (script, _check_count) = gen.generate().unwrap();
1331
1332 assert!(
1334 script.contains("'X-Avi-Tenant': 'admin'"),
1335 "Should use custom value for X-Avi-Tenant, not test-value"
1336 );
1337 assert!(
1338 script.contains("'X-CSRFToken': 'real-csrf-token'"),
1339 "Should use custom value for X-CSRFToken, not test-value"
1340 );
1341 assert!(
1343 script.contains("'Cookie': 'sessionid=abc123'"),
1344 "Should include Cookie header from custom_headers"
1345 );
1346 assert!(
1348 !script.contains("'test-value'"),
1349 "test-value placeholders should be replaced by custom values"
1350 );
1351 }
1352
1353 #[test]
1354 fn test_effective_headers_merging() {
1355 let config = ConformanceConfig {
1356 target_url: "http://localhost".to_string(),
1357 api_key: None,
1358 basic_auth: None,
1359 skip_tls_verify: false,
1360 categories: None,
1361 base_path: None,
1362 custom_headers: vec![
1363 ("X-Auth".to_string(), "real-token".to_string()),
1364 ("Cookie".to_string(), "session=abc".to_string()),
1365 ],
1366 output_dir: None,
1367 all_operations: false,
1368 };
1369 let gen = SpecDrivenConformanceGenerator::new(config, vec![]);
1370
1371 let spec_headers = vec![
1373 ("X-Auth".to_string(), "test-value".to_string()),
1374 ("X-Other".to_string(), "keep-this".to_string()),
1375 ];
1376 let effective = gen.effective_headers(&spec_headers);
1377
1378 assert_eq!(effective[0], ("X-Auth".to_string(), "real-token".to_string()));
1380 assert_eq!(effective[1], ("X-Other".to_string(), "keep-this".to_string()));
1382 assert_eq!(effective[2], ("Cookie".to_string(), "session=abc".to_string()));
1384 }
1385}