spark-test commented on code in PR #60362:
URL: https://github.com/apache/spark/pull/60362#discussion_r4546691103


##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -228,8 +231,41 @@ def write_test_file(filepath, header, cases):
         case_lines.append(_CASE_END)
         blocks.append("\n".join(case_lines))
 
+    return "\n\n\n".join(blocks) + "\n"
+
+
+def write_test_file(filepath, header, cases):
+    """Write *header* and *cases* back into ``.test`` file format."""
     with open(filepath, "w") as f:
-        f.write("\n\n\n".join(blocks) + "\n")
+        f.write(serialize_test_file(header, cases))
+
+
+_GOLDEN_DIFF_BEGIN = "=== BEGIN GOLDEN DIFF ==="
+_GOLDEN_DIFF_END = "=== END GOLDEN DIFF ==="
+_GOLDEN_REL_DIR = "python/pyspark/sql/tests/df_golden"
+
+
+def _golden_diff(test_file, new_content):
+    """Return a repo-relative unified diff for use with ``git apply``."""
+    with open(test_file) as f:
+        old_content = f.read()
+    rel = "{}/{}".format(_GOLDEN_REL_DIR, os.path.basename(test_file))
+    lines = difflib.unified_diff(
+        old_content.splitlines(keepends=True),

Review Comment:
   **Non-blocking (P2):** `str.splitlines()` also ends a line at `\x0b`, 
`\x0c`, `\x1c`, `\x1d`, `\x1e`, `\x85`, U+2028 and U+2029, but 
`parse_test_file`, `serialize_test_file` and git break lines only at `\n`. When 
one of these characters sits on a changed or context line of a hunk, difflib 
sees one file line as two, and the join below appends `\ No newline at end of 
file` to the first half. The printed block then misstates the file and is not 
an applicable patch. These characters can reach a golden: `_format_value` 
rejects only tab and newline in string results, and plan text shows string 
literals raw.
   
   In a scratch repro, a golden written by `write_test_file` had a result row 
change from `'a\x0cb'` to `'a\x0cc'`. `git apply --check` rejected the printed 
patch with `patch does not apply`, and it did the same for each of the other 
seven characters. The same edit without the character, or with `\x1f`, applied 
cleanly, and the character on a line outside the hunk only shifted the hunk 
header. Splitting both texts on `'\n'` only, for example with 
`io.StringIO(text, newline='\n').readlines()` (which needs `import io`), made 
every patch apply and reproduce the regenerated file exactly. `\r` is the only 
other `splitlines` boundary, and the `.test` format already cannot hold one, 
because `parse_test_file` reads files with universal newlines.
   
   Verdicts and regeneration are unaffected, and `group_by.test` contains none 
of these characters today, so the problem stays hidden until a case renders 
one; `test_golden_diff` covers only ASCII text.
   
   **Verification:**
   - **Regression:** For each of \x0b, \x0c, \x1c, \x1d, \x1e, \x85, U+2028 and 
U+2029, a diff-helper case that puts the character on a changed line and 
another that puts it on an unchanged line next to a change yield the unified 
diff computed over '\n'-delimited lines: one diff line per file line, correct 
hunk line numbers, and no no-newline marker inside the hunk.
   - **Behavior:** Applying the helper's diff for such text with git apply from 
the repository root succeeds and leaves the golden file equal to the 
regenerated text.
   - **Compatibility:** The existing diff-helper cases (an unchanged file, a 
one-line change, and a file without a final newline) still produce exactly 
their current output.



##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -693,23 +729,28 @@ def run_golden_test(test_case, spark, test_file):
     regenerate = os.environ.get("SPARK_GENERATE_GOLDEN_FILES") is not None
     base_dir = os.path.dirname(test_file)
 
-    header, cases = parse_test_file(test_file, require_terminated=not 
regenerate)
-    _validate_test_file(test_file, header, cases, regenerate)
+    # Parse leniently to generate a diff for incomplete goldens; verify 
strictly below.
+    header, cases = parse_test_file(test_file)
+    _validate_test_file(test_file, header, cases, regenerate=True)
 
     # Golden files are generated with ANSI mode on, matching the SQL golden
     # tests.  The session is discarded after the file, so nothing to restore.
     spark.conf.set("spark.sql.ansi.enabled", "true")
 
-    regenerated_cases = []
-    for case in cases:
-        actual = compute_case_outputs(spark, case, base_dir)
-        if regenerate:
-            regenerated_cases.append(_regenerate_case(case, actual))
-        else:
-            _compare_case(test_case, case, actual)
+    # Capture every case once so a mismatch does not leave the diff incomplete.
+    actuals = [compute_case_outputs(spark, case, base_dir) for case in cases]
+    regenerated_cases = [_regenerate_case(case, actual) for case, actual in 
zip(cases, actuals)]
+    diff = _golden_diff(test_file, serialize_test_file(header, 
regenerated_cases))
+    if diff:
+        _print_golden_diff(diff)
 
     if regenerate:
         write_test_file(test_file, header, regenerated_cases)
+    else:
+        header, cases = parse_test_file(test_file, require_terminated=True)

Review Comment:
   **Nit (P3):** This strict re-parse and the validation on the next line are 
what still make verify mode reject an unterminated golden, unknown sections, a 
case with no expected sections, and conflicting or unpaired result sections, 
but no test sends such a golden through `run_golden_test`. Every verify-mode 
fixture in `DFGoldenRunnerTests` is written by `write_test_file`, so it is 
terminated and has an expected section. The one case without expected sections 
runs only in regeneration mode, and the framework tests call `parse_test_file` 
and `_validate_test_file` directly.
   
   By the review's reading, deleting these two lines would make verify mode 
accept all of those malformed goldens while every test still passes, and 
weakening either line alone would drop part of that protection just as quietly. 
Moving the strict checks back before the cases run would also pass every test, 
while dropping the diff that the lenient first pass exists to print for 
incomplete goldens.
   
   **Verification:**
   - **Regression:** A verify-mode run of a golden containing a case without 
expected sections shows the diff markers on stderr, fails with the 
no-expected-sections validation message, leaves the file byte-for-byte 
unchanged, and records exactly one execution per case. The test fails if verify 
mode skips strict validation or validates before running the cases.
   - **Regression:** A verify-mode run of a golden whose last case lacks its 
terminator shows the diff markers, fails with the unterminated-file message, 
leaves the file unchanged, and records exactly one execution per case. The test 
fails if verify mode skips the strict re-parse or performs it before running 
the cases.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to