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