Skip to main content

mockforge_bench/conformance/
generator.rs

1//! k6 script generator for OpenAPI 3.0.0 conformance testing
2
3use crate::error::{BenchError, Result};
4use std::path::{Path, PathBuf};
5
6use super::custom::CustomConformanceConfig;
7
8/// Configuration for conformance test generation
9#[derive(Default, Clone)]
10pub struct ConformanceConfig {
11    /// Target base URL
12    pub target_url: String,
13    /// API key for security scheme tests
14    pub api_key: Option<String>,
15    /// Basic auth credentials (user:pass) for security scheme tests
16    pub basic_auth: Option<String>,
17    /// Skip TLS verification
18    pub skip_tls_verify: bool,
19    /// Optional category filter — None means all categories
20    pub categories: Option<Vec<String>>,
21    /// Optional base path prefix for all generated URLs (e.g., "/api")
22    pub base_path: Option<String>,
23    /// Custom headers to inject into every conformance request (e.g., auth headers).
24    /// Each entry is (header_name, header_value). When a custom header matches
25    /// a spec-derived header name, the custom value replaces the placeholder.
26    pub custom_headers: Vec<(String, String)>,
27    /// Output directory for the conformance report (absolute path).
28    /// Used to write `conformance-report.json` to a deterministic location
29    /// so the CLI can find it after k6 execution.
30    pub output_dir: Option<PathBuf>,
31    /// When true, test ALL operations for method/response/body categories
32    /// instead of just one representative per feature check name.
33    pub all_operations: bool,
34    /// Optional path to a YAML file with custom conformance checks
35    pub custom_checks_file: Option<PathBuf>,
36    /// Delay in milliseconds between consecutive conformance requests.
37    /// Useful when testing against rate-limited APIs. Default: 0 (no delay).
38    pub request_delay_ms: u64,
39    /// Optional regex to filter custom checks by name or path.
40    /// Only checks whose name or path matches the regex are included.
41    pub custom_filter: Option<String>,
42    /// When true, export all request/response pairs to a JSON file
43    /// in the output directory (`conformance-requests.json`).
44    pub export_requests: bool,
45    /// When true, validate each request against the OpenAPI spec before
46    /// sending and report violations to `conformance-request-violations.json`.
47    pub validate_requests: bool,
48}
49
50impl ConformanceConfig {
51    /// Check if a category should be included based on the filter
52    pub fn should_include_category(&self, category: &str) -> bool {
53        match &self.categories {
54            None => true,
55            Some(cats) => cats.iter().any(|c| c.eq_ignore_ascii_case(category)),
56        }
57    }
58
59    /// Returns true if custom headers are configured
60    pub fn has_custom_headers(&self) -> bool {
61        !self.custom_headers.is_empty()
62    }
63
64    /// Returns true if custom headers contain a Cookie header.
65    /// When true, k6's automatic cookie jar should be disabled to prevent
66    /// duplicate cookies on subsequent requests.
67    pub fn has_cookie_header(&self) -> bool {
68        self.custom_headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("cookie"))
69    }
70
71    /// Format custom headers as a JS object literal string
72    pub fn custom_headers_js_object(&self) -> String {
73        let entries: Vec<String> = self
74            .custom_headers
75            .iter()
76            .map(|(k, v)| format!("'{}': '{}'", k, v.replace('\'', "\\'")))
77            .collect();
78        format!("{{ {} }}", entries.join(", "))
79    }
80
81    /// Generate a k6 group block for custom checks, if configured.
82    /// Returns `Ok(None)` if no custom checks file is configured.
83    /// Respects `custom_filter` to include only matching checks.
84    ///
85    /// Round 39 (#79) — returns BOTH the init-scope code (e.g.
86    /// `const __file_0 = open('/path', 'b')` for file uploads) and
87    /// the group body. The caller splices `init_code` near the top of
88    /// the script (after `BASE_URL`, before `export default
89    /// function`) and `group_body` inside the default function. k6
90    /// requires `open()` to live at init scope.
91    pub fn generate_custom_group(
92        &self,
93    ) -> Result<Option<crate::conformance::custom::K6CustomEmit>> {
94        let path = match &self.custom_checks_file {
95            Some(p) => p,
96            None => return Ok(None),
97        };
98        let mut config = CustomConformanceConfig::from_file(path)?;
99        if config.custom_checks.is_empty() {
100            return Ok(None);
101        }
102
103        // Apply regex filter if provided
104        if let Some(ref pattern) = self.custom_filter {
105            let re = regex::Regex::new(pattern).map_err(|e| {
106                BenchError::Other(format!("Invalid --conformance-custom-filter regex: {}", e))
107            })?;
108            let total = config.custom_checks.len();
109            config.custom_checks.retain(|c| re.is_match(&c.name) || re.is_match(&c.path));
110            tracing::info!(
111                "Custom check filter: {}/{} checks matched pattern",
112                config.custom_checks.len(),
113                total
114            );
115            if config.custom_checks.is_empty() {
116                return Ok(None);
117            }
118        }
119
120        Ok(Some(config.emit_k6_with_options(
121            "BASE_URL",
122            &self.custom_headers,
123            self.export_requests,
124        )))
125    }
126
127    /// Returns the effective base URL with base_path appended.
128    /// Handles trailing/leading slash normalization to avoid double slashes.
129    /// Always trims trailing slashes from the result so that `${BASE_URL}/path`
130    /// never produces `//path`.
131    pub fn effective_base_url(&self) -> String {
132        let base = match &self.base_path {
133            None => self.target_url.trim_end_matches('/').to_string(),
134            Some(bp) if bp.is_empty() => self.target_url.trim_end_matches('/').to_string(),
135            Some(bp) => {
136                let url = self.target_url.trim_end_matches('/');
137                let path = if bp.starts_with('/') {
138                    bp.as_str()
139                } else {
140                    return format!("{}/{}", url, bp).trim_end_matches('/').to_string();
141                };
142                format!("{}{}", url, path).trim_end_matches('/').to_string()
143            }
144        };
145        base
146    }
147}
148
149/// Generates k6 scripts for OpenAPI 3.0.0 conformance testing
150pub struct ConformanceGenerator {
151    config: ConformanceConfig,
152}
153
154impl ConformanceGenerator {
155    pub fn new(config: ConformanceConfig) -> Self {
156        Self { config }
157    }
158
159    /// Generate the conformance test k6 script
160    pub fn generate(&self) -> Result<String> {
161        let mut script = String::with_capacity(16384);
162
163        // Imports
164        script.push_str("import http from 'k6/http';\n");
165        script.push_str("import { check, group } from 'k6';\n");
166        if self.config.request_delay_ms > 0 {
167            script.push_str("import { sleep } from 'k6';\n");
168        }
169        script.push('\n');
170
171        // Tell k6 that all HTTP status codes are "expected" in conformance mode.
172        // Without this, k6 counts 4xx responses (e.g. intentional 404 tests) as
173        // http_req_failed errors, producing a misleading error rate percentage.
174        script.push_str(
175            "http.setResponseCallback(http.expectedStatuses({ min: 100, max: 599 }));\n\n",
176        );
177
178        // Options: 1 VU, 1 iteration (functional test, not load test)
179        script.push_str("export const options = {\n");
180        script.push_str("  vus: 1,\n");
181        script.push_str("  iterations: 1,\n");
182        if self.config.skip_tls_verify {
183            script.push_str("  insecureSkipTLSVerify: true,\n");
184        }
185        script.push_str("  thresholds: {\n");
186        script.push_str("    checks: ['rate>0'],\n");
187        script.push_str("  },\n");
188        script.push_str("};\n\n");
189
190        // Base URL (includes base_path if configured)
191        script.push_str(&format!("const BASE_URL = '{}';\n\n", self.config.effective_base_url()));
192
193        // Delay between requests (seconds) to avoid rate limiting
194        if self.config.request_delay_ms > 0 {
195            script.push_str(&format!(
196                "const REQUEST_DELAY = {:.3};\n\n",
197                self.config.request_delay_ms as f64 / 1000.0
198            ));
199        }
200
201        // Helper: JSON headers
202        script.push_str("const JSON_HEADERS = { 'Content-Type': 'application/json' };\n\n");
203
204        // Round 39 (#79) — emit init-scope code (e.g. `open()` calls
205        // for file uploads in custom checks) here, before any
206        // function declarations. k6 requires `open()` to live at
207        // script init scope; placing it inside `export default
208        // function` is a runtime ReferenceError.
209        let custom_emit = self.config.generate_custom_group()?;
210        if let Some(emit) = &custom_emit {
211            if !emit.init_code.is_empty() {
212                script.push_str("// Round 39 (#79) — preloaded upload bytes for custom checks\n");
213                script.push_str(&emit.init_code);
214                script.push('\n');
215            }
216        }
217
218        // Failure detail collector — logs req/res info for failed checks via console.log
219        script.push_str("function __captureFailure(checkName, res, expected) {\n");
220        script.push_str("  let bodyStr = '';\n");
221        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");
222        script.push_str("  let reqHeaders = {};\n");
223        script.push_str(
224            "  if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
225        );
226        script.push_str("  let reqBody = '';\n");
227        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");
228        script.push_str("  console.log('MOCKFORGE_FAILURE:' + JSON.stringify({\n");
229        script.push_str("    check: checkName,\n");
230        script.push_str("    request: {\n");
231        script.push_str("      method: res.request ? res.request.method : 'unknown',\n");
232        script.push_str("      url: res.request ? res.request.url : res.url || 'unknown',\n");
233        script.push_str("      headers: reqHeaders,\n");
234        script.push_str("      body: reqBody,\n");
235        script.push_str("    },\n");
236        script.push_str("    response: {\n");
237        script.push_str("      status: res.status,\n");
238        script.push_str("      headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 20)) : {},\n");
239        script.push_str("      body: bodyStr,\n");
240        script.push_str("    },\n");
241        script.push_str("    expected: expected,\n");
242        script.push_str("  }));\n");
243        script.push_str("}\n\n");
244
245        // Request/response capture for --export-requests (uses console.log since
246        // k6's handleSummary runs in a separate JS context with no access to
247        // module-level variables — the CLI parses the output log after k6 exits).
248        //
249        // Round 44 (#79) — Srikanth on 0.3.188: he reported `MOCKFORGE_UPLOAD_PARTS`
250        // appearing in k6-output.log but `MOCKFORGE_EXCHANGE` for the same check
251        // missing entirely from `conformance-requests.json` / `-failure-details.json`.
252        // The most likely failure mode is an exception inside `JSON.stringify`
253        // (multipart bodies can include bytes that produce surrogate-half strings
254        // k6's stringifier chokes on; very large request URLs can also bust k6's
255        // console-line length). Wrap the entire payload build + stringify in a
256        // try/catch and ALWAYS emit a fallback `MOCKFORGE_EXCHANGE` line — even
257        // when stringify fails — so the request never silently disappears from
258        // the export. The fallback carries `check`, method, URL, status, and an
259        // `_export_error` flag so a downstream consumer can tell a degraded
260        // entry from a clean one.
261        if self.config.export_requests {
262            script.push_str("function __captureExchange(checkName, res) {\n");
263            script.push_str("  try {\n");
264            script.push_str("    let bodyStr = '';\n");
265            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");
266            script.push_str("    let reqHeaders = {};\n");
267            script.push_str(
268                "    if (res.request && res.request.headers) { reqHeaders = res.request.headers; }\n",
269            );
270            // Round 41 (#79) — Srikanth on 0.3.185: "When run without
271            // Spec the export request file has blank entry". k6's
272            // `res.request.body` is empty for multipart uploads (k6
273            // serialises the form internally and the JS-side body
274            // string is null). Fall back to a content-type-derived
275            // summary so the export at least surfaces "multipart/form-data; N parts"
276            // instead of an empty string. Real bodies still surface
277            // unchanged.
278            // Round 46 (#79) — Srikanth on 0.3.190: a 13MB multipart
279            // upload landed `[]` in conformance-requests.json even
280            // though `MOCKFORGE_EXCHANGE:` was present in the k6 log.
281            // Root cause: k6's logfmt encoder doesn't fully escape
282            // binary bytes that JSON.stringify emits as raw chars
283            // (control codepoints above 0x1F, surrogate halves, etc),
284            // so the resulting line wasn't valid JSON-in-logfmt and the
285            // parser dropped it on the floor. Fix: when Content-Type is
286            // `multipart/`, NEVER include raw body bytes in the export.
287            // Walk the part boundaries server-side (in JS) and emit a
288            // structured summary list of `{name, filename, contentType,
289            // bytes}` per part, then a one-line preamble showing the
290            // boundary + total byte count. This survives JSON-stringify
291            // + logfmt cleanly and gives the user a strictly more
292            // useful view than the raw envelope ever did.
293            script.push_str("    let reqBody = '';\n");
294            script.push_str("    {\n");
295            script.push_str(
296                "      const ct = (reqHeaders['Content-Type'] || reqHeaders['content-type'] || '').toString();\n",
297            );
298            script.push_str("      const isMultipart = ct.startsWith('multipart/');\n");
299            script.push_str(
300                "      if (isMultipart && res.request && res.request.body) {\n\
301                 \x20\x20\x20\x20\x20\x20\x20\x20try {\n\
302                 \x20\x20\x20\x20\x20\x20\x20\x20  const raw = res.request.body;\n\
303                 \x20\x20\x20\x20\x20\x20\x20\x20  let totalBytes = raw.length;\n\
304                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundaryMatch = ct.match(/boundary=([^;]+)/);\n\
305                 \x20\x20\x20\x20\x20\x20\x20\x20  const boundary = boundaryMatch ? boundaryMatch[1].replace(/^\"|\"$/g, '') : '';\n\
306                 \x20\x20\x20\x20\x20\x20\x20\x20  const parts = [];\n\
307                 \x20\x20\x20\x20\x20\x20\x20\x20  if (boundary) {\n\
308                 \x20\x20\x20\x20\x20\x20\x20\x20    const sep = '--' + boundary;\n\
309                 \x20\x20\x20\x20\x20\x20\x20\x20    let cursor = raw.indexOf(sep);\n\
310                 \x20\x20\x20\x20\x20\x20\x20\x20    while (cursor !== -1 && parts.length < 100) {\n\
311                 \x20\x20\x20\x20\x20\x20\x20\x20      const next = raw.indexOf(sep, cursor + sep.length);\n\
312                 \x20\x20\x20\x20\x20\x20\x20\x20      if (next === -1) break;\n\
313                 \x20\x20\x20\x20\x20\x20\x20\x20      const slice = raw.substring(cursor + sep.length, next);\n\
314                 \x20\x20\x20\x20\x20\x20\x20\x20      const headerEnd = slice.indexOf('\\r\\n\\r\\n');\n\
315                 \x20\x20\x20\x20\x20\x20\x20\x20      const partHeaders = headerEnd === -1 ? slice : slice.substring(0, headerEnd);\n\
316                 \x20\x20\x20\x20\x20\x20\x20\x20      const partBody = headerEnd === -1 ? '' : slice.substring(headerEnd + 4);\n\
317                 \x20\x20\x20\x20\x20\x20\x20\x20      const nameMatch = partHeaders.match(/name=\"([^\"]+)\"/);\n\
318                 \x20\x20\x20\x20\x20\x20\x20\x20      const filenameMatch = partHeaders.match(/filename=\"([^\"]+)\"/);\n\
319                 \x20\x20\x20\x20\x20\x20\x20\x20      const partCtMatch = partHeaders.match(/Content-Type:\\s*([^\\r\\n]+)/i);\n\
320                 \x20\x20\x20\x20\x20\x20\x20\x20      parts.push({\n\
321                 \x20\x20\x20\x20\x20\x20\x20\x20        name: nameMatch ? nameMatch[1] : '',\n\
322                 \x20\x20\x20\x20\x20\x20\x20\x20        filename: filenameMatch ? filenameMatch[1] : '',\n\
323                 \x20\x20\x20\x20\x20\x20\x20\x20        contentType: partCtMatch ? partCtMatch[1].trim() : '',\n\
324                 \x20\x20\x20\x20\x20\x20\x20\x20        bytes: Math.max(0, partBody.length - 2),\n\
325                 \x20\x20\x20\x20\x20\x20\x20\x20      });\n\
326                 \x20\x20\x20\x20\x20\x20\x20\x20      cursor = next;\n\
327                 \x20\x20\x20\x20\x20\x20\x20\x20    }\n\
328                 \x20\x20\x20\x20\x20\x20\x20\x20  }\n\
329                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 47 #79 — overlay accurate on-disk byte counts from\n\
330                 \x20\x20\x20\x20\x20\x20\x20\x20  // the per-check size map written at init scope; falls back\n\
331                 \x20\x20\x20\x20\x20\x20\x20\x20  // to the JS-string-derived bytes when no entry exists.\n\
332                 \x20\x20\x20\x20\x20\x20\x20\x20  // Round 48 #79 — Srikanth on 0.3.192: per-file counts were\n\
333                 \x20\x20\x20\x20\x20\x20\x20\x20  // exact but the total was still off because we kept using\n\
334                 \x20\x20\x20\x20\x20\x20\x20\x20  // raw.length (UTF-16 code units). Recompute totalBytes as\n\
335                 \x20\x20\x20\x20\x20\x20\x20\x20  // the SUM of per-part bytes once they've been overlaid; only\n\
336                 \x20\x20\x20\x20\x20\x20\x20\x20  // every part's true byte count came from disk does the sum\n\
337                 \x20\x20\x20\x20\x20\x20\x20\x20  // equal the actual upload size (the multipart envelope\n\
338                 \x20\x20\x20\x20\x20\x20\x20\x20  // overhead bytes stay reported as the raw.length delta).\n\
339                 \x20\x20\x20\x20\x20\x20\x20\x20  const __mfSizes = (globalThis.__mfUploadSizes || {})[checkName] || {};\n\
340                 \x20\x20\x20\x20\x20\x20\x20\x20  let __allKnown = parts.length > 0;\n\
341                 \x20\x20\x20\x20\x20\x20\x20\x20  parts.forEach(function (p) { if (typeof __mfSizes[p.name] === 'number') { p.bytes = __mfSizes[p.name]; } else { __allKnown = false; } });\n\
342                 \x20\x20\x20\x20\x20\x20\x20\x20  const partsTotal = parts.reduce(function (acc, p) { return acc + p.bytes; }, 0);\n\
343                 \x20\x20\x20\x20\x20\x20\x20\x20  if (__allKnown) totalBytes = partsTotal;\n\
344                 \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\
345                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart/form-data; boundary=' + boundary + '; ' + parts.length + ' part(s); total ' + totalBytes + ' bytes: ' + summary + '>';\n\
346                 \x20\x20\x20\x20\x20\x20\x20\x20} catch (e) {\n\
347                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart upload; summary failed: ' + (e && e.message ? e.message : 'unknown') + '>';\n\
348                 \x20\x20\x20\x20\x20\x20\x20\x20}\n\
349                 \x20\x20\x20\x20\x20\x20} else if (isMultipart) {\n\
350                 \x20\x20\x20\x20\x20\x20\x20\x20reqBody = '<multipart upload; body bytes not surfaced by k6 res.request.body>';\n\
351                 \x20\x20\x20\x20\x20\x20} else if (res.request && res.request.body) {\n\
352                 \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\
353                 \x20\x20\x20\x20\x20\x20}\n\
354                 \x20\x20\x20\x20}\n",
355            );
356            // Round 47 (#79) — emit a separate MOCKFORGE_NETWORK_EVENT
357            // line when the request never completed (k6 returns
358            // status=0 with an error_code/error string for connect /
359            // tls / timeout failures). The CLI executor harvests these
360            // into `conformance-network-events.json` for the k6 path,
361            // matching the native + self-test paths.
362            script.push_str(
363                "    if (res && res.status === 0) {\n\
364                 \x20\x20\x20\x20\x20\x20const ec = (res.error_code != null) ? res.error_code : 0;\n\
365                 \x20\x20\x20\x20\x20\x20const em = (res.error != null) ? String(res.error) : '';\n\
366                 \x20\x20\x20\x20\x20\x20// k6 error_code ranges: 1200s = TCP/DNS, 1300s = TLS, 1400s = timeout, 1500s = HTTP/2, others. Map coarsely.\n\
367                 \x20\x20\x20\x20\x20\x20let kind = 'other';\n\
368                 \x20\x20\x20\x20\x20\x20if (ec >= 1200 && ec < 1300) kind = 'connect';\n\
369                 \x20\x20\x20\x20\x20\x20else if (ec >= 1300 && ec < 1400) kind = 'tls';\n\
370                 \x20\x20\x20\x20\x20\x20else if (ec >= 1400 && ec < 1500) kind = 'timeout';\n\
371                 \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\
372                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('tls') !== -1) kind = 'tls';\n\
373                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('connect') !== -1 || em.toLowerCase().indexOf('refused') !== -1) kind = 'connect';\n\
374                 \x20\x20\x20\x20\x20\x20console.log('MOCKFORGE_NETWORK_EVENT:' + JSON.stringify({\n\
375                 \x20\x20\x20\x20\x20\x20  timestamp: new Date().toISOString(),\n\
376                 \x20\x20\x20\x20\x20\x20  check: checkName,\n\
377                 \x20\x20\x20\x20\x20\x20  method: res.request ? res.request.method : 'unknown',\n\
378                 \x20\x20\x20\x20\x20\x20  url: res.request ? res.request.url : res.url || 'unknown',\n\
379                 \x20\x20\x20\x20\x20\x20  kind: kind,\n\
380                 \x20\x20\x20\x20\x20\x20  error_code: ec,\n\
381                 \x20\x20\x20\x20\x20\x20  message: em,\n\
382                 \x20\x20\x20\x20\x20\x20}));\n\
383                 \x20\x20\x20\x20}\n",
384            );
385            script.push_str("    console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
386            script.push_str("      check: checkName,\n");
387            script.push_str("      request: {\n");
388            script.push_str("        method: res.request ? res.request.method : 'unknown',\n");
389            script.push_str("        url: res.request ? res.request.url : res.url || 'unknown',\n");
390            script.push_str("        headers: reqHeaders,\n");
391            script.push_str("        body: reqBody,\n");
392            script.push_str("      },\n");
393            script.push_str("      response: {\n");
394            script.push_str("        status: res.status,\n");
395            script.push_str("        headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
396            script.push_str("        body: bodyStr,\n");
397            script.push_str("      },\n");
398            script.push_str("    }));\n");
399            script.push_str("  } catch (e) {\n");
400            // Fallback path: still emit SOMETHING the parser can pick up
401            // so the request doesn't vanish from the export. Stays short
402            // on purpose — bigger payload was what tripped the primary
403            // path.
404            script.push_str("    try {\n");
405            script.push_str("      console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
406            script.push_str("        check: checkName,\n");
407            script.push_str("        request: {\n");
408            script.push_str(
409                "          method: (res && res.request) ? res.request.method : 'unknown',\n",
410            );
411            script.push_str("          url: (res && res.request) ? res.request.url : (res && res.url) || 'unknown',\n");
412            script.push_str("          headers: {},\n");
413            script.push_str("          body: '<exchange capture failed: ' + (e && e.message ? e.message : 'unknown error') + '>',\n");
414            script.push_str("        },\n");
415            script.push_str("        response: {\n");
416            script.push_str("          status: (res && res.status) || 0,\n");
417            script.push_str("          headers: {},\n");
418            script.push_str("          body: '',\n");
419            script.push_str("        },\n");
420            script.push_str("        _export_error: (e && e.message) ? e.message : String(e),\n");
421            script.push_str("      }));\n");
422            script.push_str("    } catch (e2) {\n");
423            // Last-resort: a hand-rolled JSON string so even if a
424            // second stringify fails, we still flag the failure.
425            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");
426            script.push_str("    }\n");
427            script.push_str("  }\n");
428            script.push_str("}\n\n");
429        }
430
431        // Default function
432        script.push_str("export default function () {\n");
433
434        if self.config.has_cookie_header() {
435            script.push_str(
436                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
437            );
438            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
439        }
440
441        // Helper to insert a delay between groups when --conformance-delay is set
442        let delay_between = if self.config.request_delay_ms > 0 {
443            "  sleep(REQUEST_DELAY);\n".to_string()
444        } else {
445            String::new()
446        };
447
448        // Round 39 (#79) — Srikanth on 0.3.183: "In the exported
449        // request I see it is sending request to
450        // api/conformance/params/hello and some other URLs". When the
451        // user passed `--conformance-custom` without `--spec`, the
452        // generator still emitted the 47 built-in reference checks
453        // against `/conformance/...` paths, which 404 on a real
454        // target. Skip them when custom checks are the only input —
455        // matching the native executor's `custom_only` branch.
456        let custom_only = self.config.custom_checks_file.is_some()
457            && !self.config.target_url.is_empty()
458            // Reference checks ARE the right answer when the user
459            // explicitly listed categories with --conformance-category.
460            && self.config.categories.is_none();
461        if !custom_only {
462            if self.config.should_include_category("Parameters") {
463                self.generate_parameters_group(&mut script);
464                script.push_str(&delay_between);
465            }
466            if self.config.should_include_category("Request Bodies") {
467                self.generate_request_bodies_group(&mut script);
468                script.push_str(&delay_between);
469            }
470            if self.config.should_include_category("Schema Types") {
471                self.generate_schema_types_group(&mut script);
472                script.push_str(&delay_between);
473            }
474            if self.config.should_include_category("Composition") {
475                self.generate_composition_group(&mut script);
476                script.push_str(&delay_between);
477            }
478            if self.config.should_include_category("String Formats") {
479                self.generate_string_formats_group(&mut script);
480                script.push_str(&delay_between);
481            }
482            if self.config.should_include_category("Constraints") {
483                self.generate_constraints_group(&mut script);
484                script.push_str(&delay_between);
485            }
486            if self.config.should_include_category("Response Codes") {
487                self.generate_response_codes_group(&mut script);
488                script.push_str(&delay_between);
489            }
490            if self.config.should_include_category("HTTP Methods") {
491                self.generate_http_methods_group(&mut script);
492                script.push_str(&delay_between);
493            }
494            if self.config.should_include_category("Content Types") {
495                self.generate_content_negotiation_group(&mut script);
496                script.push_str(&delay_between);
497            }
498            if self.config.should_include_category("Security") {
499                self.generate_security_group(&mut script);
500            }
501        }
502
503        // Custom checks from YAML file — round 39: we already called
504        // `generate_custom_group()` above to emit init-scope code, so
505        // here we just splice the group body inside the default
506        // function.
507        if let Some(emit) = custom_emit {
508            script.push_str(&emit.group_body);
509        }
510
511        script.push_str("}\n\n");
512
513        // handleSummary for conformance report output
514        self.generate_handle_summary(&mut script);
515
516        Ok(script)
517    }
518
519    /// Write the generated script to a file
520    pub fn write_script(&self, path: &Path) -> Result<()> {
521        let script = self.generate()?;
522        if let Some(parent) = path.parent() {
523            std::fs::create_dir_all(parent)?;
524        }
525        std::fs::write(path, script)
526            .map_err(|e| BenchError::Other(format!("Failed to write conformance script: {}", e)))
527    }
528
529    /// Returns a JS expression for merging custom headers with provided headers.
530    /// If no custom headers, returns the input as-is.
531    /// If custom headers exist, wraps with Object.assign using inline header object.
532    fn merge_with_custom_headers(&self, headers_expr: &str) -> String {
533        if self.config.has_custom_headers() {
534            format!(
535                "Object.assign({{}}, {}, {})",
536                headers_expr,
537                self.config.custom_headers_js_object()
538            )
539        } else {
540            headers_expr.to_string()
541        }
542    }
543
544    /// Emit a GET request with optional custom headers merged in.
545    fn emit_get(&self, script: &mut String, url: &str, extra_headers: Option<&str>) {
546        let has_custom = self.config.has_custom_headers();
547        let custom_obj = self.config.custom_headers_js_object();
548        match (extra_headers, has_custom) {
549            (None, false) => {
550                script.push_str(&format!("      let res = http.get(`{}`);\n", url));
551            }
552            (None, true) => {
553                script.push_str(&format!(
554                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
555                    url, custom_obj
556                ));
557            }
558            (Some(hdrs), false) => {
559                script.push_str(&format!(
560                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
561                    url, hdrs
562                ));
563            }
564            (Some(hdrs), true) => {
565                script.push_str(&format!(
566                    "      let res = http.get(`{}`, {{ headers: Object.assign({{}}, {}, {}) }});\n",
567                    url, hdrs, custom_obj
568                ));
569            }
570        }
571        self.maybe_clear_cookie_jar(script);
572        self.maybe_capture_exchange(script);
573    }
574
575    /// Emit a POST/PUT/PATCH request with optional custom headers merged in.
576    fn emit_post_like(
577        &self,
578        script: &mut String,
579        method: &str,
580        url: &str,
581        body: &str,
582        headers_expr: &str,
583    ) {
584        let merged = self.merge_with_custom_headers(headers_expr);
585        script.push_str(&format!(
586            "      let res = http.{}(`{}`, {}, {{ headers: {} }});\n",
587            method, url, body, merged
588        ));
589        self.maybe_clear_cookie_jar(script);
590        self.maybe_capture_exchange(script);
591    }
592
593    /// Emit a DELETE/HEAD/OPTIONS request with optional custom headers.
594    fn emit_no_body(&self, script: &mut String, method: &str, url: &str) {
595        if self.config.has_custom_headers() {
596            script.push_str(&format!(
597                "      let res = http.{}(`{}`, {{ headers: {} }});\n",
598                method,
599                url,
600                self.config.custom_headers_js_object()
601            ));
602        } else {
603            script.push_str(&format!("      let res = http.{}(`{}`);\n", method, url));
604        }
605        self.maybe_clear_cookie_jar(script);
606        self.maybe_capture_exchange(script);
607    }
608
609    /// Emit `__captureExchange` call when `--export-requests` is enabled.
610    fn maybe_capture_exchange(&self, script: &mut String) {
611        if self.config.export_requests {
612            script.push_str(
613                "      if (typeof __captureExchange === 'function') __captureExchange('', res);\n",
614            );
615        }
616    }
617
618    /// Emit cookie jar clearing after a request when custom Cookie headers are used.
619    /// Prevents k6's internal cookie jar from re-sending server Set-Cookie values
620    /// alongside the custom Cookie header on subsequent requests.
621    fn maybe_clear_cookie_jar(&self, script: &mut String) {
622        if self.config.has_cookie_header() {
623            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
624        }
625    }
626
627    fn generate_parameters_group(&self, script: &mut String) {
628        script.push_str("  group('Parameters', function () {\n");
629
630        // Path param: string
631        script.push_str("    {\n");
632        self.emit_get(script, "${BASE_URL}/conformance/params/hello", None);
633        script.push_str(
634            "      check(res, { 'param:path:string': (r) => r.status >= 200 && r.status < 500 });\n",
635        );
636        script.push_str("    }\n");
637
638        // Path param: integer
639        script.push_str("    {\n");
640        self.emit_get(script, "${BASE_URL}/conformance/params/42", None);
641        script.push_str(
642            "      check(res, { 'param:path:integer': (r) => r.status >= 200 && r.status < 500 });\n",
643        );
644        script.push_str("    }\n");
645
646        // Query param: string
647        script.push_str("    {\n");
648        self.emit_get(script, "${BASE_URL}/conformance/params/query?name=test", None);
649        script.push_str(
650            "      check(res, { 'param:query:string': (r) => r.status >= 200 && r.status < 500 });\n",
651        );
652        script.push_str("    }\n");
653
654        // Query param: integer
655        script.push_str("    {\n");
656        self.emit_get(script, "${BASE_URL}/conformance/params/query?count=10", None);
657        script.push_str(
658            "      check(res, { 'param:query:integer': (r) => r.status >= 200 && r.status < 500 });\n",
659        );
660        script.push_str("    }\n");
661
662        // Query param: array
663        script.push_str("    {\n");
664        self.emit_get(script, "${BASE_URL}/conformance/params/query?tags=a&tags=b", None);
665        script.push_str(
666            "      check(res, { 'param:query:array': (r) => r.status >= 200 && r.status < 500 });\n",
667        );
668        script.push_str("    }\n");
669
670        // Header param
671        script.push_str("    {\n");
672        self.emit_get(
673            script,
674            "${BASE_URL}/conformance/params/header",
675            Some("{ 'X-Custom-Param': 'test-value' }"),
676        );
677        script.push_str(
678            "      check(res, { 'param:header': (r) => r.status >= 200 && r.status < 500 });\n",
679        );
680        script.push_str("    }\n");
681
682        // Cookie param
683        script.push_str("    {\n");
684        script.push_str("      let jar = http.cookieJar();\n");
685        script.push_str("      jar.set(BASE_URL, 'session', 'abc123');\n");
686        self.emit_get(script, "${BASE_URL}/conformance/params/cookie", None);
687        script.push_str(
688            "      check(res, { 'param:cookie': (r) => r.status >= 200 && r.status < 500 });\n",
689        );
690        script.push_str("    }\n");
691
692        script.push_str("  });\n\n");
693    }
694
695    fn generate_request_bodies_group(&self, script: &mut String) {
696        script.push_str("  group('Request Bodies', function () {\n");
697
698        // JSON body
699        script.push_str("    {\n");
700        self.emit_post_like(
701            script,
702            "post",
703            "${BASE_URL}/conformance/body/json",
704            "JSON.stringify({ name: 'test', value: 42 })",
705            "JSON_HEADERS",
706        );
707        script.push_str(
708            "      check(res, { 'body:json': (r) => r.status >= 200 && r.status < 500 });\n",
709        );
710        script.push_str("    }\n");
711
712        // Form-urlencoded body
713        script.push_str("    {\n");
714        if self.config.has_custom_headers() {
715            script.push_str(&format!(
716                "      let res = http.post(`${{BASE_URL}}/conformance/body/form`, {{ field1: 'value1', field2: 'value2' }}, {{ headers: {} }});\n",
717                self.config.custom_headers_js_object()
718            ));
719        } else {
720            script.push_str(
721                "      let res = http.post(`${BASE_URL}/conformance/body/form`, { field1: 'value1', field2: 'value2' });\n",
722            );
723        }
724        self.maybe_clear_cookie_jar(script);
725        script.push_str(
726            "      check(res, { 'body:form-urlencoded': (r) => r.status >= 200 && r.status < 500 });\n",
727        );
728        script.push_str("    }\n");
729
730        // Multipart body
731        script.push_str("    {\n");
732        script.push_str(
733            "      let data = { field: http.file('test content', 'test.txt', 'text/plain') };\n",
734        );
735        if self.config.has_custom_headers() {
736            script.push_str(&format!(
737                "      let res = http.post(`${{BASE_URL}}/conformance/body/multipart`, data, {{ headers: {} }});\n",
738                self.config.custom_headers_js_object()
739            ));
740        } else {
741            script.push_str(
742                "      let res = http.post(`${BASE_URL}/conformance/body/multipart`, data);\n",
743            );
744        }
745        self.maybe_clear_cookie_jar(script);
746        script.push_str(
747            "      check(res, { 'body:multipart': (r) => r.status >= 200 && r.status < 500 });\n",
748        );
749        script.push_str("    }\n");
750
751        script.push_str("  });\n\n");
752    }
753
754    fn generate_schema_types_group(&self, script: &mut String) {
755        script.push_str("  group('Schema Types', function () {\n");
756
757        let types = [
758            ("string", r#"{ "value": "hello" }"#, "schema:string"),
759            ("integer", r#"{ "value": 42 }"#, "schema:integer"),
760            ("number", r#"{ "value": 3.14 }"#, "schema:number"),
761            ("boolean", r#"{ "value": true }"#, "schema:boolean"),
762            ("array", r#"{ "value": [1, 2, 3] }"#, "schema:array"),
763            ("object", r#"{ "value": { "nested": "data" } }"#, "schema:object"),
764        ];
765
766        for (type_name, body, check_name) in types {
767            script.push_str("    {\n");
768            let url = format!("${{BASE_URL}}/conformance/schema/{}", type_name);
769            let body_str = format!("'{}'", body);
770            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
771            script.push_str(&format!(
772                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
773                check_name
774            ));
775            script.push_str("    }\n");
776        }
777
778        script.push_str("  });\n\n");
779    }
780
781    fn generate_composition_group(&self, script: &mut String) {
782        script.push_str("  group('Composition', function () {\n");
783
784        let compositions = [
785            ("oneOf", r#"{ "type": "string", "value": "test" }"#, "composition:oneOf"),
786            ("anyOf", r#"{ "value": "test" }"#, "composition:anyOf"),
787            ("allOf", r#"{ "name": "test", "id": 1 }"#, "composition:allOf"),
788        ];
789
790        for (kind, body, check_name) in compositions {
791            script.push_str("    {\n");
792            let url = format!("${{BASE_URL}}/conformance/composition/{}", kind);
793            let body_str = format!("'{}'", body);
794            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
795            script.push_str(&format!(
796                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
797                check_name
798            ));
799            script.push_str("    }\n");
800        }
801
802        script.push_str("  });\n\n");
803    }
804
805    fn generate_string_formats_group(&self, script: &mut String) {
806        script.push_str("  group('String Formats', function () {\n");
807
808        let formats = [
809            ("date", r#"{ "value": "2024-01-15" }"#, "format:date"),
810            ("date-time", r#"{ "value": "2024-01-15T10:30:00Z" }"#, "format:date-time"),
811            ("email", r#"{ "value": "test@example.com" }"#, "format:email"),
812            ("uuid", r#"{ "value": "550e8400-e29b-41d4-a716-446655440000" }"#, "format:uuid"),
813            ("uri", r#"{ "value": "https://example.com/path" }"#, "format:uri"),
814            ("ipv4", r#"{ "value": "192.168.1.1" }"#, "format:ipv4"),
815            ("ipv6", r#"{ "value": "::1" }"#, "format:ipv6"),
816        ];
817
818        for (fmt, body, check_name) in formats {
819            script.push_str("    {\n");
820            let url = format!("${{BASE_URL}}/conformance/formats/{}", fmt);
821            let body_str = format!("'{}'", body);
822            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
823            script.push_str(&format!(
824                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
825                check_name
826            ));
827            script.push_str("    }\n");
828        }
829
830        script.push_str("  });\n\n");
831    }
832
833    fn generate_constraints_group(&self, script: &mut String) {
834        script.push_str("  group('Constraints', function () {\n");
835
836        let constraints = [
837            (
838                "required",
839                "JSON.stringify({ required_field: 'present' })",
840                "constraint:required",
841            ),
842            ("optional", "JSON.stringify({})", "constraint:optional"),
843            ("minmax", "JSON.stringify({ value: 50 })", "constraint:minmax"),
844            ("pattern", "JSON.stringify({ value: 'ABC-123' })", "constraint:pattern"),
845            ("enum", "JSON.stringify({ status: 'active' })", "constraint:enum"),
846        ];
847
848        for (kind, body, check_name) in constraints {
849            script.push_str("    {\n");
850            let url = format!("${{BASE_URL}}/conformance/constraints/{}", kind);
851            self.emit_post_like(script, "post", &url, body, "JSON_HEADERS");
852            script.push_str(&format!(
853                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
854                check_name
855            ));
856            script.push_str("    }\n");
857        }
858
859        script.push_str("  });\n\n");
860    }
861
862    fn generate_response_codes_group(&self, script: &mut String) {
863        script.push_str("  group('Response Codes', function () {\n");
864
865        let codes = [
866            ("200", "response:200"),
867            ("201", "response:201"),
868            ("204", "response:204"),
869            ("400", "response:400"),
870            ("404", "response:404"),
871        ];
872
873        for (code, check_name) in codes {
874            script.push_str("    {\n");
875            let url = format!("${{BASE_URL}}/conformance/responses/{}", code);
876            self.emit_get(script, &url, None);
877            script.push_str(&format!(
878                "      check(res, {{ '{}': (r) => r.status === {} }});\n",
879                check_name, code
880            ));
881            script.push_str("    }\n");
882        }
883
884        script.push_str("  });\n\n");
885    }
886
887    fn generate_http_methods_group(&self, script: &mut String) {
888        script.push_str("  group('HTTP Methods', function () {\n");
889
890        // GET
891        script.push_str("    {\n");
892        self.emit_get(script, "${BASE_URL}/conformance/methods", None);
893        script.push_str(
894            "      check(res, { 'method:GET': (r) => r.status >= 200 && r.status < 500 });\n",
895        );
896        script.push_str("    }\n");
897
898        // POST
899        script.push_str("    {\n");
900        self.emit_post_like(
901            script,
902            "post",
903            "${BASE_URL}/conformance/methods",
904            "JSON.stringify({ action: 'create' })",
905            "JSON_HEADERS",
906        );
907        script.push_str(
908            "      check(res, { 'method:POST': (r) => r.status >= 200 && r.status < 500 });\n",
909        );
910        script.push_str("    }\n");
911
912        // PUT
913        script.push_str("    {\n");
914        self.emit_post_like(
915            script,
916            "put",
917            "${BASE_URL}/conformance/methods",
918            "JSON.stringify({ action: 'update' })",
919            "JSON_HEADERS",
920        );
921        script.push_str(
922            "      check(res, { 'method:PUT': (r) => r.status >= 200 && r.status < 500 });\n",
923        );
924        script.push_str("    }\n");
925
926        // PATCH
927        script.push_str("    {\n");
928        self.emit_post_like(
929            script,
930            "patch",
931            "${BASE_URL}/conformance/methods",
932            "JSON.stringify({ action: 'patch' })",
933            "JSON_HEADERS",
934        );
935        script.push_str(
936            "      check(res, { 'method:PATCH': (r) => r.status >= 200 && r.status < 500 });\n",
937        );
938        script.push_str("    }\n");
939
940        // DELETE
941        script.push_str("    {\n");
942        self.emit_no_body(script, "del", "${BASE_URL}/conformance/methods");
943        script.push_str(
944            "      check(res, { 'method:DELETE': (r) => r.status >= 200 && r.status < 500 });\n",
945        );
946        script.push_str("    }\n");
947
948        // HEAD
949        script.push_str("    {\n");
950        self.emit_no_body(script, "head", "${BASE_URL}/conformance/methods");
951        script.push_str(
952            "      check(res, { 'method:HEAD': (r) => r.status >= 200 && r.status < 500 });\n",
953        );
954        script.push_str("    }\n");
955
956        // OPTIONS
957        script.push_str("    {\n");
958        self.emit_no_body(script, "options", "${BASE_URL}/conformance/methods");
959        script.push_str(
960            "      check(res, { 'method:OPTIONS': (r) => r.status >= 200 && r.status < 500 });\n",
961        );
962        script.push_str("    }\n");
963
964        script.push_str("  });\n\n");
965    }
966
967    fn generate_content_negotiation_group(&self, script: &mut String) {
968        script.push_str("  group('Content Types', function () {\n");
969
970        script.push_str("    {\n");
971        self.emit_get(
972            script,
973            "${BASE_URL}/conformance/content-types",
974            Some("{ 'Accept': 'application/json' }"),
975        );
976        script.push_str(
977            "      check(res, { 'content:negotiation': (r) => r.status >= 200 && r.status < 500 });\n",
978        );
979        script.push_str("    }\n");
980
981        script.push_str("  });\n\n");
982    }
983
984    fn generate_security_group(&self, script: &mut String) {
985        script.push_str("  group('Security', function () {\n");
986
987        // Bearer token
988        script.push_str("    {\n");
989        self.emit_get(
990            script,
991            "${BASE_URL}/conformance/security/bearer",
992            Some("{ 'Authorization': 'Bearer test-token-123' }"),
993        );
994        script.push_str(
995            "      check(res, { 'security:bearer': (r) => r.status >= 200 && r.status < 500 });\n",
996        );
997        script.push_str("    }\n");
998
999        // API Key
1000        let api_key = self.config.api_key.as_deref().unwrap_or("test-api-key-123");
1001        script.push_str("    {\n");
1002        let api_key_hdrs = format!("{{ 'X-API-Key': '{}' }}", api_key);
1003        self.emit_get(script, "${BASE_URL}/conformance/security/apikey", Some(&api_key_hdrs));
1004        script.push_str(
1005            "      check(res, { 'security:apikey': (r) => r.status >= 200 && r.status < 500 });\n",
1006        );
1007        script.push_str("    }\n");
1008
1009        // Basic auth
1010        let basic_creds = self.config.basic_auth.as_deref().unwrap_or("user:pass");
1011        let encoded = base64_encode(basic_creds);
1012        script.push_str("    {\n");
1013        let basic_hdrs = format!("{{ 'Authorization': 'Basic {}' }}", encoded);
1014        self.emit_get(script, "${BASE_URL}/conformance/security/basic", Some(&basic_hdrs));
1015        script.push_str(
1016            "      check(res, { 'security:basic': (r) => r.status >= 200 && r.status < 500 });\n",
1017        );
1018        script.push_str("    }\n");
1019
1020        script.push_str("  });\n\n");
1021    }
1022
1023    fn generate_handle_summary(&self, script: &mut String) {
1024        // Determine the report output path. When output_dir is set, use an absolute
1025        // path so k6 writes the file where the CLI expects to find it regardless of CWD.
1026        let report_path = match &self.config.output_dir {
1027            Some(dir) => {
1028                let abs = std::fs::canonicalize(dir)
1029                    .unwrap_or_else(|_| dir.clone())
1030                    .join("conformance-report.json");
1031                abs.to_string_lossy().to_string()
1032            }
1033            None => "conformance-report.json".to_string(),
1034        };
1035
1036        script.push_str("export function handleSummary(data) {\n");
1037        script.push_str("  // Extract check results for conformance reporting\n");
1038        script.push_str("  let checks = {};\n");
1039        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
1040        script.push_str("    // Overall check pass rate\n");
1041        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1042        script.push_str("  }\n");
1043        script.push_str("  // Collect per-check results from root_group\n");
1044        script.push_str("  let checkResults = {};\n");
1045        script.push_str("  function walkGroups(group) {\n");
1046        script.push_str("    if (group.checks) {\n");
1047        script.push_str("      for (let checkObj of group.checks) {\n");
1048        script.push_str("        checkResults[checkObj.name] = {\n");
1049        script.push_str("          passes: checkObj.passes,\n");
1050        script.push_str("          fails: checkObj.fails,\n");
1051        script.push_str("        };\n");
1052        script.push_str("      }\n");
1053        script.push_str("    }\n");
1054        script.push_str("    if (group.groups) {\n");
1055        script.push_str("      for (let subGroup of group.groups) {\n");
1056        script.push_str("        walkGroups(subGroup);\n");
1057        script.push_str("      }\n");
1058        script.push_str("    }\n");
1059        script.push_str("  }\n");
1060        script.push_str("  if (data.root_group) {\n");
1061        script.push_str("    walkGroups(data.root_group);\n");
1062        script.push_str("  }\n");
1063        script.push_str("  let result = {\n");
1064        script.push_str(&format!(
1065            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1066            report_path
1067        ));
1068        script.push_str("    'summary.json': JSON.stringify(data),\n");
1069        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
1070        script.push_str("  };\n");
1071        script.push_str("  return result;\n");
1072        script.push_str("}\n\n");
1073        script.push_str("// textSummary fallback\n");
1074        script.push_str("function textSummary(data, opts) {\n");
1075        script.push_str("  return JSON.stringify(data, null, 2);\n");
1076        script.push_str("}\n");
1077    }
1078}
1079
1080/// Simple base64 encoding for basic auth
1081fn base64_encode(input: &str) -> String {
1082    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1083    let bytes = input.as_bytes();
1084    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
1085    for chunk in bytes.chunks(3) {
1086        let b0 = chunk[0] as u32;
1087        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
1088        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
1089        let triple = (b0 << 16) | (b1 << 8) | b2;
1090        result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
1091        result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
1092        if chunk.len() > 1 {
1093            result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
1094        } else {
1095            result.push('=');
1096        }
1097        if chunk.len() > 2 {
1098            result.push(CHARS[(triple & 0x3F) as usize] as char);
1099        } else {
1100            result.push('=');
1101        }
1102    }
1103    result
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108    use super::*;
1109
1110    #[test]
1111    fn test_generate_conformance_script() {
1112        let config = ConformanceConfig {
1113            target_url: "http://localhost:8080".to_string(),
1114            api_key: None,
1115            basic_auth: None,
1116            skip_tls_verify: false,
1117            categories: None,
1118            base_path: None,
1119            custom_headers: vec![],
1120            output_dir: None,
1121            all_operations: false,
1122            custom_checks_file: None,
1123            request_delay_ms: 0,
1124            custom_filter: None,
1125            export_requests: false,
1126            validate_requests: false,
1127        };
1128        let generator = ConformanceGenerator::new(config);
1129        let script = generator.generate().unwrap();
1130
1131        assert!(script.contains("import http from 'k6/http'"));
1132        assert!(script.contains("vus: 1"));
1133        assert!(script.contains("iterations: 1"));
1134        assert!(script.contains("group('Parameters'"));
1135        assert!(script.contains("group('Request Bodies'"));
1136        assert!(script.contains("group('Schema Types'"));
1137        assert!(script.contains("group('Composition'"));
1138        assert!(script.contains("group('String Formats'"));
1139        assert!(script.contains("group('Constraints'"));
1140        assert!(script.contains("group('Response Codes'"));
1141        assert!(script.contains("group('HTTP Methods'"));
1142        assert!(script.contains("group('Content Types'"));
1143        assert!(script.contains("group('Security'"));
1144        assert!(script.contains("handleSummary"));
1145    }
1146
1147    #[test]
1148    fn test_base64_encode() {
1149        assert_eq!(base64_encode("user:pass"), "dXNlcjpwYXNz");
1150        assert_eq!(base64_encode("a"), "YQ==");
1151        assert_eq!(base64_encode("ab"), "YWI=");
1152        assert_eq!(base64_encode("abc"), "YWJj");
1153    }
1154
1155    #[test]
1156    fn test_conformance_script_with_custom_auth() {
1157        let config = ConformanceConfig {
1158            target_url: "https://api.example.com".to_string(),
1159            api_key: Some("my-api-key".to_string()),
1160            basic_auth: Some("admin:secret".to_string()),
1161            skip_tls_verify: true,
1162            categories: None,
1163            base_path: None,
1164            custom_headers: vec![],
1165            output_dir: None,
1166            all_operations: false,
1167            custom_checks_file: None,
1168            request_delay_ms: 0,
1169            custom_filter: None,
1170            export_requests: false,
1171            validate_requests: false,
1172        };
1173        let generator = ConformanceGenerator::new(config);
1174        let script = generator.generate().unwrap();
1175
1176        assert!(script.contains("insecureSkipTLSVerify: true"));
1177        assert!(script.contains("my-api-key"));
1178        assert!(script.contains(&base64_encode("admin:secret")));
1179    }
1180
1181    #[test]
1182    fn test_should_include_category_none_includes_all() {
1183        let config = ConformanceConfig {
1184            target_url: "http://localhost:8080".to_string(),
1185            api_key: None,
1186            basic_auth: None,
1187            skip_tls_verify: false,
1188            categories: None,
1189            base_path: None,
1190            custom_headers: vec![],
1191            output_dir: None,
1192            all_operations: false,
1193            custom_checks_file: None,
1194            request_delay_ms: 0,
1195            custom_filter: None,
1196            export_requests: false,
1197            validate_requests: false,
1198        };
1199        assert!(config.should_include_category("Parameters"));
1200        assert!(config.should_include_category("Security"));
1201        assert!(config.should_include_category("Anything"));
1202    }
1203
1204    #[test]
1205    fn test_should_include_category_filtered() {
1206        let config = ConformanceConfig {
1207            target_url: "http://localhost:8080".to_string(),
1208            api_key: None,
1209            basic_auth: None,
1210            skip_tls_verify: false,
1211            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
1212            base_path: None,
1213            custom_headers: vec![],
1214            output_dir: None,
1215            all_operations: false,
1216            custom_checks_file: None,
1217            request_delay_ms: 0,
1218            custom_filter: None,
1219            export_requests: false,
1220            validate_requests: false,
1221        };
1222        assert!(config.should_include_category("Parameters"));
1223        assert!(config.should_include_category("Security"));
1224        assert!(config.should_include_category("parameters")); // case-insensitive
1225        assert!(!config.should_include_category("Composition"));
1226        assert!(!config.should_include_category("Schema Types"));
1227    }
1228
1229    #[test]
1230    fn test_generate_with_category_filter() {
1231        let config = ConformanceConfig {
1232            target_url: "http://localhost:8080".to_string(),
1233            api_key: None,
1234            basic_auth: None,
1235            skip_tls_verify: false,
1236            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
1237            base_path: None,
1238            custom_headers: vec![],
1239            output_dir: None,
1240            all_operations: false,
1241            custom_checks_file: None,
1242            request_delay_ms: 0,
1243            custom_filter: None,
1244            export_requests: false,
1245            validate_requests: false,
1246        };
1247        let generator = ConformanceGenerator::new(config);
1248        let script = generator.generate().unwrap();
1249
1250        assert!(script.contains("group('Parameters'"));
1251        assert!(script.contains("group('Security'"));
1252        assert!(!script.contains("group('Request Bodies'"));
1253        assert!(!script.contains("group('Schema Types'"));
1254        assert!(!script.contains("group('Composition'"));
1255    }
1256
1257    #[test]
1258    fn test_effective_base_url_no_base_path() {
1259        let config = ConformanceConfig {
1260            target_url: "https://example.com".to_string(),
1261            api_key: None,
1262            basic_auth: None,
1263            skip_tls_verify: false,
1264            categories: None,
1265            base_path: None,
1266            custom_headers: vec![],
1267            output_dir: None,
1268            all_operations: false,
1269            custom_checks_file: None,
1270            request_delay_ms: 0,
1271            custom_filter: None,
1272            export_requests: false,
1273            validate_requests: false,
1274        };
1275        assert_eq!(config.effective_base_url(), "https://example.com");
1276    }
1277
1278    #[test]
1279    fn test_effective_base_url_with_base_path() {
1280        let config = ConformanceConfig {
1281            target_url: "https://example.com".to_string(),
1282            api_key: None,
1283            basic_auth: None,
1284            skip_tls_verify: false,
1285            categories: None,
1286            base_path: Some("/api".to_string()),
1287            custom_headers: vec![],
1288            output_dir: None,
1289            all_operations: false,
1290            custom_checks_file: None,
1291            request_delay_ms: 0,
1292            custom_filter: None,
1293            export_requests: false,
1294            validate_requests: false,
1295        };
1296        assert_eq!(config.effective_base_url(), "https://example.com/api");
1297    }
1298
1299    #[test]
1300    fn test_effective_base_url_trailing_slash_normalization() {
1301        let config = ConformanceConfig {
1302            target_url: "https://example.com/".to_string(),
1303            api_key: None,
1304            basic_auth: None,
1305            skip_tls_verify: false,
1306            categories: None,
1307            base_path: Some("/api".to_string()),
1308            custom_headers: vec![],
1309            output_dir: None,
1310            all_operations: false,
1311            custom_checks_file: None,
1312            request_delay_ms: 0,
1313            custom_filter: None,
1314            export_requests: false,
1315            validate_requests: false,
1316        };
1317        assert_eq!(config.effective_base_url(), "https://example.com/api");
1318    }
1319
1320    #[test]
1321    fn test_effective_base_url_trailing_slash_no_base_path() {
1322        // Regression: --target https://192.168.2.86/ without --base-path
1323        // must not produce double slashes when combined with /path
1324        let config = ConformanceConfig {
1325            target_url: "https://192.168.2.86/".to_string(),
1326            api_key: None,
1327            basic_auth: None,
1328            skip_tls_verify: false,
1329            categories: None,
1330            base_path: None,
1331            custom_headers: vec![],
1332            output_dir: None,
1333            all_operations: false,
1334            custom_checks_file: None,
1335            request_delay_ms: 0,
1336            custom_filter: None,
1337            export_requests: false,
1338            validate_requests: false,
1339        };
1340        assert_eq!(config.effective_base_url(), "https://192.168.2.86");
1341    }
1342
1343    #[test]
1344    fn test_generate_script_with_base_path() {
1345        let config = ConformanceConfig {
1346            target_url: "https://192.168.2.86".to_string(),
1347            api_key: None,
1348            basic_auth: None,
1349            skip_tls_verify: true,
1350            categories: None,
1351            base_path: Some("/api".to_string()),
1352            custom_headers: vec![],
1353            output_dir: None,
1354            all_operations: false,
1355            custom_checks_file: None,
1356            request_delay_ms: 0,
1357            custom_filter: None,
1358            export_requests: false,
1359            validate_requests: false,
1360        };
1361        let generator = ConformanceGenerator::new(config);
1362        let script = generator.generate().unwrap();
1363
1364        assert!(script.contains("const BASE_URL = 'https://192.168.2.86/api'"));
1365        // Verify URLs include the base path via BASE_URL
1366        assert!(script.contains("${BASE_URL}/conformance/"));
1367    }
1368
1369    #[test]
1370    fn test_generate_with_custom_headers() {
1371        let config = ConformanceConfig {
1372            target_url: "https://192.168.2.86".to_string(),
1373            api_key: None,
1374            basic_auth: None,
1375            skip_tls_verify: true,
1376            categories: Some(vec!["Parameters".to_string()]),
1377            base_path: Some("/api".to_string()),
1378            custom_headers: vec![
1379                ("X-Avi-Tenant".to_string(), "admin".to_string()),
1380                ("X-CSRFToken".to_string(), "real-token".to_string()),
1381            ],
1382            output_dir: None,
1383            all_operations: false,
1384            custom_checks_file: None,
1385            request_delay_ms: 0,
1386            custom_filter: None,
1387            export_requests: false,
1388            validate_requests: false,
1389        };
1390        let generator = ConformanceGenerator::new(config);
1391        let script = generator.generate().unwrap();
1392
1393        // Custom headers should be inlined into requests (no separate const)
1394        assert!(
1395            !script.contains("const CUSTOM_HEADERS"),
1396            "Script should NOT declare a CUSTOM_HEADERS const"
1397        );
1398        assert!(script.contains("'X-Avi-Tenant': 'admin'"));
1399        assert!(script.contains("'X-CSRFToken': 'real-token'"));
1400    }
1401
1402    #[test]
1403    fn test_custom_headers_js_object() {
1404        let config = ConformanceConfig {
1405            target_url: "http://localhost".to_string(),
1406            api_key: None,
1407            basic_auth: None,
1408            skip_tls_verify: false,
1409            categories: None,
1410            base_path: None,
1411            custom_headers: vec![
1412                ("Authorization".to_string(), "Bearer abc123".to_string()),
1413                ("X-Custom".to_string(), "value".to_string()),
1414            ],
1415            output_dir: None,
1416            all_operations: false,
1417            custom_checks_file: None,
1418            request_delay_ms: 0,
1419            custom_filter: None,
1420            export_requests: false,
1421            validate_requests: false,
1422        };
1423        let js = config.custom_headers_js_object();
1424        assert!(js.contains("'Authorization': 'Bearer abc123'"));
1425        assert!(js.contains("'X-Custom': 'value'"));
1426    }
1427}