Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 42 additions & 6 deletions test/ttpsuite/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,65 @@

Python TTP 0.10.1's own test suite (`test/pytest` in [dmulyalin/ttp](https://github.com/dmulyalin/ttp)), replayed through gottp. This is the compliance measure for the baseline (#60).

Current result (gottp `cbc344c`):

```
go test ./test/ttpsuite -v -run TestTTPSuite | grep 'suite:'
go test ./test/ttpsuite -v | grep -E 'suite:|repros:|parity:'
```

Current result (gottp `718c77b`):

```
TTP 0.10.1 suite: pass 22 / skipped-by-issue 174 / design 4 of 200
gottp repros: pass 1 / skipped-by-issue 9 / design 0 of 10
source-map parity: same 199 / diverge 11 of 210
```

The Go test needs no Python, so it runs in plain `go test ./...` and in CI.
The Go tests need no Python, so they run in plain `go test ./...` and in CI. There are three:

- `TestTTPSuite`: TTP's own 200 cases against TTP 0.10.1's results (below).
- `TestGottpRepros`: gottp bug repros against TTP 0.10.1's results ([gottp repros](#gottp-repros)).
- `TestSourceMapParity`: every case from both, parsed with source maps off and on, must give the same data ([Source-map parity](#source-map-parity)).

## How it works

- `testdata/cases/<module>.json` holds 200 cases, one file per TTP test module. Each case has the template, the inputs, the TTP test it came from (`source`) and the result Python TTP 0.10.1 returned (`expected`).
- `ttpsuite_test.go` runs each case as a subtest through gottp's Python-style API (`NewParser`, `AddTemplate`, `AddInput`, `Parse`, `Result`) with the working directory set to `testdata/pytest`, so the templates' `./assets/...` paths resolve. The result is compared **strictly**: there is no list-unwrapping normalization (unlike `test/comparison`), because that normalization hides #62.
- `known_failures.json` lists every case that doesn't match yet. `issue` is the issue its first strict difference belongs to, `also` lists issues the case hits after that, and `reason` is one line. A reason starting with `design:` marks a deliberate difference.
- The test fails when a case differs and isn't listed, when a listed case passes ("remove it from known_failures.json"), and when the table names a case that doesn't exist. So the table can't go stale: fixing an issue makes its cases fail until their entries are removed.
- `TTPSUITE_REPORT=/tmp/report.json go test ./test/ttpsuite` writes every case's outcome, first difference and gottp result, for triage.
- `TTPSUITE_REPORT=/tmp/report.json go test ./test/ttpsuite` writes every case's outcome, first difference and gottp result, for triage (`TTPSUITE_REPROS_REPORT` does the same for the repros).

## gottp repros

`testdata/gottp-repros/` holds minimal repros of gottp bugs: `NAME.ttp` (template), `NAME.txt` (the `Default_Input` data) and `NAME.expected.json` (Python TTP 0.10.1's result, written by `record.py expect`). The case name is `gottp-repros/NAME`; `NAME` starts with the issue number. `TestGottpRepros` runs them like the suite cases, through the Python-style API, and they share `known_failures.json`, so each one turns on when its issue is fixed. To add one, write the `.ttp` and `.txt` and run `record.py expect`.

| Repro | Issue |
|---|---|
| `issue28_parent_start_line_without_variables` | #28 |
| `issue29_joinmatches_on_start_line` | #29 |
| `issue30_indented_line_matches_any_indentation` | #30 |
| `issue31_ignore_vars_name` | #31 |
| `issue32_one_line_fills_several_template_lines` | #32 |
| `issue33_trailing_ignore_with_trailing_whitespace` | #33 |
| `issue34_split_joinmatches` | #34 |
| `issue35_strip_characters_argument` | #35 |
| `issue36_unknown_function_falls_back_to_str_method` | #36 |
| `sourcemap_void_group` | passes; covers `void` for source-map parity (#108) |

## Source-map parity

`CompiledTemplate.Parse` runs `Runtime.Parse` when source maps are off, and a separate copy of the orchestration (`Runtime.ParseWithSourceMap` and `parseGroupWithSourceMap`) when `ParseOptions{EnableSourceMap: true}`. The editor always turns source maps on. `TestSourceMapParity` parses every case (suite and repros) through `CompiledTemplate.ParseWithValidation` both ways and requires the same data, or the same error. The source map itself isn't compared, and it doesn't matter whether the data matches TTP.

`sourcemap_divergences.json` lists the cases that differ, with the same rules as `known_failures.json`: an unlisted divergence, a listed case at parity and a stale entry all fail the test. `TTPSUITE_SOURCEMAP_REPORT=/tmp/sm.json` writes both results of every diverging case.

| Issue | Cases | Title |
|---|---|---|
| #105 | 5 | Source map: a group without input= parses only Default_Input (other inputs give an empty result) |
| #106 | 4 | Source map: group errors lose the "failed to parse group <name>" context |
| #107 | 1 | Source map: the ignore("<vars name>") empty-record special case is missing, so the group is dropped |
| #108 | 1 | Source map: void groups are not dropped from the results |

## Regenerating the data

Never edit `testdata/cases/` by hand. `record.py` writes it from Python TTP, pinned in `../comparison/requirements.txt`:
Never edit `testdata/cases/` or the `*.expected.json` files by hand. `record.py` writes them from Python TTP, pinned in `../comparison/requirements.txt`. It needs every package in `requirements.txt` (it exits if one is missing): without the optional formatter and validation packages TTP returns different results for some cases.

```
python3 -m venv /tmp/ttpvenv && /tmp/ttpvenv/bin/pip install -r test/ttpsuite/requirements.txt
Expand Down
36 changes: 36 additions & 0 deletions test/ttpsuite/known_failures.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,42 @@
{
"_comment": "TTP 0.10.1 suite cases that don't match yet. issue = the issue the first strict difference belongs to; also = issues hit after it. A reason starting with 'design:' marks a deliberate difference. A case listed here that passes fails the test, so remove it when its issue is fixed.",
"cases": {
"gottp-repros/issue28_parent_start_line_without_variables": {
"issue": 28,
"reason": "parent group whose _start_ line has no variables drops its child groups"
},
"gottp-repros/issue29_joinmatches_on_start_line": {
"issue": 29,
"reason": "joinmatches on a _start_ line merges consecutive records into one"
},
"gottp-repros/issue30_indented_line_matches_any_indentation": {
"issue": 30,
"reason": "indented template line matches data at any indentation"
},
"gottp-repros/issue31_ignore_vars_name": {
"issue": 31,
"reason": "ignore(\"<vars name>\") empties the group"
},
"gottp-repros/issue32_one_line_fills_several_template_lines": {
"issue": 32,
"reason": "one data line fills variables from several template lines"
},
"gottp-repros/issue33_trailing_ignore_with_trailing_whitespace": {
"issue": 33,
"reason": "trailing {{ ignore(\".*\") }} fails when the data line has trailing whitespace"
},
"gottp-repros/issue34_split_joinmatches": {
"issue": 34,
"reason": "split() | joinmatches returns a joined string instead of a merged list"
},
"gottp-repros/issue35_strip_characters_argument": {
"issue": 35,
"reason": "strip(\"()\") ignores its characters argument"
},
"gottp-repros/issue36_unknown_function_falls_back_to_str_method": {
"issue": 36,
"reason": "rstrip(\",\") (str method fallback) is silently skipped"
},
"test_N2G_formatter/test_n2g_formatter": {
"issue": 80,
"reason": "format=\"n2g\" is not supported"
Expand Down
56 changes: 55 additions & 1 deletion test/ttpsuite/record.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
record.py expect [--check]
Re-run every case in testdata/cases/ through the installed Python TTP
(cwd = testdata/pytest, so relative asset paths resolve) and rewrite each
case's "expected". With --check, write nothing and exit 1 if any
case's "expected". Also re-run every gottp bug repro in
testdata/gottp-repros/ (NAME.ttp + NAME.txt) and rewrite its
NAME.expected.json. With --check, write nothing and exit 1 if any
expectation would change. Needs the TTP version pinned in
../comparison/requirements.txt.

Expand Down Expand Up @@ -41,6 +43,7 @@
TESTDATA = os.path.join(HERE, "testdata")
CASES_DIR = os.path.join(TESTDATA, "cases")
PYTEST_DIR = os.path.join(TESTDATA, "pytest")
REPROS_DIR = os.path.join(TESTDATA, "gottp-repros")
REQUIREMENTS = os.path.join(HERE, "..", "comparison", "requirements.txt")

INIT_KW = ["data", "template", "log_level", "log_file", "base_path", "vars",
Expand All @@ -61,12 +64,22 @@ def pinned_ttp_version():
sys.exit(f"no ttp== pin in {REQUIREMENTS}")


# Optional TTP dependencies from requirements.txt. Without them TTP still
# runs but some cases return different results, so "expect" would rewrite
# their expectations.
OPTIONAL_DEPS = ["cerberus", "deepdiff", "jinja2", "N2G", "tabulate", "yangson", "yaml"]


def require_pinned_ttp():
import importlib.util
import ttp # noqa: F401
from importlib.metadata import version
want, got = pinned_ttp_version(), version("ttp")
if want != got:
sys.exit(f"installed ttp {got}, but {REQUIREMENTS} pins {want}")
missing = [m for m in OPTIONAL_DEPS if importlib.util.find_spec(m) is None]
if missing:
sys.exit(f"missing {', '.join(missing)}: pip install -r {os.path.join(HERE, 'requirements.txt')}")
return got


Expand Down Expand Up @@ -233,13 +246,54 @@ def cmd_expect(args):
dirty = True
if dirty and not args.check:
_write_cases(path, cases)
rtotal, rchanged = expect_repros(args.check)
total += rtotal
changed += rchanged
print(f"ttp {ver}: {total} cases, {len(changed)} expectation(s) changed")
for name in changed:
print(" changed:", name)
if args.check and changed:
sys.exit(1)


def repro_case(stem):
"""Build the case for testdata/gottp-repros/STEM.ttp + STEM.txt, in the
same shape as testdata/cases/*.json (ttpsuite_test.go loadRepros)."""
with open(os.path.join(REPROS_DIR, stem + ".ttp"), encoding="utf-8") as f:
tmpl = f.read()
with open(os.path.join(REPROS_DIR, stem + ".txt"), encoding="utf-8") as f:
data = f.read()
return {"name": "gottp-repros/" + stem, "template": tmpl,
"inputs": [{"name": "Default_Input", "data": data}]}


def expect_repros(check):
"""Re-record NAME.expected.json for every NAME.ttp in testdata/gottp-repros.
Returns (number of repros, names whose expectation changed)."""
stems = sorted(fn[:-4] for fn in os.listdir(REPROS_DIR) if fn.endswith(".ttp"))
changed = []
for stem in stems:
case = repro_case(stem)
got = run_ttp(case)
path = os.path.join(REPROS_DIR, stem + ".expected.json")
old = None
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
old = json.load(f)
if old != got:
changed.append(case["name"])
if not check:
with open(path, "w", encoding="utf-8") as f:
json.dump(got, f, indent=1, ensure_ascii=False)
f.write("\n")
for fn in sorted(os.listdir(REPROS_DIR)):
if fn.endswith(".expected.json") and fn[:-len(".expected.json")] not in stems:
changed.append("gottp-repros/" + fn + " (no .ttp)")
if not check:
os.remove(os.path.join(REPROS_DIR, fn))
return len(stems), changed


def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
Expand Down
49 changes: 49 additions & 0 deletions test/ttpsuite/sourcemap_divergences.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
{
"_comment": "Cases whose parsed data changes when ParseOptions{EnableSourceMap: true} is set (Runtime.ParseWithSourceMap instead of Runtime.Parse). issue = the root cause of the first difference. A case listed here that reaches parity fails TestSourceMapParity, so remove it when its issue is fixed.",
"cases": {
"gottp-repros/issue31_ignore_vars_name": {
"issue": 107,
"reason": "ignore(\"<vars name>\") empty-record special case is missing: g is dropped instead of {}"
},
"gottp-repros/sourcemap_void_group": {
"issue": 108,
"reason": "void group is kept in the results"
},
"test_answers_and_docs/test_docs_ttp_dictionary_usage_example": {
"issue": 106,
"reason": "both paths fail on the macro; the source-map error lacks \"failed to parse group <name>:\""
},
"test_extend_tag/test_extend_tag_from_file_with_vars_inputs_filter": {
"issue": 105,
"reason": "group without input= parses only Default_Input; the case's inputs have other names, so the result is empty"
},
"test_group_functions/test_group_macro_chaining": {
"issue": 106,
"reason": "both paths fail on the macro; the source-map error lacks \"failed to parse group <name>:\""
},
"test_group_functions/test_group_macro_chaining_returns_dictionary": {
"issue": 106,
"reason": "both paths fail on the macro; the source-map error lacks \"failed to parse group <name>:\""
},
"test_inputs/test_input_to_groups_mapping": {
"issue": 105,
"reason": "group without input= parses only Default_Input; the case's inputs have other names, so the result is empty"
},
"test_misc/test_inner_group_strange_parsing_results": {
"issue": 106,
"reason": "both paths fail on the macro; the source-map error lacks \"failed to parse group <name>:\""
},
"test_output_functions/test_global_output_deepdiff_with_var_before": {
"issue": 105,
"reason": "group without input= parses only Default_Input; the case's inputs have other names, so the result is empty"
},
"test_output_functions/test_group_specific_output_deepdiff_with_var_before": {
"issue": 105,
"reason": "group without input= parses only Default_Input; the case's inputs have other names, so the result is empty"
},
"test_output_functions/test_group_specific_output_deepdiff_with_var_before_with_add_field": {
"issue": 105,
"reason": "group without input= parses only Default_Input; the case's inputs have other names, so the result is empty"
}
}
}
116 changes: 116 additions & 0 deletions test/ttpsuite/sourcemap_parity_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package ttpsuite

import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"

"github.com/roc-ops/gottp"
)

const divergencesFile = "sourcemap_divergences.json"

// parseCompiled parses one case through CompiledTemplate.ParseWithValidation,
// with source maps off or on, and returns the data after a JSON round trip.
// With source maps off it runs Runtime.Parse; with them on it runs
// Runtime.ParseWithSourceMap, the path the editor uses.
func parseCompiled(c ttpCase, sourceMap bool) (interface{}, error) {
ct, err := gottp.CompileTemplate(c.Template)
if err != nil {
return nil, fmt.Errorf("CompileTemplate: %w", err)
}
inputs := gottp.Inputs{}
for _, in := range c.Inputs {
inputs[in.Name] = in.Data
}
var opts *gottp.ParseOptions
if sourceMap {
opts = &gottp.ParseOptions{EnableSourceMap: true}
}
res, err := ct.ParseWithValidation(inputs, nil, opts)
if err != nil {
return nil, fmt.Errorf("ParseWithValidation: %w", err)
}
if sourceMap && res.SourceMap == nil {
return nil, fmt.Errorf("EnableSourceMap: true returned no source map")
}
return jsonRoundTrip(res.Data)
}

// TestSourceMapParity checks that turning source maps on doesn't change the
// parsed data, for every case in testdata/cases and testdata/gottp-repros.
// The source map itself isn't compared. This is independent of whether the
// data matches TTP: a case can fail TestTTPSuite and still be at parity.
//
// sourcemap_divergences.json lists the cases whose data differs, each with
// the issue that tracks the root cause. As with known_failures.json, a listed
// case that reaches parity fails the test until its entry is removed.
func TestSourceMapParity(t *testing.T) {
cases := append(loadCases(t), loadRepros(t)...)
known := loadKnownFailures(t, divergencesFile)
checkNoStaleEntries(t, divergencesFile, known, cases, func(string) bool { return true })
abs := enterPytestDir(t)

// TTPSUITE_SOURCEMAP_REPORT=file writes every diverging case with both
// results, for triage.
type reportRow struct {
Name string `json:"name"`
Problem string `json:"problem"`
Known string `json:"known,omitempty"`
Off interface{} `json:"off"`
On interface{} `json:"on"`
}
var report []reportRow

var same, diverge int
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
for k, v := range c.Env {
t.Setenv(k, filepath.Join(abs, v))
}
off, errOff := runWithTimeout(func() (interface{}, error) { return parseCompiled(c, false) })
on, errOn := runWithTimeout(func() (interface{}, error) { return parseCompiled(c, true) })
problem := parityDiff(off, errOff, on, errOn)
k, isKnown := known[c.Name]
if problem != "" {
diverge++
report = append(report, reportRow{Name: c.Name, Problem: problem, Known: k.describe(), Off: off, On: on})
}
switch {
case problem == "" && isKnown:
t.Errorf("%s is now at source-map parity: remove it from %s (was: %s)", c.Name, divergencesFile, k.describe())
case problem == "":
same++
case isKnown:
t.Skipf("%s; first difference (off vs on): %s", k.describe(), truncate(problem, 300))
default:
t.Errorf("%s: source maps on changes the result and the case is not in %s\nfirst difference (off vs on): %s\noff: %s\non: %s",
c.Name, divergencesFile, problem, truncate(jsonString(off), 1500), truncate(jsonString(on), 1500))
}
})
}
if path := os.Getenv("TTPSUITE_SOURCEMAP_REPORT"); path != "" {
b, _ := json.MarshalIndent(report, "", " ")
if err := os.WriteFile(path, b, 0o644); err != nil {
t.Errorf("TTPSUITE_SOURCEMAP_REPORT: %v", err)
}
}
t.Logf("source-map parity: same %d / diverge %d of %d", same, diverge, len(cases))
}

// parityDiff describes the first difference between the source-map-off and
// source-map-on outcomes, or returns "" if they match (equal data, or the
// same error).
func parityDiff(off interface{}, errOff error, on interface{}, errOn error) string {
switch {
case errOff != nil || errOn != nil:
if errOff != nil && errOn != nil && errOff.Error() == errOn.Error() {
return ""
}
return fmt.Sprintf("off error: %v; on error: %v", errOff, errOn)
default:
return firstDiff(off, on, "$")
}
}
Loading
Loading