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  // Round 49 #79 — Srikanth on 0.3.193 asked why our proxy\n\
345                 \x20\x20\x20\x20\x20\x20\x20\x20  // counted 57998271 bytes vs mockforge's 57996316 (disk\n\
346                 \x20\x20\x20\x20\x20\x20\x20\x20  // sum). The diff is the multipart envelope (boundaries,\n\
347                 \x20\x20\x20\x20\x20\x20\x20\x20  // per-part Content-Disposition / Content-Type lines,\n\
348                 \x20\x20\x20\x20\x20\x20\x20\x20  // CRLFs, the final closing boundary). Surface both:\n\
349                 \x20\x20\x20\x20\x20\x20\x20\x20  // `total` stays the disk-sum payload (what a receiver\n\
350                 \x20\x20\x20\x20\x20\x20\x20\x20  // writes back to disk); `wire` adds the envelope so\n\
351                 \x20\x20\x20\x20\x20\x20\x20\x20  // packet captures / proxy byte counters match.\n\
352                 \x20\x20\x20\x20\x20\x20\x20\x20  const wireBytes = (typeof raw === 'string' && raw.length) ? raw.length : totalBytes;\n\
353                 \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\
354                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart/form-data; boundary=' + boundary + '; ' + parts.length + ' part(s); total ' + totalBytes + ' bytes (wire ' + wireBytes + ' bytes w/ envelope): ' + summary + '>';\n\
355                 \x20\x20\x20\x20\x20\x20\x20\x20} catch (e) {\n\
356                 \x20\x20\x20\x20\x20\x20\x20\x20  reqBody = '<multipart upload; summary failed: ' + (e && e.message ? e.message : 'unknown') + '>';\n\
357                 \x20\x20\x20\x20\x20\x20\x20\x20}\n\
358                 \x20\x20\x20\x20\x20\x20} else if (isMultipart) {\n\
359                 \x20\x20\x20\x20\x20\x20\x20\x20reqBody = '<multipart upload; body bytes not surfaced by k6 res.request.body>';\n\
360                 \x20\x20\x20\x20\x20\x20} else if (res.request && res.request.body) {\n\
361                 \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\
362                 \x20\x20\x20\x20\x20\x20}\n\
363                 \x20\x20\x20\x20}\n",
364            );
365            // Round 47 (#79) — emit a separate MOCKFORGE_NETWORK_EVENT
366            // line when the request never completed (k6 returns
367            // status=0 with an error_code/error string for connect /
368            // tls / timeout failures). The CLI executor harvests these
369            // into `conformance-network-events.json` for the k6 path,
370            // matching the native + self-test paths.
371            script.push_str(
372                "    if (res && res.status === 0) {\n\
373                 \x20\x20\x20\x20\x20\x20const ec = (res.error_code != null) ? res.error_code : 0;\n\
374                 \x20\x20\x20\x20\x20\x20const em = (res.error != null) ? String(res.error) : '';\n\
375                 \x20\x20\x20\x20\x20\x20// k6 error_code ranges: 1200s = TCP/DNS, 1300s = TLS, 1400s = timeout, 1500s = HTTP/2, others. Map coarsely.\n\
376                 \x20\x20\x20\x20\x20\x20let kind = 'other';\n\
377                 \x20\x20\x20\x20\x20\x20if (ec >= 1200 && ec < 1300) kind = 'connect';\n\
378                 \x20\x20\x20\x20\x20\x20else if (ec >= 1300 && ec < 1400) kind = 'tls';\n\
379                 \x20\x20\x20\x20\x20\x20else if (ec >= 1400 && ec < 1500) kind = 'timeout';\n\
380                 \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\
381                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('tls') !== -1) kind = 'tls';\n\
382                 \x20\x20\x20\x20\x20\x20else if (em.toLowerCase().indexOf('connect') !== -1 || em.toLowerCase().indexOf('refused') !== -1) kind = 'connect';\n\
383                 \x20\x20\x20\x20\x20\x20console.log('MOCKFORGE_NETWORK_EVENT:' + JSON.stringify({\n\
384                 \x20\x20\x20\x20\x20\x20  timestamp: new Date().toISOString(),\n\
385                 \x20\x20\x20\x20\x20\x20  check: checkName,\n\
386                 \x20\x20\x20\x20\x20\x20  method: res.request ? res.request.method : 'unknown',\n\
387                 \x20\x20\x20\x20\x20\x20  url: res.request ? res.request.url : res.url || 'unknown',\n\
388                 \x20\x20\x20\x20\x20\x20  kind: kind,\n\
389                 \x20\x20\x20\x20\x20\x20  error_code: ec,\n\
390                 \x20\x20\x20\x20\x20\x20  message: em,\n\
391                 \x20\x20\x20\x20\x20\x20}));\n\
392                 \x20\x20\x20\x20}\n",
393            );
394            script.push_str("    console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
395            script.push_str("      check: checkName,\n");
396            script.push_str("      request: {\n");
397            script.push_str("        method: res.request ? res.request.method : 'unknown',\n");
398            script.push_str("        url: res.request ? res.request.url : res.url || 'unknown',\n");
399            script.push_str("        headers: reqHeaders,\n");
400            script.push_str("        body: reqBody,\n");
401            script.push_str("      },\n");
402            script.push_str("      response: {\n");
403            script.push_str("        status: res.status,\n");
404            script.push_str("        headers: res.headers ? Object.fromEntries(Object.entries(res.headers).slice(0, 30)) : {},\n");
405            script.push_str("        body: bodyStr,\n");
406            script.push_str("      },\n");
407            script.push_str("    }));\n");
408            script.push_str("  } catch (e) {\n");
409            // Fallback path: still emit SOMETHING the parser can pick up
410            // so the request doesn't vanish from the export. Stays short
411            // on purpose — bigger payload was what tripped the primary
412            // path.
413            script.push_str("    try {\n");
414            script.push_str("      console.log('MOCKFORGE_EXCHANGE:' + JSON.stringify({\n");
415            script.push_str("        check: checkName,\n");
416            script.push_str("        request: {\n");
417            script.push_str(
418                "          method: (res && res.request) ? res.request.method : 'unknown',\n",
419            );
420            script.push_str("          url: (res && res.request) ? res.request.url : (res && res.url) || 'unknown',\n");
421            script.push_str("          headers: {},\n");
422            script.push_str("          body: '<exchange capture failed: ' + (e && e.message ? e.message : 'unknown error') + '>',\n");
423            script.push_str("        },\n");
424            script.push_str("        response: {\n");
425            script.push_str("          status: (res && res.status) || 0,\n");
426            script.push_str("          headers: {},\n");
427            script.push_str("          body: '',\n");
428            script.push_str("        },\n");
429            script.push_str("        _export_error: (e && e.message) ? e.message : String(e),\n");
430            script.push_str("      }));\n");
431            script.push_str("    } catch (e2) {\n");
432            // Last-resort: a hand-rolled JSON string so even if a
433            // second stringify fails, we still flag the failure.
434            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");
435            script.push_str("    }\n");
436            script.push_str("  }\n");
437            script.push_str("}\n\n");
438        }
439
440        // Default function
441        script.push_str("export default function () {\n");
442
443        if self.config.has_cookie_header() {
444            script.push_str(
445                "  // Clear cookie jar to prevent server Set-Cookie from duplicating custom Cookie header\n",
446            );
447            script.push_str("  http.cookieJar().clear(BASE_URL);\n\n");
448        }
449
450        // Helper to insert a delay between groups when --conformance-delay is set
451        let delay_between = if self.config.request_delay_ms > 0 {
452            "  sleep(REQUEST_DELAY);\n".to_string()
453        } else {
454            String::new()
455        };
456
457        // Round 39 (#79) — Srikanth on 0.3.183: "In the exported
458        // request I see it is sending request to
459        // api/conformance/params/hello and some other URLs". When the
460        // user passed `--conformance-custom` without `--spec`, the
461        // generator still emitted the 47 built-in reference checks
462        // against `/conformance/...` paths, which 404 on a real
463        // target. Skip them when custom checks are the only input —
464        // matching the native executor's `custom_only` branch.
465        let custom_only = self.config.custom_checks_file.is_some()
466            && !self.config.target_url.is_empty()
467            // Reference checks ARE the right answer when the user
468            // explicitly listed categories with --conformance-category.
469            && self.config.categories.is_none();
470        if !custom_only {
471            if self.config.should_include_category("Parameters") {
472                self.generate_parameters_group(&mut script);
473                script.push_str(&delay_between);
474            }
475            if self.config.should_include_category("Request Bodies") {
476                self.generate_request_bodies_group(&mut script);
477                script.push_str(&delay_between);
478            }
479            if self.config.should_include_category("Schema Types") {
480                self.generate_schema_types_group(&mut script);
481                script.push_str(&delay_between);
482            }
483            if self.config.should_include_category("Composition") {
484                self.generate_composition_group(&mut script);
485                script.push_str(&delay_between);
486            }
487            if self.config.should_include_category("String Formats") {
488                self.generate_string_formats_group(&mut script);
489                script.push_str(&delay_between);
490            }
491            if self.config.should_include_category("Constraints") {
492                self.generate_constraints_group(&mut script);
493                script.push_str(&delay_between);
494            }
495            if self.config.should_include_category("Response Codes") {
496                self.generate_response_codes_group(&mut script);
497                script.push_str(&delay_between);
498            }
499            if self.config.should_include_category("HTTP Methods") {
500                self.generate_http_methods_group(&mut script);
501                script.push_str(&delay_between);
502            }
503            if self.config.should_include_category("Content Types") {
504                self.generate_content_negotiation_group(&mut script);
505                script.push_str(&delay_between);
506            }
507            if self.config.should_include_category("Security") {
508                self.generate_security_group(&mut script);
509            }
510        }
511
512        // Custom checks from YAML file — round 39: we already called
513        // `generate_custom_group()` above to emit init-scope code, so
514        // here we just splice the group body inside the default
515        // function.
516        if let Some(emit) = custom_emit {
517            script.push_str(&emit.group_body);
518        }
519
520        script.push_str("}\n\n");
521
522        // handleSummary for conformance report output
523        self.generate_handle_summary(&mut script);
524
525        Ok(script)
526    }
527
528    /// Write the generated script to a file
529    pub fn write_script(&self, path: &Path) -> Result<()> {
530        let script = self.generate()?;
531        if let Some(parent) = path.parent() {
532            std::fs::create_dir_all(parent)?;
533        }
534        std::fs::write(path, script)
535            .map_err(|e| BenchError::Other(format!("Failed to write conformance script: {}", e)))
536    }
537
538    /// Returns a JS expression for merging custom headers with provided headers.
539    /// If no custom headers, returns the input as-is.
540    /// If custom headers exist, wraps with Object.assign using inline header object.
541    fn merge_with_custom_headers(&self, headers_expr: &str) -> String {
542        if self.config.has_custom_headers() {
543            format!(
544                "Object.assign({{}}, {}, {})",
545                headers_expr,
546                self.config.custom_headers_js_object()
547            )
548        } else {
549            headers_expr.to_string()
550        }
551    }
552
553    /// Emit a GET request with optional custom headers merged in.
554    fn emit_get(&self, script: &mut String, url: &str, extra_headers: Option<&str>) {
555        let has_custom = self.config.has_custom_headers();
556        let custom_obj = self.config.custom_headers_js_object();
557        match (extra_headers, has_custom) {
558            (None, false) => {
559                script.push_str(&format!("      let res = http.get(`{}`);\n", url));
560            }
561            (None, true) => {
562                script.push_str(&format!(
563                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
564                    url, custom_obj
565                ));
566            }
567            (Some(hdrs), false) => {
568                script.push_str(&format!(
569                    "      let res = http.get(`{}`, {{ headers: {} }});\n",
570                    url, hdrs
571                ));
572            }
573            (Some(hdrs), true) => {
574                script.push_str(&format!(
575                    "      let res = http.get(`{}`, {{ headers: Object.assign({{}}, {}, {}) }});\n",
576                    url, hdrs, custom_obj
577                ));
578            }
579        }
580        self.maybe_clear_cookie_jar(script);
581        self.maybe_capture_exchange(script);
582    }
583
584    /// Emit a POST/PUT/PATCH request with optional custom headers merged in.
585    fn emit_post_like(
586        &self,
587        script: &mut String,
588        method: &str,
589        url: &str,
590        body: &str,
591        headers_expr: &str,
592    ) {
593        let merged = self.merge_with_custom_headers(headers_expr);
594        script.push_str(&format!(
595            "      let res = http.{}(`{}`, {}, {{ headers: {} }});\n",
596            method, url, body, merged
597        ));
598        self.maybe_clear_cookie_jar(script);
599        self.maybe_capture_exchange(script);
600    }
601
602    /// Emit a DELETE/HEAD/OPTIONS request with optional custom headers.
603    fn emit_no_body(&self, script: &mut String, method: &str, url: &str) {
604        if self.config.has_custom_headers() {
605            script.push_str(&format!(
606                "      let res = http.{}(`{}`, {{ headers: {} }});\n",
607                method,
608                url,
609                self.config.custom_headers_js_object()
610            ));
611        } else {
612            script.push_str(&format!("      let res = http.{}(`{}`);\n", method, url));
613        }
614        self.maybe_clear_cookie_jar(script);
615        self.maybe_capture_exchange(script);
616    }
617
618    /// Emit `__captureExchange` call when `--export-requests` is enabled.
619    fn maybe_capture_exchange(&self, script: &mut String) {
620        if self.config.export_requests {
621            script.push_str(
622                "      if (typeof __captureExchange === 'function') __captureExchange('', res);\n",
623            );
624        }
625    }
626
627    /// Emit cookie jar clearing after a request when custom Cookie headers are used.
628    /// Prevents k6's internal cookie jar from re-sending server Set-Cookie values
629    /// alongside the custom Cookie header on subsequent requests.
630    fn maybe_clear_cookie_jar(&self, script: &mut String) {
631        if self.config.has_cookie_header() {
632            script.push_str("      http.cookieJar().clear(BASE_URL);\n");
633        }
634    }
635
636    fn generate_parameters_group(&self, script: &mut String) {
637        script.push_str("  group('Parameters', function () {\n");
638
639        // Path param: string
640        script.push_str("    {\n");
641        self.emit_get(script, "${BASE_URL}/conformance/params/hello", None);
642        script.push_str(
643            "      check(res, { 'param:path:string': (r) => r.status >= 200 && r.status < 500 });\n",
644        );
645        script.push_str("    }\n");
646
647        // Path param: integer
648        script.push_str("    {\n");
649        self.emit_get(script, "${BASE_URL}/conformance/params/42", None);
650        script.push_str(
651            "      check(res, { 'param:path:integer': (r) => r.status >= 200 && r.status < 500 });\n",
652        );
653        script.push_str("    }\n");
654
655        // Query param: string
656        script.push_str("    {\n");
657        self.emit_get(script, "${BASE_URL}/conformance/params/query?name=test", None);
658        script.push_str(
659            "      check(res, { 'param:query:string': (r) => r.status >= 200 && r.status < 500 });\n",
660        );
661        script.push_str("    }\n");
662
663        // Query param: integer
664        script.push_str("    {\n");
665        self.emit_get(script, "${BASE_URL}/conformance/params/query?count=10", None);
666        script.push_str(
667            "      check(res, { 'param:query:integer': (r) => r.status >= 200 && r.status < 500 });\n",
668        );
669        script.push_str("    }\n");
670
671        // Query param: array
672        script.push_str("    {\n");
673        self.emit_get(script, "${BASE_URL}/conformance/params/query?tags=a&tags=b", None);
674        script.push_str(
675            "      check(res, { 'param:query:array': (r) => r.status >= 200 && r.status < 500 });\n",
676        );
677        script.push_str("    }\n");
678
679        // Header param
680        script.push_str("    {\n");
681        self.emit_get(
682            script,
683            "${BASE_URL}/conformance/params/header",
684            Some("{ 'X-Custom-Param': 'test-value' }"),
685        );
686        script.push_str(
687            "      check(res, { 'param:header': (r) => r.status >= 200 && r.status < 500 });\n",
688        );
689        script.push_str("    }\n");
690
691        // Cookie param
692        script.push_str("    {\n");
693        script.push_str("      let jar = http.cookieJar();\n");
694        script.push_str("      jar.set(BASE_URL, 'session', 'abc123');\n");
695        self.emit_get(script, "${BASE_URL}/conformance/params/cookie", None);
696        script.push_str(
697            "      check(res, { 'param:cookie': (r) => r.status >= 200 && r.status < 500 });\n",
698        );
699        script.push_str("    }\n");
700
701        script.push_str("  });\n\n");
702    }
703
704    fn generate_request_bodies_group(&self, script: &mut String) {
705        script.push_str("  group('Request Bodies', function () {\n");
706
707        // JSON body
708        script.push_str("    {\n");
709        self.emit_post_like(
710            script,
711            "post",
712            "${BASE_URL}/conformance/body/json",
713            "JSON.stringify({ name: 'test', value: 42 })",
714            "JSON_HEADERS",
715        );
716        script.push_str(
717            "      check(res, { 'body:json': (r) => r.status >= 200 && r.status < 500 });\n",
718        );
719        script.push_str("    }\n");
720
721        // Form-urlencoded body
722        script.push_str("    {\n");
723        if self.config.has_custom_headers() {
724            script.push_str(&format!(
725                "      let res = http.post(`${{BASE_URL}}/conformance/body/form`, {{ field1: 'value1', field2: 'value2' }}, {{ headers: {} }});\n",
726                self.config.custom_headers_js_object()
727            ));
728        } else {
729            script.push_str(
730                "      let res = http.post(`${BASE_URL}/conformance/body/form`, { field1: 'value1', field2: 'value2' });\n",
731            );
732        }
733        self.maybe_clear_cookie_jar(script);
734        script.push_str(
735            "      check(res, { 'body:form-urlencoded': (r) => r.status >= 200 && r.status < 500 });\n",
736        );
737        script.push_str("    }\n");
738
739        // Multipart body
740        script.push_str("    {\n");
741        script.push_str(
742            "      let data = { field: http.file('test content', 'test.txt', 'text/plain') };\n",
743        );
744        if self.config.has_custom_headers() {
745            script.push_str(&format!(
746                "      let res = http.post(`${{BASE_URL}}/conformance/body/multipart`, data, {{ headers: {} }});\n",
747                self.config.custom_headers_js_object()
748            ));
749        } else {
750            script.push_str(
751                "      let res = http.post(`${BASE_URL}/conformance/body/multipart`, data);\n",
752            );
753        }
754        self.maybe_clear_cookie_jar(script);
755        script.push_str(
756            "      check(res, { 'body:multipart': (r) => r.status >= 200 && r.status < 500 });\n",
757        );
758        script.push_str("    }\n");
759
760        script.push_str("  });\n\n");
761    }
762
763    fn generate_schema_types_group(&self, script: &mut String) {
764        script.push_str("  group('Schema Types', function () {\n");
765
766        let types = [
767            ("string", r#"{ "value": "hello" }"#, "schema:string"),
768            ("integer", r#"{ "value": 42 }"#, "schema:integer"),
769            ("number", r#"{ "value": 3.14 }"#, "schema:number"),
770            ("boolean", r#"{ "value": true }"#, "schema:boolean"),
771            ("array", r#"{ "value": [1, 2, 3] }"#, "schema:array"),
772            ("object", r#"{ "value": { "nested": "data" } }"#, "schema:object"),
773        ];
774
775        for (type_name, body, check_name) in types {
776            script.push_str("    {\n");
777            let url = format!("${{BASE_URL}}/conformance/schema/{}", type_name);
778            let body_str = format!("'{}'", body);
779            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
780            script.push_str(&format!(
781                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
782                check_name
783            ));
784            script.push_str("    }\n");
785        }
786
787        script.push_str("  });\n\n");
788    }
789
790    fn generate_composition_group(&self, script: &mut String) {
791        script.push_str("  group('Composition', function () {\n");
792
793        let compositions = [
794            ("oneOf", r#"{ "type": "string", "value": "test" }"#, "composition:oneOf"),
795            ("anyOf", r#"{ "value": "test" }"#, "composition:anyOf"),
796            ("allOf", r#"{ "name": "test", "id": 1 }"#, "composition:allOf"),
797        ];
798
799        for (kind, body, check_name) in compositions {
800            script.push_str("    {\n");
801            let url = format!("${{BASE_URL}}/conformance/composition/{}", kind);
802            let body_str = format!("'{}'", body);
803            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
804            script.push_str(&format!(
805                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
806                check_name
807            ));
808            script.push_str("    }\n");
809        }
810
811        script.push_str("  });\n\n");
812    }
813
814    fn generate_string_formats_group(&self, script: &mut String) {
815        script.push_str("  group('String Formats', function () {\n");
816
817        let formats = [
818            ("date", r#"{ "value": "2024-01-15" }"#, "format:date"),
819            ("date-time", r#"{ "value": "2024-01-15T10:30:00Z" }"#, "format:date-time"),
820            ("email", r#"{ "value": "test@example.com" }"#, "format:email"),
821            ("uuid", r#"{ "value": "550e8400-e29b-41d4-a716-446655440000" }"#, "format:uuid"),
822            ("uri", r#"{ "value": "https://example.com/path" }"#, "format:uri"),
823            ("ipv4", r#"{ "value": "192.168.1.1" }"#, "format:ipv4"),
824            ("ipv6", r#"{ "value": "::1" }"#, "format:ipv6"),
825        ];
826
827        for (fmt, body, check_name) in formats {
828            script.push_str("    {\n");
829            let url = format!("${{BASE_URL}}/conformance/formats/{}", fmt);
830            let body_str = format!("'{}'", body);
831            self.emit_post_like(script, "post", &url, &body_str, "JSON_HEADERS");
832            script.push_str(&format!(
833                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
834                check_name
835            ));
836            script.push_str("    }\n");
837        }
838
839        script.push_str("  });\n\n");
840    }
841
842    fn generate_constraints_group(&self, script: &mut String) {
843        script.push_str("  group('Constraints', function () {\n");
844
845        let constraints = [
846            (
847                "required",
848                "JSON.stringify({ required_field: 'present' })",
849                "constraint:required",
850            ),
851            ("optional", "JSON.stringify({})", "constraint:optional"),
852            ("minmax", "JSON.stringify({ value: 50 })", "constraint:minmax"),
853            ("pattern", "JSON.stringify({ value: 'ABC-123' })", "constraint:pattern"),
854            ("enum", "JSON.stringify({ status: 'active' })", "constraint:enum"),
855        ];
856
857        for (kind, body, check_name) in constraints {
858            script.push_str("    {\n");
859            let url = format!("${{BASE_URL}}/conformance/constraints/{}", kind);
860            self.emit_post_like(script, "post", &url, body, "JSON_HEADERS");
861            script.push_str(&format!(
862                "      check(res, {{ '{}': (r) => r.status >= 200 && r.status < 500 }});\n",
863                check_name
864            ));
865            script.push_str("    }\n");
866        }
867
868        script.push_str("  });\n\n");
869    }
870
871    fn generate_response_codes_group(&self, script: &mut String) {
872        script.push_str("  group('Response Codes', function () {\n");
873
874        let codes = [
875            ("200", "response:200"),
876            ("201", "response:201"),
877            ("204", "response:204"),
878            ("400", "response:400"),
879            ("404", "response:404"),
880        ];
881
882        for (code, check_name) in codes {
883            script.push_str("    {\n");
884            let url = format!("${{BASE_URL}}/conformance/responses/{}", code);
885            self.emit_get(script, &url, None);
886            script.push_str(&format!(
887                "      check(res, {{ '{}': (r) => r.status === {} }});\n",
888                check_name, code
889            ));
890            script.push_str("    }\n");
891        }
892
893        script.push_str("  });\n\n");
894    }
895
896    fn generate_http_methods_group(&self, script: &mut String) {
897        script.push_str("  group('HTTP Methods', function () {\n");
898
899        // GET
900        script.push_str("    {\n");
901        self.emit_get(script, "${BASE_URL}/conformance/methods", None);
902        script.push_str(
903            "      check(res, { 'method:GET': (r) => r.status >= 200 && r.status < 500 });\n",
904        );
905        script.push_str("    }\n");
906
907        // POST
908        script.push_str("    {\n");
909        self.emit_post_like(
910            script,
911            "post",
912            "${BASE_URL}/conformance/methods",
913            "JSON.stringify({ action: 'create' })",
914            "JSON_HEADERS",
915        );
916        script.push_str(
917            "      check(res, { 'method:POST': (r) => r.status >= 200 && r.status < 500 });\n",
918        );
919        script.push_str("    }\n");
920
921        // PUT
922        script.push_str("    {\n");
923        self.emit_post_like(
924            script,
925            "put",
926            "${BASE_URL}/conformance/methods",
927            "JSON.stringify({ action: 'update' })",
928            "JSON_HEADERS",
929        );
930        script.push_str(
931            "      check(res, { 'method:PUT': (r) => r.status >= 200 && r.status < 500 });\n",
932        );
933        script.push_str("    }\n");
934
935        // PATCH
936        script.push_str("    {\n");
937        self.emit_post_like(
938            script,
939            "patch",
940            "${BASE_URL}/conformance/methods",
941            "JSON.stringify({ action: 'patch' })",
942            "JSON_HEADERS",
943        );
944        script.push_str(
945            "      check(res, { 'method:PATCH': (r) => r.status >= 200 && r.status < 500 });\n",
946        );
947        script.push_str("    }\n");
948
949        // DELETE
950        script.push_str("    {\n");
951        self.emit_no_body(script, "del", "${BASE_URL}/conformance/methods");
952        script.push_str(
953            "      check(res, { 'method:DELETE': (r) => r.status >= 200 && r.status < 500 });\n",
954        );
955        script.push_str("    }\n");
956
957        // HEAD
958        script.push_str("    {\n");
959        self.emit_no_body(script, "head", "${BASE_URL}/conformance/methods");
960        script.push_str(
961            "      check(res, { 'method:HEAD': (r) => r.status >= 200 && r.status < 500 });\n",
962        );
963        script.push_str("    }\n");
964
965        // OPTIONS
966        script.push_str("    {\n");
967        self.emit_no_body(script, "options", "${BASE_URL}/conformance/methods");
968        script.push_str(
969            "      check(res, { 'method:OPTIONS': (r) => r.status >= 200 && r.status < 500 });\n",
970        );
971        script.push_str("    }\n");
972
973        script.push_str("  });\n\n");
974    }
975
976    fn generate_content_negotiation_group(&self, script: &mut String) {
977        script.push_str("  group('Content Types', function () {\n");
978
979        script.push_str("    {\n");
980        self.emit_get(
981            script,
982            "${BASE_URL}/conformance/content-types",
983            Some("{ 'Accept': 'application/json' }"),
984        );
985        script.push_str(
986            "      check(res, { 'content:negotiation': (r) => r.status >= 200 && r.status < 500 });\n",
987        );
988        script.push_str("    }\n");
989
990        script.push_str("  });\n\n");
991    }
992
993    fn generate_security_group(&self, script: &mut String) {
994        script.push_str("  group('Security', function () {\n");
995
996        // Bearer token
997        script.push_str("    {\n");
998        self.emit_get(
999            script,
1000            "${BASE_URL}/conformance/security/bearer",
1001            Some("{ 'Authorization': 'Bearer test-token-123' }"),
1002        );
1003        script.push_str(
1004            "      check(res, { 'security:bearer': (r) => r.status >= 200 && r.status < 500 });\n",
1005        );
1006        script.push_str("    }\n");
1007
1008        // API Key
1009        let api_key = self.config.api_key.as_deref().unwrap_or("test-api-key-123");
1010        script.push_str("    {\n");
1011        let api_key_hdrs = format!("{{ 'X-API-Key': '{}' }}", api_key);
1012        self.emit_get(script, "${BASE_URL}/conformance/security/apikey", Some(&api_key_hdrs));
1013        script.push_str(
1014            "      check(res, { 'security:apikey': (r) => r.status >= 200 && r.status < 500 });\n",
1015        );
1016        script.push_str("    }\n");
1017
1018        // Basic auth
1019        let basic_creds = self.config.basic_auth.as_deref().unwrap_or("user:pass");
1020        let encoded = base64_encode(basic_creds);
1021        script.push_str("    {\n");
1022        let basic_hdrs = format!("{{ 'Authorization': 'Basic {}' }}", encoded);
1023        self.emit_get(script, "${BASE_URL}/conformance/security/basic", Some(&basic_hdrs));
1024        script.push_str(
1025            "      check(res, { 'security:basic': (r) => r.status >= 200 && r.status < 500 });\n",
1026        );
1027        script.push_str("    }\n");
1028
1029        script.push_str("  });\n\n");
1030    }
1031
1032    fn generate_handle_summary(&self, script: &mut String) {
1033        // Determine the report output path. When output_dir is set, use an absolute
1034        // path so k6 writes the file where the CLI expects to find it regardless of CWD.
1035        let report_path = match &self.config.output_dir {
1036            Some(dir) => {
1037                let abs = std::fs::canonicalize(dir)
1038                    .unwrap_or_else(|_| dir.clone())
1039                    .join("conformance-report.json");
1040                abs.to_string_lossy().to_string()
1041            }
1042            None => "conformance-report.json".to_string(),
1043        };
1044
1045        script.push_str("export function handleSummary(data) {\n");
1046        script.push_str("  // Extract check results for conformance reporting\n");
1047        script.push_str("  let checks = {};\n");
1048        script.push_str("  if (data.metrics && data.metrics.checks) {\n");
1049        script.push_str("    // Overall check pass rate\n");
1050        script.push_str("    checks.overall_pass_rate = data.metrics.checks.values.rate;\n");
1051        script.push_str("  }\n");
1052        script.push_str("  // Collect per-check results from root_group\n");
1053        script.push_str("  let checkResults = {};\n");
1054        script.push_str("  function walkGroups(group) {\n");
1055        script.push_str("    if (group.checks) {\n");
1056        script.push_str("      for (let checkObj of group.checks) {\n");
1057        script.push_str("        checkResults[checkObj.name] = {\n");
1058        script.push_str("          passes: checkObj.passes,\n");
1059        script.push_str("          fails: checkObj.fails,\n");
1060        script.push_str("        };\n");
1061        script.push_str("      }\n");
1062        script.push_str("    }\n");
1063        script.push_str("    if (group.groups) {\n");
1064        script.push_str("      for (let subGroup of group.groups) {\n");
1065        script.push_str("        walkGroups(subGroup);\n");
1066        script.push_str("      }\n");
1067        script.push_str("    }\n");
1068        script.push_str("  }\n");
1069        script.push_str("  if (data.root_group) {\n");
1070        script.push_str("    walkGroups(data.root_group);\n");
1071        script.push_str("  }\n");
1072        script.push_str("  let result = {\n");
1073        script.push_str(&format!(
1074            "    '{}': JSON.stringify({{ checks: checkResults, overall: checks }}, null, 2),\n",
1075            report_path
1076        ));
1077        script.push_str("    'summary.json': JSON.stringify(data),\n");
1078        script.push_str("    stdout: textSummary(data, { indent: '  ', enableColors: true }),\n");
1079        script.push_str("  };\n");
1080        script.push_str("  return result;\n");
1081        script.push_str("}\n\n");
1082        script.push_str("// textSummary fallback\n");
1083        script.push_str("function textSummary(data, opts) {\n");
1084        script.push_str("  return JSON.stringify(data, null, 2);\n");
1085        script.push_str("}\n");
1086    }
1087}
1088
1089/// Simple base64 encoding for basic auth
1090fn base64_encode(input: &str) -> String {
1091    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1092    let bytes = input.as_bytes();
1093    let mut result = String::with_capacity(bytes.len().div_ceil(3) * 4);
1094    for chunk in bytes.chunks(3) {
1095        let b0 = chunk[0] as u32;
1096        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
1097        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
1098        let triple = (b0 << 16) | (b1 << 8) | b2;
1099        result.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
1100        result.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
1101        if chunk.len() > 1 {
1102            result.push(CHARS[((triple >> 6) & 0x3F) as usize] as char);
1103        } else {
1104            result.push('=');
1105        }
1106        if chunk.len() > 2 {
1107            result.push(CHARS[(triple & 0x3F) as usize] as char);
1108        } else {
1109            result.push('=');
1110        }
1111    }
1112    result
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118
1119    #[test]
1120    fn test_generate_conformance_script() {
1121        let config = ConformanceConfig {
1122            target_url: "http://localhost:8080".to_string(),
1123            api_key: None,
1124            basic_auth: None,
1125            skip_tls_verify: false,
1126            categories: None,
1127            base_path: None,
1128            custom_headers: vec![],
1129            output_dir: None,
1130            all_operations: false,
1131            custom_checks_file: None,
1132            request_delay_ms: 0,
1133            custom_filter: None,
1134            export_requests: false,
1135            validate_requests: false,
1136        };
1137        let generator = ConformanceGenerator::new(config);
1138        let script = generator.generate().unwrap();
1139
1140        assert!(script.contains("import http from 'k6/http'"));
1141        assert!(script.contains("vus: 1"));
1142        assert!(script.contains("iterations: 1"));
1143        assert!(script.contains("group('Parameters'"));
1144        assert!(script.contains("group('Request Bodies'"));
1145        assert!(script.contains("group('Schema Types'"));
1146        assert!(script.contains("group('Composition'"));
1147        assert!(script.contains("group('String Formats'"));
1148        assert!(script.contains("group('Constraints'"));
1149        assert!(script.contains("group('Response Codes'"));
1150        assert!(script.contains("group('HTTP Methods'"));
1151        assert!(script.contains("group('Content Types'"));
1152        assert!(script.contains("group('Security'"));
1153        assert!(script.contains("handleSummary"));
1154    }
1155
1156    #[test]
1157    fn test_base64_encode() {
1158        assert_eq!(base64_encode("user:pass"), "dXNlcjpwYXNz");
1159        assert_eq!(base64_encode("a"), "YQ==");
1160        assert_eq!(base64_encode("ab"), "YWI=");
1161        assert_eq!(base64_encode("abc"), "YWJj");
1162    }
1163
1164    #[test]
1165    fn test_conformance_script_with_custom_auth() {
1166        let config = ConformanceConfig {
1167            target_url: "https://api.example.com".to_string(),
1168            api_key: Some("my-api-key".to_string()),
1169            basic_auth: Some("admin:secret".to_string()),
1170            skip_tls_verify: true,
1171            categories: None,
1172            base_path: None,
1173            custom_headers: vec![],
1174            output_dir: None,
1175            all_operations: false,
1176            custom_checks_file: None,
1177            request_delay_ms: 0,
1178            custom_filter: None,
1179            export_requests: false,
1180            validate_requests: false,
1181        };
1182        let generator = ConformanceGenerator::new(config);
1183        let script = generator.generate().unwrap();
1184
1185        assert!(script.contains("insecureSkipTLSVerify: true"));
1186        assert!(script.contains("my-api-key"));
1187        assert!(script.contains(&base64_encode("admin:secret")));
1188    }
1189
1190    #[test]
1191    fn test_should_include_category_none_includes_all() {
1192        let config = ConformanceConfig {
1193            target_url: "http://localhost:8080".to_string(),
1194            api_key: None,
1195            basic_auth: None,
1196            skip_tls_verify: false,
1197            categories: None,
1198            base_path: None,
1199            custom_headers: vec![],
1200            output_dir: None,
1201            all_operations: false,
1202            custom_checks_file: None,
1203            request_delay_ms: 0,
1204            custom_filter: None,
1205            export_requests: false,
1206            validate_requests: false,
1207        };
1208        assert!(config.should_include_category("Parameters"));
1209        assert!(config.should_include_category("Security"));
1210        assert!(config.should_include_category("Anything"));
1211    }
1212
1213    #[test]
1214    fn test_should_include_category_filtered() {
1215        let config = ConformanceConfig {
1216            target_url: "http://localhost:8080".to_string(),
1217            api_key: None,
1218            basic_auth: None,
1219            skip_tls_verify: false,
1220            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
1221            base_path: None,
1222            custom_headers: vec![],
1223            output_dir: None,
1224            all_operations: false,
1225            custom_checks_file: None,
1226            request_delay_ms: 0,
1227            custom_filter: None,
1228            export_requests: false,
1229            validate_requests: false,
1230        };
1231        assert!(config.should_include_category("Parameters"));
1232        assert!(config.should_include_category("Security"));
1233        assert!(config.should_include_category("parameters")); // case-insensitive
1234        assert!(!config.should_include_category("Composition"));
1235        assert!(!config.should_include_category("Schema Types"));
1236    }
1237
1238    #[test]
1239    fn test_generate_with_category_filter() {
1240        let config = ConformanceConfig {
1241            target_url: "http://localhost:8080".to_string(),
1242            api_key: None,
1243            basic_auth: None,
1244            skip_tls_verify: false,
1245            categories: Some(vec!["Parameters".to_string(), "Security".to_string()]),
1246            base_path: None,
1247            custom_headers: vec![],
1248            output_dir: None,
1249            all_operations: false,
1250            custom_checks_file: None,
1251            request_delay_ms: 0,
1252            custom_filter: None,
1253            export_requests: false,
1254            validate_requests: false,
1255        };
1256        let generator = ConformanceGenerator::new(config);
1257        let script = generator.generate().unwrap();
1258
1259        assert!(script.contains("group('Parameters'"));
1260        assert!(script.contains("group('Security'"));
1261        assert!(!script.contains("group('Request Bodies'"));
1262        assert!(!script.contains("group('Schema Types'"));
1263        assert!(!script.contains("group('Composition'"));
1264    }
1265
1266    #[test]
1267    fn test_effective_base_url_no_base_path() {
1268        let config = ConformanceConfig {
1269            target_url: "https://example.com".to_string(),
1270            api_key: None,
1271            basic_auth: None,
1272            skip_tls_verify: false,
1273            categories: None,
1274            base_path: None,
1275            custom_headers: vec![],
1276            output_dir: None,
1277            all_operations: false,
1278            custom_checks_file: None,
1279            request_delay_ms: 0,
1280            custom_filter: None,
1281            export_requests: false,
1282            validate_requests: false,
1283        };
1284        assert_eq!(config.effective_base_url(), "https://example.com");
1285    }
1286
1287    #[test]
1288    fn test_effective_base_url_with_base_path() {
1289        let config = ConformanceConfig {
1290            target_url: "https://example.com".to_string(),
1291            api_key: None,
1292            basic_auth: None,
1293            skip_tls_verify: false,
1294            categories: None,
1295            base_path: Some("/api".to_string()),
1296            custom_headers: vec![],
1297            output_dir: None,
1298            all_operations: false,
1299            custom_checks_file: None,
1300            request_delay_ms: 0,
1301            custom_filter: None,
1302            export_requests: false,
1303            validate_requests: false,
1304        };
1305        assert_eq!(config.effective_base_url(), "https://example.com/api");
1306    }
1307
1308    #[test]
1309    fn test_effective_base_url_trailing_slash_normalization() {
1310        let config = ConformanceConfig {
1311            target_url: "https://example.com/".to_string(),
1312            api_key: None,
1313            basic_auth: None,
1314            skip_tls_verify: false,
1315            categories: None,
1316            base_path: Some("/api".to_string()),
1317            custom_headers: vec![],
1318            output_dir: None,
1319            all_operations: false,
1320            custom_checks_file: None,
1321            request_delay_ms: 0,
1322            custom_filter: None,
1323            export_requests: false,
1324            validate_requests: false,
1325        };
1326        assert_eq!(config.effective_base_url(), "https://example.com/api");
1327    }
1328
1329    #[test]
1330    fn test_effective_base_url_trailing_slash_no_base_path() {
1331        // Regression: --target https://192.168.2.86/ without --base-path
1332        // must not produce double slashes when combined with /path
1333        let config = ConformanceConfig {
1334            target_url: "https://192.168.2.86/".to_string(),
1335            api_key: None,
1336            basic_auth: None,
1337            skip_tls_verify: false,
1338            categories: None,
1339            base_path: None,
1340            custom_headers: vec![],
1341            output_dir: None,
1342            all_operations: false,
1343            custom_checks_file: None,
1344            request_delay_ms: 0,
1345            custom_filter: None,
1346            export_requests: false,
1347            validate_requests: false,
1348        };
1349        assert_eq!(config.effective_base_url(), "https://192.168.2.86");
1350    }
1351
1352    #[test]
1353    fn test_generate_script_with_base_path() {
1354        let config = ConformanceConfig {
1355            target_url: "https://192.168.2.86".to_string(),
1356            api_key: None,
1357            basic_auth: None,
1358            skip_tls_verify: true,
1359            categories: None,
1360            base_path: Some("/api".to_string()),
1361            custom_headers: vec![],
1362            output_dir: None,
1363            all_operations: false,
1364            custom_checks_file: None,
1365            request_delay_ms: 0,
1366            custom_filter: None,
1367            export_requests: false,
1368            validate_requests: false,
1369        };
1370        let generator = ConformanceGenerator::new(config);
1371        let script = generator.generate().unwrap();
1372
1373        assert!(script.contains("const BASE_URL = 'https://192.168.2.86/api'"));
1374        // Verify URLs include the base path via BASE_URL
1375        assert!(script.contains("${BASE_URL}/conformance/"));
1376    }
1377
1378    #[test]
1379    fn test_generate_with_custom_headers() {
1380        let config = ConformanceConfig {
1381            target_url: "https://192.168.2.86".to_string(),
1382            api_key: None,
1383            basic_auth: None,
1384            skip_tls_verify: true,
1385            categories: Some(vec!["Parameters".to_string()]),
1386            base_path: Some("/api".to_string()),
1387            custom_headers: vec![
1388                ("X-Avi-Tenant".to_string(), "admin".to_string()),
1389                ("X-CSRFToken".to_string(), "real-token".to_string()),
1390            ],
1391            output_dir: None,
1392            all_operations: false,
1393            custom_checks_file: None,
1394            request_delay_ms: 0,
1395            custom_filter: None,
1396            export_requests: false,
1397            validate_requests: false,
1398        };
1399        let generator = ConformanceGenerator::new(config);
1400        let script = generator.generate().unwrap();
1401
1402        // Custom headers should be inlined into requests (no separate const)
1403        assert!(
1404            !script.contains("const CUSTOM_HEADERS"),
1405            "Script should NOT declare a CUSTOM_HEADERS const"
1406        );
1407        assert!(script.contains("'X-Avi-Tenant': 'admin'"));
1408        assert!(script.contains("'X-CSRFToken': 'real-token'"));
1409    }
1410
1411    #[test]
1412    fn test_custom_headers_js_object() {
1413        let config = ConformanceConfig {
1414            target_url: "http://localhost".to_string(),
1415            api_key: None,
1416            basic_auth: None,
1417            skip_tls_verify: false,
1418            categories: None,
1419            base_path: None,
1420            custom_headers: vec![
1421                ("Authorization".to_string(), "Bearer abc123".to_string()),
1422                ("X-Custom".to_string(), "value".to_string()),
1423            ],
1424            output_dir: None,
1425            all_operations: false,
1426            custom_checks_file: None,
1427            request_delay_ms: 0,
1428            custom_filter: None,
1429            export_requests: false,
1430            validate_requests: false,
1431        };
1432        let js = config.custom_headers_js_object();
1433        assert!(js.contains("'Authorization': 'Bearer abc123'"));
1434        assert!(js.contains("'X-Custom': 'value'"));
1435    }
1436}