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