#!/usr/bin/env python3 # -*- coding: utf-8 -*- """postman2tsv.py - Postman v2.1 collection -> test scenario TSV. Python 3.6.8 compatible, standard library only, offline. No JS execution: scripts are analysed statically (tokenizer + statement tree + 3-valued guards). Usage: python postman2tsv.py [--env ENVFILE] [-o OUTDIR] [--no-script-params] [--mask-secrets] [--max-cell N] [--inline-limit N] [--no-guard-eval] Outputs per collection (utf-8-sig): .tsv main TSV (14 columns, one row per request) .scripts.tsv sidecar with full ancestor scripts (Part-split) .scripts/ one .js file per ancestor script (raw UTF-8) Console: set PYTHONIOENCODING=utf-8 to see Korean text on stderr under LANG=C. """ import argparse import collections import csv import io import json import os import re import sys from http import HTTPStatus MAIN_HEADER = ['시나리오(Level 1)', '시나리오(Level 2)', '시나리오 (Level 3)', '시나리오', 'Test Case/Expected Result', 'No', 'Test Data (Request)', 'Expected Result(Response)', 'Method', 'URL(원본)', 'Headers', 'Body', '상위 Pre-script', 'Test Script 원문'] SIDE_HEADER = ['Node', 'Index Path', 'Kind', 'Part', 'Content', 'Chars', 'File'] NO_TEST = '(test script 없음)' NO_VERIFY = '(검증 없음)' UNSUMMARIZED = '(요약 불가 - 원문 참조)' COND = '(조건부)' COLL_SUFFIX = '.postman_collection.json' LAYER_ORDER = ('local', 'environment', 'collection', 'globals') RUNTIME = ('R', None, None) STR_PAT = r'"(?:[^"\\\n]|\\.)*"|\'(?:[^\'\\\n]|\\.)*\'' # --------------------------------------------------------------------------- # Kleene 3-valued logic (True / False / None = Unknown) # --------------------------------------------------------------------------- def k_and(a, b): if a is False or b is False: return False if a is True and b is True: return True return None def k_or(a, b): if a is True or b is True: return True if a is False and b is False: return False return None def k_not(a): return None if a is None else (not a) # --------------------------------------------------------------------------- # Low-level JS scanning helpers # --------------------------------------------------------------------------- def skip_string(s, i): """s[i] is a quote; return index just past the closing quote.""" q = s[i] n = len(s) i += 1 while i < n: c = s[i] if c == '\\': i += 2 continue if c == q: return i + 1 if c == '\n' and q != '`': return i i += 1 return n def skip_regex(s, i): """s[i] == '/' in regex context; return end index or -1.""" n = len(s) j = i + 1 in_class = False while j < n: c = s[j] if c == '\\': j += 2 continue if c == '\n': return -1 if in_class: if c == ']': in_class = False elif c == '[': in_class = True elif c == '/': j += 1 while j < n and (s[j].isalpha()): j += 1 return j j += 1 return -1 _REGEX_PREV = set('(,=:[!&|?{};+-*%<>~^') _REGEX_KW_TAIL = re.compile(r'(?:^|[^\w$])(?:return|typeof|case|in|of|delete|void|throw)\s*$') def strip_comments(s): """Remove // and /* */ comments (string-aware). Newlines are preserved. Regex literals are replaced by /re/ so later scanners are not confused.""" out = [] i = 0 n = len(s) last = '' while i < n: c = s[i] if c in '"\'`': j = skip_string(s, i) out.append(s[i:j]) last = c i = j continue if c == '/' and i + 1 < n: d = s[i + 1] if d == '/': j = s.find('\n', i) if j < 0: j = n out.append(' ') i = j continue if d == '*': j = s.find('*/', i + 2) j = n if j < 0 else j + 2 nl = s.count('\n', i, j) out.append('\n' * nl if nl else ' ') i = j continue if last == '' or last in _REGEX_PREV or _REGEX_KW_TAIL.search(''.join(out[-12:])): j = skip_regex(s, i) if j > 0: out.append('/re/') last = '/' i = j continue out.append(c) if not c.isspace(): last = c i += 1 return ''.join(out) def find_close(s, i): """s[i] in '([{'; return index of the matching closer or -1.""" depth = 0 n = len(s) while i < n: c = s[i] if c in '"\'`': i = skip_string(s, i) continue if c in '([{': depth += 1 elif c in ')]}': depth -= 1 if depth == 0: return i i += 1 return -1 def split_top(s, sep): """Split s at depth-0 occurrences of sep, outside strings.""" parts = [] depth = 0 i = 0 n = len(s) start = 0 L = len(sep) while i < n: c = s[i] if c in '"\'`': i = skip_string(s, i) continue if c in '([{': depth += 1 elif c in ')]}': depth -= 1 elif depth == 0 and s.startswith(sep, i): if sep == '+' and (s[i + 1:i + 2] in ('+', '=') or (i > 0 and s[i - 1] == '+')): i += 1 continue parts.append(s[start:i]) i += L start = i continue i += 1 parts.append(s[start:]) return parts def find_top_op(s, ops): """Return (pos, op) of the first depth-0 operator from ops, or (-1, None).""" depth = 0 i = 0 n = len(s) ops = sorted(ops, key=len, reverse=True) while i < n: c = s[i] if c in '"\'`': i = skip_string(s, i) continue if c in '([{': depth += 1 elif c in ')]}': depth -= 1 elif depth == 0: for op in ops: if s.startswith(op, i): prev = s[i - 1] if i > 0 else '' if op[0] in '=<>' and prev in '=!<>': continue if op in ('<', '>') and s[i + 1:i + 2] == '=': continue if op in ('<', '>') and (s[i + 1:i + 2] == op or prev == op): continue if op in ('==', '!=') and s[i + 2:i + 3] == '=': continue if op == '>' and prev == '=': continue return i, op i += 1 return -1, None def skip_ws(s, i): n = len(s) while i < n and s[i] in ' \t\r\n\f\v\ufeff\xa0': i += 1 return i # --------------------------------------------------------------------------- # JS literal parsing / static expression evaluation # --------------------------------------------------------------------------- _NUM_RE = re.compile(r'[+-]?(?:0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)') _IDENT_RE = re.compile(r'[A-Za-z_$\u0080-\uffff][\w$\u0080-\uffff]*') _SIMPLE_ESC = {'n': '\n', 't': '\t', 'r': '\r', 'b': '\b', 'f': '\f', 'v': '\v', '0': '\0'} def decode_js_string(body): if '\\' not in body: return body out = [] i = 0 n = len(body) while i < n: c = body[i] if c != '\\' or i + 1 >= n: out.append(c) i += 1 continue d = body[i + 1] if d in _SIMPLE_ESC and not (d == '0' and i + 2 < n and body[i + 2].isdigit()): out.append(_SIMPLE_ESC[d]) i += 2 elif d == 'x' and re.match(r'[0-9a-fA-F]{2}', body[i + 2:i + 4]): out.append(chr(int(body[i + 2:i + 4], 16))) i += 4 elif d == 'u' and body[i + 2:i + 3] == '{': j = body.find('}', i + 3) try: out.append(chr(int(body[i + 3:j], 16))) i = j + 1 except (ValueError, OverflowError): out.append(d) i += 2 elif d == 'u' and re.match(r'[0-9a-fA-F]{4}', body[i + 2:i + 6]): out.append(chr(int(body[i + 2:i + 6], 16))) i += 6 elif d == '\n': i += 2 else: out.append(d) i += 2 return ''.join(out) def _parse_value(t, i): i = skip_ws(t, i) c = t[i] if c in '"\'': j = skip_string(t, i) if j > len(t) or t[j - 1] != c or j - 1 == i: raise ValueError('bad string') return decode_js_string(t[i + 1:j - 1]), j if c == '`': j = skip_string(t, i) inner = t[i + 1:j - 1] if '${' in inner or t[j - 1] != '`': raise ValueError('template') return decode_js_string(inner), j if c == '[': res = [] i += 1 while True: i = skip_ws(t, i) if t[i] == ']': return res, i + 1 v, i = _parse_value(t, i) res.append(v) i = skip_ws(t, i) if t[i] == ',': i += 1 elif t[i] != ']': raise ValueError('bad array') if c == '{': res = collections.OrderedDict() i += 1 while True: i = skip_ws(t, i) if t[i] == '}': return res, i + 1 if t[i] in '"\'': j = skip_string(t, i) key = decode_js_string(t[i + 1:j - 1]) i = j else: m = _IDENT_RE.match(t, i) or _NUM_RE.match(t, i) if not m: raise ValueError('bad key') key = m.group(0) i = m.end() i = skip_ws(t, i) if t[i] != ':': raise ValueError('bad object') v, i = _parse_value(t, i + 1) res[key] = v i = skip_ws(t, i) if t[i] == ',': i += 1 elif t[i] != '}': raise ValueError('bad object') m = _NUM_RE.match(t, i) if m: txt = m.group(0) if re.match(r'[+-]?0[xX]', txt): return int(txt, 16), m.end() if '.' in txt or 'e' in txt or 'E' in txt: return float(txt), m.end() return int(txt), m.end() m = _IDENT_RE.match(t, i) if m: w = m.group(0) if w == 'true': return True, m.end() if w == 'false': return False, m.end() if w == 'null': return None, m.end() raise ValueError('not a literal') def parse_js_literal(t): """Return (ok, python_value) for a complete JS literal.""" t = t.strip() if not t: return False, None try: v, i = _parse_value(t, 0) except (ValueError, IndexError): return False, None if skip_ws(t, i) != len(t): return False, None return True, v def parse_object_props(text): """'{k: expr, ...}' -> OrderedDict key -> raw expression text (or None).""" t = text.strip() if not (t.startswith('{') and t.endswith('}')): return None if find_close(t, 0) != len(t) - 1: return None res = collections.OrderedDict() for part in split_top(t[1:-1], ','): part = part.strip() if not part: continue pos = -1 depth = 0 i = 0 while i < len(part): c = part[i] if c in '"\'`': i = skip_string(part, i) continue if c in '([{': depth += 1 elif c in ')]}': depth -= 1 elif c == ':' and depth == 0: pos = i break i += 1 if pos < 0: return None k = part[:pos].strip() ok, kv = parse_js_literal(k) if ok and isinstance(kv, str): k = kv elif not _IDENT_RE.match(k): return None res[k] = part[pos + 1:].strip() return res def render_typed(v): """JS-style rendering of a typed value.""" if v is True: return 'true' if v is False: return 'false' if v is None: return 'null' if isinstance(v, int): return str(v) if isinstance(v, float): return repr(v) if isinstance(v, str): return v try: return json.dumps(v, ensure_ascii=False, separators=(',', ':')) except (TypeError, ValueError): return str(v) _GET_RE = re.compile( r'^(pm\.environment|pm\.collectionVariables|pm\.globals|pm\.variables|pm\.iterationData|postman)' r'\s*\.\s*(get|has|getEnvironmentVariable|getGlobalVariable)\s*\(\s*(' + STR_PAT + r')\s*\)$') def _get_layer(obj, fn): if obj == 'postman': return 'globals' if 'Global' in fn else 'environment' return {'pm.environment': 'environment', 'pm.collectionVariables': 'collection', 'pm.globals': 'globals', 'pm.variables': 'merged', 'pm.iterationData': 'none'}.get(obj, 'merged') def match_get(expr): """Return (layer, key, fn) if expr is a variable getter call.""" m = _GET_RE.match(expr.strip()) if not m: return None ok, key = parse_js_literal(m.group(3)) if not ok: return None return _get_layer(m.group(1), m.group(2)), key, m.group(2) def eval_static(expr, scope): """Static evaluation: literals, getters and '+' concatenation. Returns (ok, value). Getters of undefined/RUNTIME keys yield '{{K}}'.""" expr = expr.strip() if not expr: return False, None terms = split_top(expr, '+') vals = [] for t in terms: t = t.strip() if not t: return False, None if t.startswith('(') and find_close(t, 0) == len(t) - 1: ok, v = eval_static(t[1:-1], scope) else: g = match_get(t) if g is not None: layer, key, fn = g e = scope.lookup(layer, key) if scope is not None else None if fn == 'has': return False, None if e is not None and e[0] == 'V': ok, v = True, e[1] else: ok, v = True, '{{' + key + '}}' else: ok, v = parse_js_literal(t) if not ok: return False, None vals.append(v) acc = vals[0] for v in vals[1:]: if isinstance(acc, str) or isinstance(v, str): acc = render_typed(acc) + render_typed(v) elif isinstance(acc, (int, float)) and isinstance(v, (int, float)) \ and not isinstance(acc, bool) and not isinstance(v, bool): acc = acc + v else: return False, None return True, acc # --------------------------------------------------------------------------- # Statement tree # --------------------------------------------------------------------------- _KW = re.compile(r'(if|else|switch|for|while|do|try|function|return|break|continue|throw)(?![\w$])') _FUNC_AT = re.compile(r'function(?![\w$])\s*\*?\s*[\w$]*\s*\(') _ARROW_AT = re.compile(r'(\([^()]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{') _PMTEST = re.compile(r'pm\s*\.\s*test\s*\(') _CASE_AT = re.compile(r'(case|default)(?![\w$])') def read_stmt_end(s, i): """Return (end_of_text, next_pos) for the simple statement starting at i.""" n = len(s) depth = 0 j = i while j < n: c = s[j] if c in '"\'`': j = skip_string(s, j) continue if c in '([{': depth += 1 elif c in ')]}': if depth == 0: return j, j depth -= 1 elif depth == 0: if c == ';': return j, j + 1 if c == '\n': k = skip_ws(s, j + 1) if k >= n: return j, j + 1 nxt = s[k:k + 2] cont = nxt[0] in '.?:' or (nxt[0] == '+' and nxt != '++') or nxt in ('&&', '||') if not cont: prev = s[i:j].rstrip() if prev and prev[-1] in '+-*/%,(=&|?:.[{<>!' and not prev.endswith(('++', '--')): cont = True if not cont: return j, j + 1 j += 1 return n, n def find_callbacks(text): """Callbacks inside a simple statement: [(kind, name_expr, nodes)].""" res = [] is_test = _PMTEST.match(text) is not None test_name = None if is_test: op = text.index('(') cl = find_close(text, op) if cl > 0: args = split_top(text[op + 1:cl], ',') test_name = args[0].strip() if args else None i = 0 n = len(text) first = True while i < n: c = text[i] if c in '"\'`': i = skip_string(text, i) continue prev_ok = i == 0 or not (text[i - 1].isalnum() or text[i - 1] in '_$') body_open = -1 if c == 'f' and prev_ok: m = _FUNC_AT.match(text, i) if m: p = m.end() - 1 q = find_close(text, p) if q > 0: b = skip_ws(text, q + 1) if b < n and text[b] == '{': body_open = b elif (c == '(' or c.isalpha() or c in '_$') and prev_ok: m = _ARROW_AT.match(text, i) if m: body_open = m.end() - 1 if body_open >= 0: bc = find_close(text, body_open) if bc < 0: bc = n - 1 kind = 'test' if (is_test and first) else 'unknown' first = False res.append((kind, test_name if kind == 'test' else None, parse_block(text[body_open + 1:bc]))) i = bc + 1 continue i += 1 return res def make_stmt(text): return ('stmt', text, find_callbacks(text) if ('function' in text or '=>' in text) else []) def parse_body(s, i): n = len(s) i = skip_ws(s, i) if i >= n: return [], i if s[i] == '{': j = find_close(s, i) if j < 0: j = n - 1 return parse_block(s[i + 1:j]), j + 1 node, e = parse_one(s, i) return ([node] if node is not None else []), e def parse_if(s, i): n = len(s) branches = [] else_body = None k = i + 2 e = k while True: k = skip_ws(s, k) if k >= n or s[k] != '(': end, nx = read_stmt_end(s, i) return make_stmt(s[i:end].strip()), max(nx, i + 1) j = find_close(s, k) if j < 0: return None, n cond = s[k + 1:j] body, e = parse_body(s, j + 1) branches.append((cond, body)) p = skip_ws(s, e) m = _KW.match(s, p) if m and m.group(1) == 'else': q = skip_ws(s, m.end()) m2 = _KW.match(s, q) if m2 and m2.group(1) == 'if': k = m2.end() continue else_body, e = parse_body(s, m.end()) break return ('if', branches, else_body), e def parse_switch_arms(body): marks = [] depth = 0 i = 0 n = len(body) while i < n: c = body[i] if c in '"\'`': i = skip_string(body, i) continue if c in '([{': depth += 1 elif c in ')]}': depth -= 1 elif depth == 0 and c in 'cd' and (i == 0 or not (body[i - 1].isalnum() or body[i - 1] in '_$.')): m = _CASE_AT.match(body, i) if m: p = skip_ws(body, m.end()) lit = None if m.group(1) == 'case': if p < n and body[p] in '"\'`': q = skip_string(body, p) else: mm = re.compile(r'[-\w.$]+').match(body, p) q = mm.end() if mm else p lit = body[p:q] p = skip_ws(body, q) if p < n and body[p] == ':': marks.append((lit, p + 1, i)) i = p + 1 continue i += 1 arms = [] for idx, (lit, start, _kw) in enumerate(marks): end = marks[idx + 1][2] if idx + 1 < len(marks) else n nodes = parse_block(body[start:end]) out = [] has_break = False for nd in nodes: if nd[0] == 'break': has_break = True break out.append(nd) arms.append((lit, out, has_break)) return arms def parse_one(s, i): """Parse one statement at s[i] (non-space). Returns (node|None, next_i).""" n = len(s) c = s[i] if c == '{': j = find_close(s, i) if j < 0: j = n - 1 return ('block', parse_block(s[i + 1:j])), j + 1 m = _KW.match(s, i) if m: kw = m.group(1) k = m.end() if kw == 'if': return parse_if(s, i) if kw in ('for', 'while', 'switch'): p = skip_ws(s, k) if p < n and s[p] == '(': j = find_close(s, p) if j > 0: if kw == 'switch': b = skip_ws(s, j + 1) if b < n and s[b] == '{': q = find_close(s, b) if q < 0: q = n - 1 return ('switch', s[p + 1:j], parse_switch_arms(s[b + 1:q])), q + 1 else: body, e = parse_body(s, j + 1) return ('loop', body), e elif kw == 'do': body, e = parse_body(s, k) p = skip_ws(s, e) m2 = _KW.match(s, p) if m2 and m2.group(1) == 'while': p2 = skip_ws(s, m2.end()) if p2 < n and s[p2] == '(': q = find_close(s, p2) if q > 0: e = q + 1 return ('loop', body), e elif kw == 'try': body, e = parse_body(s, k) catch_body = [] fin_body = [] p = skip_ws(s, e) m2 = _KW.match(s, p) if s.startswith('catch', p): p2 = skip_ws(s, p + 5) if p2 < n and s[p2] == '(': q = find_close(s, p2) p2 = q + 1 if q > 0 else p2 catch_body, e = parse_body(s, p2) p = skip_ws(s, e) if s.startswith('finally', p): fin_body, e = parse_body(s, p + 7) return ('try', body, catch_body, fin_body), e elif kw == 'function': p = s.find('(', k) if p >= 0: j = find_close(s, p) if j > 0: b = skip_ws(s, j + 1) if b < n and s[b] == '{': q = find_close(s, b) if q < 0: q = n - 1 return ('func', parse_block(s[b + 1:q])), q + 1 elif kw == 'else': body, e = parse_body(s, k) return ('loop', body), e elif kw in ('return', 'throw', 'break', 'continue'): end, nx = read_stmt_end(s, i) return (('break',) if kw in ('break', 'continue') else ('return',)), max(nx, i + 1) end, nx = read_stmt_end(s, i) text = s[i:end].strip() if not text: return None, max(nx, i + 1) return make_stmt(text), max(nx, i + 1) def parse_block(s): nodes = [] i = 0 n = len(s) while True: while i < n and (s[i] in ' \t\r\n\f\v\ufeff\xa0;'): i += 1 if i >= n: break if s[i] in ')]}': i += 1 continue node, i = parse_one(s, i) if node is not None: nodes.append(node) return nodes _PARSE_CACHE = {} def parse_script(text): t = _PARSE_CACHE.get(text) if t is None: t = parse_block(strip_comments(text)) _PARSE_CACHE[text] = t return t def iter_stmts(nodes): """Yield every simple statement text in a tree (all branches).""" for nd in nodes: k = nd[0] if k == 'stmt': yield nd[1] for _kind, _name, body in nd[2]: for x in iter_stmts(body): yield x elif k in ('block', 'loop', 'func'): for x in iter_stmts(nd[1]): yield x elif k == 'if': for _c, body in nd[1]: for x in iter_stmts(body): yield x if nd[2]: for x in iter_stmts(nd[2]): yield x elif k == 'switch': for _l, body, _b in nd[2]: for x in iter_stmts(body): yield x elif k == 'try': for part in nd[1:]: for x in iter_stmts(part): yield x # --------------------------------------------------------------------------- # Scope (four Postman variable layers) # --------------------------------------------------------------------------- class Scope(object): __slots__ = ('layers', 'unk', 'test_primary', 'test_cond', 'params', 'heur') def __init__(self): self.layers = dict((k, collections.OrderedDict()) for k in LAYER_ORDER) self.unk = set() self.test_primary = collections.OrderedDict() self.test_cond = [] self.params = [] self.heur = False def copy(self): c = Scope.__new__(Scope) c.layers = dict((k, collections.OrderedDict(v)) for k, v in self.layers.items()) c.unk = set(self.unk) c.test_primary = collections.OrderedDict(self.test_primary) c.test_cond = list(self.test_cond) c.params = list(self.params) c.heur = self.heur return c def lookup(self, layer, key): if layer == 'merged': for L in LAYER_ORDER: d = self.layers[L] if key in d: return d[key] return None if layer == 'none': return None return self.layers[layer].get(key) def truthy(e): if e is None: return False if e[0] == 'R': return None v = e[1] if v is None or v is False: return False if v is True: return True if isinstance(v, (int, float)): return v != 0 and v == v if isinstance(v, str): if v == '': return False if e[2] in ('env', 'coll') and v.strip().lower() in ('false', '0'): return False return True return True _COND_CACHE = {} def parse_cond(t): t = t.strip() parts = split_top(t, '||') if len(parts) > 1: return ('or', [parse_cond(p) for p in parts]) parts = split_top(t, '&&') if len(parts) > 1: return ('and', [parse_cond(p) for p in parts]) if t.startswith('!') and not t.startswith('!='): return ('not', parse_cond(t[1:])) if t.startswith('(') and find_close(t, 0) == len(t) - 1: return parse_cond(t[1:-1]) return ('atom', t) _INCLUDES_RE = re.compile(r'^(\[.*\])\s*\.\s*includes\s*\((.*)\)$', re.S) def eval_atom(a, scope): a = a.strip() if a == 'true': return True if a == 'false': return False g = match_get(a) if g is not None: e = scope.lookup(g[0], g[1]) if g[2] == 'has': if e is None: return False return None if e[0] == 'R' else True return truthy(e) pos, op = find_top_op(a, ('===', '!==', '==', '!=')) if pos >= 0: left = a[:pos].strip() right = a[pos + len(op):].strip() g = match_get(left) other = right if g is None: g = match_get(right) other = left if g is None: return None e = scope.lookup(g[0], g[1]) if e is None or e[0] == 'R': return None ok, lit = parse_js_literal(other) if not ok: return None eq = render_typed(e[1]) == render_typed(lit) return eq if op in ('==', '===') else (not eq) m = _INCLUDES_RE.match(a) if m: ok, lst = parse_js_literal(m.group(1)) g = match_get(m.group(2)) if not ok or g is None or not isinstance(lst, list): return None e = scope.lookup(g[0], g[1]) if e is None or e[0] == 'R': return None sv = render_typed(e[1]) return any(render_typed(x) == sv for x in lst) return None def eval_cond(tree, scope, false_atoms): t = tree[0] if t == 'or': r = False for c in tree[1]: r = k_or(r, eval_cond(c, scope, false_atoms)) return r if t == 'and': r = True for c in tree[1]: r = k_and(r, eval_cond(c, scope, false_atoms)) return r if t == 'not': return k_not(eval_cond(tree[1], scope, false_atoms)) v = eval_atom(tree[1], scope) if v is False: false_atoms.append(re.sub(r'\s+', ' ', tree[1])[:80]) return v # --------------------------------------------------------------------------- # Tree execution (shared by pre-script application and test summarising) # --------------------------------------------------------------------------- class BaseCtx(object): def __init__(self, scope, opts, stats): self.scope = scope self.opts = opts self.stats = stats def guard(self, cond): if self.opts.no_guard_eval: self.stats['unknown_guards'] += 1 return None tree = _COND_CACHE.get(cond) if tree is None: tree = parse_cond(cond) _COND_CACHE[cond] = tree fa = [] v = eval_cond(tree, self.scope, fa) self._count(v, fa) return v def case_match(self, expr, lit): if self.opts.no_guard_eval: return None g = match_get(expr) if g is None: return None e = self.scope.lookup(g[0], g[1]) if e is None or e[0] == 'R': return None ok, lv = parse_js_literal(lit) if not ok: return None return render_typed(e[1]) == render_typed(lv) def _count(self, v, fa): if v is None: self.stats['unknown_guards'] += 1 elif v is False: self.stats['false_guards'] += 1 for a in fa: self.stats['false_atoms'][a] += 1 def stmt(self, text, g): pass def enter_cb(self, kind, name, g): pass def exit_cb(self, kind, name, g): pass def exec_nodes(nodes, g, ctx): """Walk a statement tree under guard g. Returns True if a return was hit.""" returned = False for nd in nodes: eg = k_and(g, None) if returned else g if eg is False: continue kind = nd[0] r = False if kind == 'stmt': ctx.stmt(nd[1], eg) for ck, name, body in nd[2]: cg = eg if ck == 'test' else k_and(eg, None) ctx.enter_cb(ck, name, cg) exec_nodes(body, cg, ctx) ctx.exit_cb(ck, name, cg) elif kind == 'block': r = exec_nodes(nd[1], eg, ctx) elif kind == 'if': prior = True for cond, body in nd[1]: c = ctx.guard(cond) bg = k_and(eg, k_and(prior, c)) prior = k_and(prior, k_not(c)) if bg is not False and exec_nodes(body, bg, ctx): r = True if prior is False: break if nd[2] is not None and prior is not False: if exec_nodes(nd[2], k_and(eg, prior), ctx): r = True elif kind == 'switch': arms = nd[2] matches = [ctx.case_match(nd[1], lit) if lit is not None else 'default' for lit, _b, _h in arms] any_m = False for mv in matches: if mv != 'default': any_m = k_or(any_m, mv) entered = False prev_break = True for (lit, body, has_break), mv in zip(arms, matches): mm = k_not(any_m) if mv == 'default' else mv entered = mm if prev_break else k_or(entered, mm) prev_break = has_break bg = k_and(eg, entered) if bg is not False and exec_nodes(body, bg, ctx): r = True elif kind == 'loop': r = exec_nodes(nd[1], k_and(eg, None), ctx) elif kind == 'func': exec_nodes(nd[1], k_and(eg, None), ctx) elif kind == 'try': r = exec_nodes(nd[1], eg, ctx) if exec_nodes(nd[2], k_and(eg, None), ctx): r = True if exec_nodes(nd[3], eg, ctx): r = True elif kind == 'return': r = True if r: returned = True return returned # --------------------------------------------------------------------------- # Pre-script application (sets, TEST_* record, script params) # --------------------------------------------------------------------------- _SET_RE = re.compile( r'^(pm\.environment|pm\.collectionVariables|pm\.globals|pm\.variables|postman)\s*\.\s*' r'(set|unset|setEnvironmentVariable|setGlobalVariable|clearEnvironmentVariable|clearGlobalVariable)\s*\(', re.S) _PARAM_RE = re.compile( r'^pm\s*\.\s*request\s*\.\s*(body\s*\.\s*urlencoded|body\s*\.\s*formdata|url\s*\.\s*query|headers)' r'\s*\.\s*(add|upsert|remove|clear|append)\s*\(', re.S) _PARAM_RE2 = re.compile(r'^pm\s*\.\s*request\s*\.\s*(addHeader|removeHeader|upsertHeader)\s*\(', re.S) def call_args(text, m): """For a regex match ending in '(', return the arg list if the call spans the text.""" p = m.end() - 1 q = find_close(text, p) if q < 0 or text[q + 1:].strip() not in ('', ';'): return None args = [a.strip() for a in split_top(text[p + 1:q], ',')] while args and args[-1] == '': args.pop() return args def match_set(text): """Return (layer, key_expr, value_expr|None) for a variable set/unset call.""" m = _SET_RE.match(text) if not m: return None args = call_args(text, m) if args is None or not args: return None obj, fn = m.group(1), m.group(2) if obj == 'postman': layer = 'globals' if 'Global' in fn else 'environment' else: layer = {'pm.environment': 'environment', 'pm.collectionVariables': 'collection', 'pm.globals': 'globals', 'pm.variables': 'local'}[obj] is_unset = fn in ('unset', 'clearEnvironmentVariable', 'clearGlobalVariable') or len(args) == 1 return layer, args[0], (None if is_unset else args[1]) def match_param(text): """Return (target, op, args) for a pm.request param mutation.""" m = _PARAM_RE.match(text) if m: target = re.sub(r'\s+', '', m.group(1)).replace('body.', '') op = m.group(2) if op == 'append': op = 'add' args = call_args(text, m) return None if args is None else (target, op, args) m = _PARAM_RE2.match(text) if m: args = call_args(text, m) op = {'addHeader': 'add', 'removeHeader': 'remove', 'upsertHeader': 'upsert'}[m.group(1)] return None if args is None else ('headers', op, args) return None class PreCtx(BaseCtx): def stmt(self, text, g): ms = match_set(text) if ms is not None: layer, kexpr, vexpr = ms ok, key = parse_js_literal(kexpr) if not ok or not isinstance(key, str): return if vexpr is None: self.apply_set(layer, key, None, g) else: ok, v = eval_static(vexpr, self.scope) self.apply_set(layer, key, ('V', v, 'script') if ok else RUNTIME, g) return mp = match_param(text) if mp is not None: self.param_op(mp, g) def apply_set(self, layer, key, entry, g): sc = self.scope if key.startswith('TEST_'): if entry is None: if g is True: sc.test_primary.pop(key, None) elif g is True: sc.test_primary[key] = entry else: sc.test_cond.append((key, entry)) L = sc.layers[layer] if entry is None: if g is True: L.pop(key, None) sc.unk.discard((layer, key)) return if g is True: L[key] = entry sc.unk.discard((layer, key)) return if entry[0] == 'R': L[key] = entry sc.heur = True return if (layer, key) in sc.unk: return cur = L.get(key) if cur is None or (cur[0] == 'V' and cur[1] == ''): L[key] = entry sc.unk.add((layer, key)) sc.heur = True def param_op(self, mp, g): if self.opts.no_script_params: return target, op, args = mp if op in ('add', 'upsert'): if not args: self.stats['skipped_param_ops'] += 1 return props = parse_object_props(args[0]) if props is None or 'key' not in props: self.stats['skipped_param_ops'] += 1 return ok, key = eval_static(props['key'], self.scope) ok2, val = (True, '') if props.get('value') is None else eval_static(props['value'], self.scope) dis = False if props.get('disabled') is not None: okd, dv = parse_js_literal(props['disabled']) dis = bool(dv) if okd else False if not (ok and ok2): self.stats['skipped_param_ops'] += 1 return item = {'key': render_typed(key), 'value': val, 'disabled': dis, 'script': True} if target == 'formdata' and props.get('src') is not None: oks, src = eval_static(props['src'], self.scope) if oks: item['src'] = src item['type'] = 'file' self.scope.params.append((target, op, item)) elif op == 'remove': ok, key = (False, None) if not args else eval_static(args[0], self.scope) if not ok: self.stats['skipped_param_ops'] += 1 return self.scope.params.append((target, 'remove', {'key': render_typed(key)})) else: self.scope.params.append((target, 'clear', None)) if g is None: self.scope.heur = True def apply_script(text, scope, opts, stats): if text and text.strip(): exec_nodes(parse_script(text), True, PreCtx(scope, opts, stats)) def script_static_sets(text): """Keys of static set templates in source order (for the digest).""" keys = [] for st in iter_stmts(parse_script(text)): ms = match_set(st) if ms is None or ms[2] is None: continue ok, key = parse_js_literal(ms[1]) if not ok or not isinstance(key, str): continue okv, _v = eval_static(ms[2], None) if okv and key not in keys: keys.append(key) return keys _TESTSET_CACHE = {} def script_sets_test(text): r = _TESTSET_CACHE.get(text) if r is None: r = False if text and 'TEST_' in text: for st in iter_stmts(parse_script(text)): ms = match_set(st) if ms is not None and ms[2] is not None: ok, key = parse_js_literal(ms[1]) if ok and isinstance(key, str) and key.startswith('TEST_'): r = True break _TESTSET_CACHE[text] = r return r # --------------------------------------------------------------------------- # Variable resolution # --------------------------------------------------------------------------- _VAR_RE = re.compile(r'\{\{([^{}]+)\}\}') def resolve(text, scope, unresolved=None): if not text or '{{' not in text: return text cur = text for _ in range(10): def rep(m): name = m.group(1) if name.startswith('$'): return m.group(0) e = scope.lookup('merged', name) if e is None: if unresolved is not None: unresolved[name] = 'undefined' return m.group(0) if e[0] == 'R': if unresolved is not None: unresolved[name] = 'runtime' return m.group(0) return render_typed(e[1]) nxt = _VAR_RE.sub(rep, cur) if nxt == cur: break cur = nxt return cur # --------------------------------------------------------------------------- # Test summariser # --------------------------------------------------------------------------- _TESTS_ASSIGN = re.compile(r'^tests\s*\[') _P1 = re.compile(r'^(?:responseCode\.code|pm\.response\.code|pm\.response\.status|responseCode)\s*={2,3}\s*(\d{3})$') _P2 = re.compile(r'^pm\.response\.to\.(?:have\.|be\.)?status\s*\(\s*(\d{3}|' + STR_PAT + r')\s*\)$') _P2OK = re.compile(r'^pm\.response\.to\.(?:be\.)?ok$') _RT = re.compile(r'^(?:responseTime|pm\.response\.responseTime)\s*(<=|<)\s*(\d+(?:\.\d+)?)$') _HAS = re.compile(r'^responseBody\.has\(\s*(' + STR_PAT + r')\s*\)$') _HEADER = re.compile(r'^pm\.response\.to\.have\.header\(\s*(' + STR_PAT + r')\s*(?:,.*)?\)$') _EXPECT = re.compile(r'^(?:pm\s*\.\s*)?expect\s*\(') _PATH_RE = re.compile(r'^([A-Za-z_$][\w$]*)((?:\s*\.\s*[A-Za-z_$][\w$]*|\s*\[\s*(?:\d+|"[^"]*"|\'[^\']*\'|' r'[A-Za-z_$][\w$]*)\s*\])*)$') _HDR_GET = re.compile(r'^(?:postman\.getResponseHeader|pm\.response\.headers\.get)\(\s*(' + STR_PAT + r')\s*\)$') def status_text(n): try: return '%d %s' % (n, HTTPStatus(n).phrase) except ValueError: return str(n) def phrase_to_code(p): for st in HTTPStatus: if st.phrase.lower() == p.lower(): return int(st) return None def render_subject(e): e = e.strip() if e in ('pm.response.text()', 'responseBody', 'pm.response.body'): return 'BODY' if e in ('pm.response.code', 'responseCode.code', 'pm.response.status'): return 'STATUS' if e in ('pm.response.responseTime', 'responseTime'): return 'RT' m = _HDR_GET.match(e) if m: return 'header ' + parse_js_literal(m.group(1))[1] if e.startswith('pm.response.json()'): rest = e[len('pm.response.json()'):].lstrip('.') return re.sub(r'\s+', '', rest) or 'body' m = _PATH_RE.match(e) if m: head, tail = m.group(1), re.sub(r'\s+', '', m.group(2)) if head in ('pm', 'postman'): return re.sub(r'\s+', '', e) return tail.lstrip('.') if tail else head return re.sub(r'\s+', ' ', e) def value_text(expr, scope): ok, v = eval_static(expr, scope) if not ok: return None return resolve(render_typed(v), scope) def list_text(expr, scope): ok, v = parse_js_literal(expr) if ok and isinstance(v, list): return '[' + ','.join(render_typed(x) for x in v) + ']' return None def parse_chai(t): m = _EXPECT.match(t) if not m: return None op = m.end() - 1 cl = find_close(t, op) if cl < 0: return None sargs = split_top(t[op + 1:cl], ',') subj = sargs[0].strip() rest = t[cl + 1:] chain = [] i = 0 n = len(rest) while True: i = skip_ws(rest, i) if i >= n: break if rest[i] != '.': return subj, chain, rest[i:].strip() mm = _IDENT_RE.match(rest, skip_ws(rest, i + 1)) if not mm: return subj, chain, rest[i:].strip() k = skip_ws(rest, mm.end()) if k < n and rest[k] == '(': c2 = find_close(rest, k) if c2 < 0: return None chain.append((mm.group(0), rest[k + 1:c2])) i = c2 + 1 else: chain.append((mm.group(0), None)) i = mm.end() return subj, chain, '' _CMP_OPS = ('===', '!==', '==', '!=', '<=', '>=', '<', '>') _CMP_NORM = {'===': '=', '==': '=', '!==': '!=', '!=': '!='} def classify_chai(subj, chain, label, scope): neg = sum(1 for nm, a in chain if nm == 'not') % 2 == 1 calls = [(nm, a) for nm, a in chain if a is not None] props = [nm for nm, a in chain if a is None] S = render_subject(subj) if calls: name, args = calls[-1] argl = split_top(args, ',') if args.strip() else [] arg0 = argl[0].strip() if argl else '' if name in ('equal', 'equals', 'eq', 'eql', 'eqls'): if S == 'STATUS': okv, v = parse_js_literal(arg0) if okv and isinstance(v, int) and not neg: return [('status', v)] vt = value_text(arg0, scope) return [('item', 'status%s%s' % ('!=' if neg else '=', vt))] if vt is not None else [] if not arg0: return [('item', '%s %s' % (S, 'defined' if neg else 'undefined'))] vt = value_text(arg0, scope) if vt is None: return [] lab = label if label else ('body' if S == 'BODY' else S) return [('item', '%s%s%s' % (lab, '!=' if neg else '=', vt))] if name in ('include', 'includes', 'contain', 'contains', 'string'): vt = value_text(arg0, scope) if vt is None: return [] word = 'not contains' if neg else 'contains' if S == 'BODY': return [('item', '%s "%s"' % (word, vt))] return [('item', '%s %s "%s"' % (S, word, vt))] if name == 'oneOf': lt = list_text(arg0, scope) if lt is None: return [] s = 'status' if S == 'STATUS' else S return [('item', '%s %s %s' % (s, 'not in' if neg else 'in', lt))] if name in ('property', 'ownProperty', 'haveOwnProperty', 'key', 'keys'): vt = value_text(arg0, scope) if vt is None: return [] return [('item', '%s %s %s' % (S, 'not has' if neg else 'has', vt))] cmp_map = {'below': '<', 'lessThan': '<', 'lt': '<', 'above': '>', 'greaterThan': '>', 'gt': '>', 'least': '>=', 'gte': '>=', 'most': '<=', 'lte': '<='} if name in cmp_map: vt = value_text(arg0, scope) if vt is None: return [] if S == 'RT': return [('item', 'responseTime%s%sms' % (cmp_map[name], vt))] return [('item', '%s%s%s' % (S, cmp_map[name], vt))] if name in ('lengthOf', 'length'): vt = value_text(arg0, scope) return [('item', '%s.length=%s' % (S, vt))] if vt is not None else [] if name in ('a', 'an'): vt = value_text(arg0, scope) return [('item', '%s is %s' % (S, vt))] if vt is not None else [] return [] for p in reversed(props): if p == 'undefined': return [('item', '%s %s' % (S, 'defined' if neg else 'undefined'))] if p in ('null', 'true', 'false'): return [('item', '%s%s%s' % (S, '!=' if neg else '=', p))] if p in ('ok', 'empty', 'NaN'): return [('item', '%s %s%s' % (S, 'not ' if neg else '', p))] if p in ('exist', 'exists'): return [('item', '%s %s' % (S, 'not exists' if neg else 'exists'))] return [] def cmp_item(left, op, right, scope): """Comparison expression -> item text or None.""" left = left.strip() right = right.strip() o = _CMP_NORM.get(op, op) ml = parse_chai(left) mr = parse_chai(right) if ml and mr and not ml[1] and not mr[1] and not ml[2] and not mr[2]: return '%s%s%s' % (render_subject(ml[0]), o, render_subject(mr[0])) ls = render_subject(left) if ls == 'RT': vt = value_text(right, scope) return 'responseTime%s%sms' % (o, vt) if vt is not None else None if _PATH_RE.match(left) and not left.startswith(('pm.', 'postman.')): vt = value_text(right, scope) if vt is not None: return '%s%s%s' % (ls, o, vt) if _PATH_RE.match(right): return '%s%s%s' % (ls, o, render_subject(right)) return None def summarize_stmt(text, scope): """Return list of ('status', N) / ('item', text); [] if nothing matched.""" t = text.strip().rstrip(';').strip() label = None if _TESTS_ASSIGN.match(t): lb = t.index('[') rb = find_close(t, lb) if rb > 0: rest = t[rb + 1:].lstrip() if rest.startswith('=') and not rest.startswith('=='): ok, lv = parse_js_literal(t[lb + 1:rb]) label = lv if ok and isinstance(lv, str) else None t = rest[1:].strip() m = _P1.match(t) if m: return [('status', int(m.group(1)))] m = _P2.match(t) if m: v = m.group(1) if v[0] in '"\'': code = phrase_to_code(parse_js_literal(v)[1]) return [('status', code)] if code else [] return [('status', int(v))] if _P2OK.match(t): return [('status', 200)] m = _RT.match(t) if m: return [('item', 'responseTime%s%sms' % (m.group(1), m.group(2)))] m = _HAS.match(t) if m: return [('item', 'contains "%s"' % resolve(parse_js_literal(m.group(1))[1], scope))] m = _HEADER.match(t) if m: return [('item', 'has header %s' % parse_js_literal(m.group(1))[1])] if _EXPECT.match(t): pc = parse_chai(t) if pc is None: return [] subj, chain, left = pc if left: pos, op = find_top_op(left, _CMP_OPS) if pos == 0: it = cmp_item(t[:len(t) - len(left)], op, left[len(op):], scope) return [('item', it)] if it else [] return [] if not chain: pos, op = find_top_op(subj, _CMP_OPS) if pos > 0: it = cmp_item(subj[:pos], op, subj[pos + len(op):], scope) return [('item', it)] if it else [] return [] return classify_chai(subj, chain, label, scope) pos, op = find_top_op(t, _CMP_OPS) if pos > 0: it = cmp_item(t[:pos], op, t[pos + len(op):], scope) return [('item', it)] if it else [] return [] class SumCtx(BaseCtx): def __init__(self, scope, opts, stats): BaseCtx.__init__(self, scope, opts, stats) self.status = [] self.items = [] self.cond = [] self.unmatched = [] self.stack = [] def total(self): return len(self.status) + len(self.items) + len(self.cond) def add(self, kind, val, g): if g is True: if kind == 'status': self.status.append(val) else: self.items.append(val) else: self.cond.append(status_text(val) if kind == 'status' else val) def stmt(self, text, g): res = summarize_stmt(text, self.scope) if not res: self.unmatched.append(text) for kind, val in res: self.add(kind, val, g) def enter_cb(self, kind, name, g): self.stack.append(self.total()) def exit_cb(self, kind, name, g): before = self.stack.pop() if kind == 'test' and self.total() == before and name: ok, v = eval_static(name, self.scope) if ok: self.add('item', resolve(render_typed(v), self.scope), g) def run_summary(text, scope, opts, stats): ctx = SumCtx(scope, opts, stats) if text and text.strip(): exec_nodes(parse_script(text), True, ctx) return ctx def shape_of(stmt): s = re.sub(STR_PAT, 'S', stmt) s = re.sub(r'\b\d+(?:\.\d+)?\b', 'N', s) return re.sub(r'\s+', ' ', s)[:100] def dedupe(seq): seen = set() out = [] for x in seq: if x not in seen: seen.add(x) out.append(x) return out def test_value_text(entry, scope): if entry[0] == 'R': return '(runtime)' return resolve(render_typed(entry[1]), scope) def coerce_status(entry, scope): s = test_value_text(entry, scope).strip() if s == '' or s == '(runtime)': return None try: return int(s) except ValueError: try: return int(float(s)) except ValueError: return s def build_expected(req_test, anc_tests, scope, verifiable, opts, stats): """Returns (text, unsummarized_flag, cond_count, unmatched_stmts).""" if not verifiable: return NO_VERIFY, False, 0, [] ctx = run_summary(req_test, scope, opts, stats) tprim = [] t_status = None for k, e in scope.test_primary.items(): if k == 'TEST_status': t_status = coerce_status(e, scope) else: tprim.append('%s=%s' % (k[5:], test_value_text(e, scope))) tcond = [] for k, e in scope.test_cond: if k == 'TEST_status': c = coerce_status(e, scope) if c is not None: tcond.append(status_text(c) if isinstance(c, int) else str(c)) else: tcond.append('%s=%s' % (k[5:], test_value_text(e, scope))) status = list(ctx.status) items = list(ctx.items) cond = list(ctx.cond) if not (status or items or cond or tprim or tcond or t_status is not None): for at in anc_tests: actx = run_summary(at, scope, opts, stats) status += actx.status items += actx.items cond += actx.cond parts = [] st = dedupe(status) if st: slot = status_text(st[0]) if t_status is not None and t_status != st[0]: slot += ' (TEST_status %s)' % t_status parts.append(slot) items = [status_text(x) for x in st[1:]] + items elif t_status is not None: parts.append(status_text(t_status) if isinstance(t_status, int) else str(t_status)) parts += tprim parts += [x for x in dedupe(items) if x not in parts] allc = dedupe(tcond + cond) if allc: parts.append(COND + ' ' + ' / '.join(allc)) if not parts: return UNSUMMARIZED, True, 0, ctx.unmatched return ' / '.join(parts), False, len(allc), [] # --------------------------------------------------------------------------- # Request rendering # --------------------------------------------------------------------------- def script_text(events, listen): """Concatenate enabled events of one type. exec may be list or str.""" out = [] for e in events or []: if not isinstance(e, dict) or e.get('listen') != listen or e.get('disabled'): continue sc = e.get('script') if isinstance(sc, str): out.append(sc) continue if not isinstance(sc, dict): continue ex = sc.get('exec') if isinstance(ex, list): out.append('\n'.join(x if isinstance(x, str) else '' for x in ex)) elif isinstance(ex, str): out.append(ex) return '\n'.join(out) def description_text(d): if isinstance(d, dict): d = d.get('content') return d if isinstance(d, str) else '' def normalize_request(item): r = item.get('request') if isinstance(r, str): return {'method': 'GET', 'url': r, 'header': [], 'body': None, 'auth': None, 'description': ''} if not isinstance(r, dict): raise TypeError('request must be an object or string, got %s' % type(r).__name__) if 'url' in r and r['url'] is None: raise ValueError('request.url is null') url = r.get('url', '') if not isinstance(url, (str, dict)): raise TypeError('request.url must be a string or object, got %s' % type(url).__name__) header = r.get('header') or [] if isinstance(header, str): hl = [] for line in header.splitlines(): if ':' in line: k, v = line.split(':', 1) hl.append({'key': k.strip(), 'value': v.strip()}) header = hl if not isinstance(header, list): header = [] method = r.get('method') if not isinstance(method, str) or not method: method = 'GET' body = r.get('body') if isinstance(r.get('body'), dict) else None auth = r.get('auth') if isinstance(r.get('auth'), dict) else None return {'method': method, 'url': url, 'header': header, 'body': body, 'auth': auth, 'description': description_text(r.get('description'))} def split_raw(raw): q = raw.find('?') if q >= 0: base = raw[:q] rest = raw[q + 1:] h = rest.find('#') if h >= 0: return base, rest[:h], rest[h + 1:] return base, rest, None h = raw.find('#') if h >= 0: return raw[:h], None, raw[h + 1:] return raw, None, None def build_raw(url): proto = url.get('protocol') host = url.get('host') path = url.get('path') s = '' if proto: s += str(proto) + '://' if isinstance(host, list): s += '.'.join(str(x) for x in host) elif host: s += str(host) if url.get('port'): s += ':' + str(url['port']) if isinstance(path, list): s += '/' + '/'.join(x if isinstance(x, str) else str((x or {}).get('value', '')) for x in path) elif path: s += '/' + str(path).lstrip('/') return s def parse_qs_items(qs): items = [] if not qs: return items for part in qs.split('&'): if '=' in part: k, v = part.split('=', 1) items.append({'key': k, 'value': v}) else: items.append({'key': part, 'value': None}) return items def url_parts(url): """-> (raw, base, query_items, hash)""" if isinstance(url, str): raw = url qitems = None else: raw = url.get('raw') if not isinstance(raw, str): raw = build_raw(url) qitems = url.get('query') if isinstance(url.get('query'), list) else None base, qs, h = split_raw(raw) if qitems is None: qitems = parse_qs_items(qs) if h is None and isinstance(url, dict) and isinstance(url.get('hash'), str): h = url['hash'] return raw, base, [dict(q) for q in qitems if isinstance(q, dict)], h def rebuild_query(items): """Enabled items -> query string. Null key -> '', null value -> key without '='.""" parts = [] for q in items: if q.get('disabled'): continue k = q.get('key') v = q.get('value') k = '' if k is None else render_typed(k) if v is None: parts.append(k) else: parts.append(k + '=' + render_typed(v)) return '&'.join(parts) def apply_ops(items, ops, target): items = list(items) for tg, op, it in ops: if tg != target: continue if op == 'clear': items = [] elif op == 'remove': items = [x for x in items if x.get('key') != it['key']] elif op == 'upsert': for idx, x in enumerate(items): if x.get('key') == it['key']: items[idx] = dict(it) break else: items.append(dict(it)) else: items.append(dict(it)) return items def auth_param(params, key): if isinstance(params, list): for p in params: if isinstance(p, dict) and p.get('key') == key: return p.get('value') return None if isinstance(params, dict): return params.get(key) return None def auth_lines(auth, inherited): t = auth.get('type') if not t or t == 'noauth': return [] params = auth.get(t) tag = ' [auth 상속]' if inherited else ' [auth]' s = lambda v: '' if v is None else render_typed(v) if t == 'bearer': return ['Authorization: Bearer ' + s(auth_param(params, 'token')) + tag] if t == 'basic': return ['Authorization: Basic ' + s(auth_param(params, 'username')) + ':' + s(auth_param(params, 'password')) + tag] if t == 'apikey': return [s(auth_param(params, 'key')) + ': ' + s(auth_param(params, 'value')) + tag] if t == 'oauth2': return ['Authorization: Bearer ' + s(auth_param(params, 'accessToken')) + tag] return ['[auth ' + str(t) + ']' + tag] def effective_auth(req_auth, chain): if isinstance(req_auth, dict) and req_auth.get('type') and req_auth.get('type') != 'inherit': return req_auth, False for node in reversed(chain): a = node.auth if isinstance(a, dict) and a.get('type') and a.get('type') != 'inherit': return a, True return None, False def kv_line(it, sep): k = it.get('key') k = '' if k is None else render_typed(k) if it.get('type') == 'file' or it.get('src') is not None and it.get('value') in (None, ''): src = it.get('src') if isinstance(src, list): src = ','.join(str(x) for x in src) line = k + sep + '@' + ('' if src is None else str(src)) else: v = it.get('value') line = k if v is None else k + sep + render_typed(v) return line + (' [script]' if it.get('script') else '') def body_text(body, ops): """-> (original_text, skipped_ops)""" if not body or body.get('disabled'): return '', 0 mode = body.get('mode') if mode == 'raw': raw = body.get('raw') if raw is None: return '', 0 return (raw if isinstance(raw, str) else json.dumps(raw, ensure_ascii=False)), 0 if mode in ('urlencoded', 'formdata'): base = [dict(x) for x in (body.get(mode) or []) if isinstance(x, dict)] items = apply_ops(base, ops, mode) return '\n'.join(kv_line(x, '=') for x in items if not x.get('disabled')), 0 if mode == 'graphql': g = body.get('graphql') or {} q = g.get('query') or '' v = g.get('variables') or '' if not isinstance(v, str): v = json.dumps(v, ensure_ascii=False) return q + ('\n[variables]\n' + v if v else ''), 0 if mode == 'file': f = body.get('file') or {} src = f.get('src') if isinstance(f, dict) else f return '[file] ' + ('' if src is None else str(src)), 0 return '', 0 # --------------------------------------------------------------------------- # Output helpers: escaping, truncation, masking, sidecar parts # --------------------------------------------------------------------------- def escape_cell(s): s = s.replace('\r\n', '\n').replace('\r', '\n') return s.replace('\n', '\\n').replace('\t', '\\t') def fit_cell(s, limit, mask): if s is None: s = '' if not isinstance(s, str): s = str(s) if mask is not None: s = mask(s) e = escape_cell(s) if len(e) > limit: keep = max(0, limit - len('…[truncated %d chars]' % len(e))) cut = e[:keep] if cut.endswith('\\'): cut = cut[:-1] e = cut + '…[truncated %d chars]' % (len(e) - len(cut)) return e def split_parts(esc, limit): if not esc: return [''] parts = [] i = 0 n = len(esc) limit = max(2, limit) while i < n: j = min(i + limit, n) if j < n and esc[j - 1] == '\\': j -= 1 parts.append(esc[i:j]) i = j return parts _SECRET_KEY = re.compile(r'(?i)(api[_-]?key|access[_-]?token|token|secret|password|passwd|authorization|access[_-]?key)') def make_masker(secret_values): lits = sorted(set(v for v in secret_values if isinstance(v, str) and len(v) >= 6 and '{{' not in v), key=len, reverse=True) pats = [ re.compile(r'(?i)(Bearer\s+)(?!\{\{)([A-Za-z0-9\-._~+/]+=*)'), re.compile(r'(?i)((?:api[_-]?key|access[_-]?token|token|secret|password)["\']?\s*[:=]\s*["\']?)' r'(?!\{\{)([^"\'\s&,;{}]+)'), re.compile(r'(?i)(\.set\s*\(\s*["\'][^"\']*(?:api[_-]?key|token|secret|password)[^"\']*["\']\s*,\s*["\'])' r'(?!\{\{)([^"\']+)'), ] def mask(s): if not s: return s for lit in lits: if lit in s: s = s.replace(lit, '****') for p in pats: s = p.sub(lambda m: m.group(1) + '****', s) return s return mask # --------------------------------------------------------------------------- # Discovery / IO # --------------------------------------------------------------------------- def fs_text(s): """Filesystem str (maybe surrogate-escaped under LANG=C) -> clean text.""" try: return os.fsencode(s).decode('utf-8', 'replace') except Exception: return s def load_json(path): with open(path, 'r', encoding='utf-8-sig') as f: return json.load(f, object_pairs_hook=collections.OrderedDict) def find_collections(root): if os.path.isfile(root): return [root] res = [] for d, dirs, files in os.walk(root): dirs[:] = sorted(x for x in dirs if x.lower() != 'env' and not x.startswith('.')) for f in sorted(files): if f.endswith(COLL_SUFFIX): res.append(os.path.join(d, f)) return res def find_env_for(coll_path, root, warn): d = os.path.dirname(os.path.abspath(coll_path)) stop = os.path.abspath(root if os.path.isdir(root) else os.path.dirname(root)) while True: try: names = sorted(os.listdir(d)) except OSError: names = [] for x in names: p = os.path.join(d, x) if x.lower() == 'env' and os.path.isdir(p): files = sorted(f for f in os.listdir(p) if f.lower().endswith('.json')) if files: if len(files) > 1: warn('several env files in %s; using %s' % (fs_text(p), fs_text(files[0]))) return os.path.join(p, files[0]) parent = os.path.dirname(d) if d == stop or parent == d: return None d = parent def load_env(path): data = load_json(path) vals = [] for v in (data.get('values') or []) if isinstance(data, dict) else []: if not isinstance(v, dict) or v.get('enabled') is False or v.get('disabled') is True: continue k = v.get('key') if isinstance(k, str): vals.append((k, v.get('value'))) return vals def output_paths(coll_path, root, outdir): fname = os.path.basename(coll_path) stem = fname[:-len(COLL_SUFFIX)] if fname.endswith(COLL_SUFFIX) else os.path.splitext(fname)[0] src_dir = os.path.dirname(os.path.abspath(coll_path)) if outdir: if os.path.isdir(root): rel = os.path.relpath(src_dir, os.path.abspath(root)) d = os.path.normpath(os.path.join(outdir, rel)) else: d = outdir else: d = src_dir return stem, os.path.join(d, stem + '.tsv'), os.path.join(d, stem + '.scripts.tsv'), \ os.path.join(d, stem + '.scripts') # --------------------------------------------------------------------------- # Collection processing # --------------------------------------------------------------------------- class Node(object): __slots__ = ('label', 'index_path', 'name', 'pre', 'test', 'auth', 'parent') def __init__(self, label, index_path, name, pre, test, auth, parent): self.label = label self.index_path = index_path self.name = name self.pre = pre self.test = test self.auth = auth self.parent = parent def new_stats(): return {'rows': 0, 'errors': 0, 'verifiable': 0, 'unsummarized': 0, 'no_verify': 0, 'heuristic_rows': 0, 'unknown_guards': 0, 'false_guards': 0, 'false_atoms': collections.Counter(), 'cond_items': 0, 'undefined': collections.Counter(), 'runtime': collections.Counter(), 'skipped_param_ops': 0, 'unsum_shapes': collections.Counter()} def walk_items(items, parent, path_names, idx_prefix, out, coll_name): for pos, it in enumerate(items or [], 1): ip = str(pos) if idx_prefix == '0' else idx_prefix + '.' + str(pos) if it is None: continue if isinstance(it, dict) and isinstance(it.get('item'), list): name = it.get('name') if isinstance(it.get('name'), str) else '' names = path_names + [name] node = Node('폴더 ' + ' - '.join(names), ip, name, script_text(it.get('event'), 'prerequest'), script_text(it.get('event'), 'test'), it.get('auth'), parent) walk_items(it['item'], node, names, ip, out, coll_name) else: out.append((it, parent, path_names, ip)) def chain_of(node): c = [] while node is not None: c.append(node) node = node.parent return list(reversed(c)) def digest(text): flat = re.sub(r'\s+', ' ', text).strip() sets = script_static_sets(text) st = ','.join(sets[:20]) + (',+%d' % (len(sets) - 20) if len(sets) > 20 else '') return '%s…\n(lines=%d, chars=%d, sets=%s)' % (flat[:200], text.count('\n') + 1, len(text), st) def process_collection(path, root, opts, log): stats = new_stats() coll = load_json(path) if not isinstance(coll, dict): raise ValueError('collection root is not an object') info = coll.get('info') if isinstance(coll.get('info'), dict) else {} stem, main_p, side_p, js_dir = output_paths(path, root, opts.output) stem_t = fs_text(stem) cname = info.get('name') if isinstance(info.get('name'), str) else stem_t env_path = opts.env if opts.env else find_env_for(path, root, log) env_vals = load_env(env_path) if env_path else [] base = Scope() for k, v in env_vals: base.layers['environment'][k] = ('V', v, 'env') coll_vars = [] for v in coll.get('variable') or []: if isinstance(v, dict) and isinstance(v.get('key'), str) and not v.get('disabled'): base.layers['collection'][v['key']] = ('V', v.get('value'), 'coll') coll_vars.append((v['key'], v.get('value'))) mask = None if opts.mask_secrets: secrets = [v for k, v in env_vals + coll_vars if _SECRET_KEY.search(k)] mask = make_masker(secrets) root_node = Node('컬렉션 ' + cname, '0', cname, script_text(coll.get('event'), 'prerequest'), script_text(coll.get('event'), 'test'), coll.get('auth'), None) reqs = [] try: walk_items(coll.get('item'), root_node, [], '0', reqs, cname) except RecursionError: raise ValueError('folder nesting too deep') scope_cache = {} def scope_for(node): sc = scope_cache.get(node.index_path) if sc is None: sc = base.copy() if node.parent is None else scope_for(node.parent).copy() apply_script(node.pre, sc, opts, stats) scope_cache[node.index_path] = sc return sc seg_cache = {} def segment(node, kind): key = (node.index_path, kind) if key not in seg_cache: text = node.pre if kind == 'prerequest' else node.test tag = '상위 pre' if kind == 'prerequest' else '상속 test' if not text.strip(): seg_cache[key] = None elif len(text) <= opts.inline_limit: seg_cache[key] = '[%s: %s]\n%s' % (tag, node.label, text) else: seg_cache[key] = '[%s: %s → %s.scripts.tsv]\n%s' % (tag, node.label, stem_t, digest(text)) return seg_cache[key] rows = [] side_nodes = collections.OrderedDict() counters = collections.Counter() for it, parent, path_names, ip in reqs: counters[parent.index_path] += 1 no = counters[parent.index_path] name = it.get('name') if isinstance(it, dict) and isinstance(it.get('name'), str) else '' lv2 = ' - '.join(path_names) try: if not isinstance(it, dict): raise TypeError('item is not an object') chain = chain_of(parent) for nd in chain: if nd.pre.strip() or nd.test.strip(): side_nodes[nd.index_path] = nd row, extra = build_row(it, chain, scope_for(parent), opts, stats, mask, cname, lv2, name, no, segment) if extra: side_nodes['req:' + ip] = Node('요청 ' + (lv2 + ' - ' if lv2 else '') + name, ip, name, extra[0], extra[1], None, parent) except Exception as ex: # per-row fault isolation stats['errors'] += 1 msg = '[ERROR] %s: %s' % (type(ex).__name__, ex) row = [cname, lv2, name, '', name, str(no), msg, msg, '', '', '', '', '', ''] row = [fit_cell(c, opts.max_cell, None) for c in row] stats['rows'] += 1 rows.append(row) # write main TSV d = os.path.dirname(main_p) if d and not os.path.isdir(d): os.makedirs(d, exist_ok=True) with open(main_p, 'w', encoding='utf-8-sig', newline='') as f: w = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') w.writerow(MAIN_HEADER) for r in rows: r = (list(r) + [''] * 14)[:14] w.writerow(r) # sidecar + .js if not os.path.isdir(js_dir): os.makedirs(js_dir, exist_ok=True) for fn in os.listdir(js_dir): if fn.endswith('.js'): os.remove(os.path.join(js_dir, fn)) js_rel = stem_t + '.scripts' all_nodes = [root_node] + [n for k, n in side_nodes.items() if k != '0'] with open(side_p, 'w', encoding='utf-8-sig', newline='') as f: w = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_MINIMAL, lineterminator='\r\n') w.writerow(SIDE_HEADER) for nd in all_nodes: for kind, text in (('prerequest', nd.pre), ('test', nd.test)): if not text or not text.strip(): continue t = mask(text) if mask is not None else text fname = '%s.%s.js' % (nd.index_path, kind) with open(os.path.join(js_dir, fname), 'wb') as jf: jf.write(t.encode('utf-8', 'surrogatepass')) parts = split_parts(escape_cell(t), opts.max_cell) for k, p in enumerate(parts, 1): w.writerow([escape_cell(nd.label), nd.index_path, kind, '%d/%d' % (k, len(parts)), p, str(len(text)), js_rel + '/' + fname]) return stats, env_path, main_p def build_row(it, chain, prefix_scope, opts, stats, mask, cname, lv2, name, no, segment): req = normalize_request(it) events = it.get('event') pre = script_text(events, 'prerequest') test = script_text(events, 'test') scope = prefix_scope.copy() apply_script(pre, scope, opts, stats) unresolved = {} # URL raw, base_url, qitems, h = url_parts(req['url']) qitems = apply_ops(qitems, scope.params, 'query') qs = rebuild_query(qitems) url_orig = base_url + ('?' + qs if qs else '') + ('#' + h if h is not None else '') url_res = resolve(url_orig, scope, unresolved) # Method m_raw = req['method'] m_res = resolve(m_raw, scope, unresolved) method_col = m_res if m_res == m_raw else '%s (%s)' % (m_res, m_raw) # Headers hdr_items = [dict(x) for x in req['header'] if isinstance(x, dict)] hdr_items = apply_ops(hdr_items, scope.params, 'headers') h_lines = [kv_line(x, ': ') for x in hdr_items if not x.get('disabled')] auth, inherited = effective_auth(req['auth'], chain) if auth: h_lines += auth_lines(auth, inherited) h_orig = '\n'.join(h_lines) h_res = resolve(h_orig, scope, unresolved) # Body b_orig, _sk = body_text(req['body'], scope.params) b_res = resolve(b_orig, scope, unresolved) body_col = b_res if b_res == b_orig else b_res + '\n[원본 body]\n' + b_orig for k, why in unresolved.items(): stats[why][k] += 1 td = '%s %s' % (m_res, url_res) if h_res: td += '\n[Headers]\n' + h_res if b_res: td += '\n[Body]\n' + b_res if scope.heur: td += '\n[heuristic]' stats['heuristic_rows'] += 1 scenario = pre if pre.strip() else '%s %s' % (m_res, url_res) test_case = req['description'] if req['description'].strip() else name anc_tests = [nd.test for nd in chain if nd.test.strip()] verifiable = bool(test.strip()) or bool(anc_tests) or \ any(script_sets_test(nd.pre) for nd in chain) or script_sets_test(pre) expected, unsum, ncond, unmatched = build_expected(test, anc_tests, scope, verifiable, opts, stats) if not verifiable: stats['no_verify'] += 1 else: stats['verifiable'] += 1 if unsum: stats['unsummarized'] += 1 for u in unmatched: stats['unsum_shapes'][shape_of(u)] += 1 stats['cond_items'] += ncond upper = '\n'.join(s for s in (segment(nd, 'prerequest') for nd in chain) if s) tsegs = [test if test.strip() else NO_TEST] + [s for s in (segment(nd, 'test') for nd in chain) if s] test_col = '\n'.join(tsegs) row = [cname, lv2, name, scenario, test_case, str(no), td, expected, method_col, raw, h_res, body_col, upper, test_col] row = [fit_cell(c, opts.max_cell, mask) for c in row] extra = None if len(escape_cell(pre)) > opts.max_cell or len(escape_cell(test)) > opts.max_cell: extra = (pre, test) return row, extra # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def rewrap_streams(): for name in ('stdout', 'stderr'): s = getattr(sys, name) buf = getattr(s, 'buffer', None) if buf is None: continue try: s.flush() except Exception: pass enc = getattr(s, 'encoding', None) or 'utf-8' setattr(sys, name, io.TextIOWrapper(buf, encoding=enc, errors='backslashreplace', line_buffering=True)) def parse_args(argv): p = argparse.ArgumentParser( prog='postman2tsv.py', description='Convert Postman v2.1 collections to test-scenario TSV files (utf-8-sig). ' 'Set PYTHONIOENCODING=utf-8 for readable console output under LANG=C.') p.add_argument('input', help='directory (searched recursively for *.postman_collection.json) or file') p.add_argument('--env', help='environment file for all collections (default: nearest env/ dir)') p.add_argument('-o', '--output', help='output directory (mirrors the input tree)') p.add_argument('--no-script-params', action='store_true', help='do not add params injected by scripts (urlencoded/query/headers .add)') p.add_argument('--mask-secrets', action='store_true', help='mask tokens/api keys in all outputs (main, sidecar, .js)') p.add_argument('--max-cell', type=int, default=30000, help='max chars per main TSV cell (default 30000)') p.add_argument('--inline-limit', type=int, default=2000, help='ancestor scripts up to N chars are inlined, longer ones digested (default 2000)') p.add_argument('--no-guard-eval', action='store_true', help='treat every if/switch guard as Unknown') a = p.parse_args(argv) if a.max_cell < 100: p.error('--max-cell must be >= 100') return a def print_stats(rel, env_path, st, out_p): w = sys.stderr.write def top(c): return ', '.join('%s(%d)' % (k, v) for k, v in c.most_common(5)) or '-' ver = st['verifiable'] pct = (100.0 * st['unsummarized'] / ver) if ver else 0.0 w('[postman2tsv] %s -> %s\n' % (fs_text(rel), fs_text(out_p))) w(' env=%s rows=%d errors=%d\n' % (fs_text(env_path) if env_path else 'none', st['rows'], st['errors'])) w(' verifiable=%d unsummarized=%d (%.1f%%) no-verification=%d conditional_items=%d\n' % (ver, st['unsummarized'], pct, st['no_verify'], st['cond_items'])) w(' heuristic_rows=%d unknown_guards=%d false_guards=%d top_false_atoms: %s\n' % (st['heuristic_rows'], st['unknown_guards'], st['false_guards'], top(st['false_atoms']))) w(' unresolved: undefined=%d [%s] runtime=%d [%s]\n' % (len(st['undefined']), top(st['undefined']), len(st['runtime']), top(st['runtime']))) w(' skipped_param_ops=%d top_unsummarized_shapes: %s\n' % (st['skipped_param_ops'], top(st['unsum_shapes']))) def main(argv=None): rewrap_streams() opts = parse_args(argv) if not os.path.exists(opts.input): sys.stderr.write('input not found: %s\n' % fs_text(opts.input)) return 2 colls = find_collections(opts.input) if not colls: sys.stderr.write('no *%s found under %s\n' % (COLL_SUFFIX, fs_text(opts.input))) return 2 def log(msg): sys.stderr.write('[warn] %s\n' % msg) failed = 0 for path in colls: rel = os.path.relpath(path, opts.input) if os.path.isdir(opts.input) else os.path.basename(path) try: st, env_path, out_p = process_collection(path, opts.input, opts, log) print_stats(rel, env_path, st, out_p) except Exception as ex: # per-collection fault isolation failed += 1 sys.stderr.write('[error] %s: %s: %s\n' % (fs_text(rel), type(ex).__name__, ex)) return 1 if failed else 0 if __name__ == '__main__': sys.exit(main())