spark-test commented on code in PR #57691:
URL: https://github.com/apache/spark/pull/57691#discussion_r4508531073
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -744,3 +752,232 @@ def _compare_case(test_case, case, actual):
got.strip("\n"),
"[{}] mismatch in `{}`".format(name, key),
)
+
+
+def is_generating_golden():
+ """Whether this run regenerates the golden files instead of checking
them."""
+ return os.environ.get("SPARK_GENERATE_GOLDEN_FILES") is not None
+
+
+def golden_file_for_input(module_file):
+ """
+ Return the golden file path for the test module at *module_file*.
+
+ Mirrors ``SQLQueryTestSuite.resultFileForInputFile``: the ``inputs``
+ directory becomes ``results`` and ``.out`` is appended, so a module and its
+ golden file are named alike and there is nothing to keep in sync by hand.
+ """
+ inputs_dir, filename = os.path.split(os.path.abspath(module_file))
+ base_dir, dir_name = os.path.split(inputs_dir)
+ assert dir_name == _INPUTS_DIR, (
+ "{}: a golden test module must live in the `{}` directory, next to the
"
+ "`{}` directory holding the golden files".format(module_file,
_INPUTS_DIR, _RESULTS_DIR)
+ )
+ return os.path.join(base_dir, _RESULTS_DIR, filename + ".out")
+
+
+def assert_cases_in_sync(test_file, declared, golden):
+ """
+ Assert that the golden file describes exactly the declared cases, in order.
+
+ Each test asserts against its own block, so a case the golden file has
never
+ heard of (or one it still remembers after the method was deleted or
renamed)
+ would otherwise go unnoticed.
+ """
+ if declared == golden:
+ return
+ missing = [name for name in declared if name not in golden]
+ extra = [name for name in golden if name not in declared]
+ if missing:
+ detail = "cases with no block in the golden file: " + ",
".join(missing)
+ elif extra:
+ detail = "blocks in the golden file with no case method: " + ",
".join(extra)
+ else:
+ detail = "the golden file lists the cases in a different order"
+ raise AssertionError(
+ "{}: golden file is out of sync with the test class ({}); "
+ "regenerate the golden files".format(test_file, detail)
+ )
+
+
+# ---------------------------------------------------------------------------
+# Test class integration
+# ---------------------------------------------------------------------------
+
+
+class DFGoldenTestMixin:
+ """
+ Mixin turning a class of case methods into DataFrame golden file tests.
+
+ Mix into a session-providing test case, listing this class first so its
+ ``setUpClass`` runs once the session exists::
+
+ class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):
+ def _test_group_by_count(self, spark):
+ return
spark.table("testData").groupBy(col("a")).agg(count(col("b")))
+
+ Every ``_test_<case>`` method declares one case and returns the DataFrame
+ under test; a ``test_<case>`` method is registered for each, so cases run,
+ report and can be selected individually like any other unittest test. The
+ golden file is derived from the test module (see
+ :func:`golden_file_for_input`), so there is nothing to declare.
+
+ The cases of a class share one Spark Connect session (``newSession()`` off
+ the session the test class provides, the Connect counterpart of
+ ``SQLQueryTestSuite``'s per-file ``newSession()``), prepared once by
+ :meth:`setup_session`. State created there -- temp views, UDFs, session
+ confs -- is discarded with the session and cannot leak into other classes.
+ """
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ # Only the cases this class declares: an inherited one already has its
+ # test method on the class that declares it.
+ for attr, method in list(vars(cls).items()):
+ if attr.startswith(_CASE_METHOD_PREFIX) and
inspect.isfunction(method):
+ cls._register_case_test(attr[len(_CASE_METHOD_PREFIX) :],
method)
+
+ @classmethod
+ def _register_case_test(cls, name, case_method):
+ """Add the unittest method that runs the case *name*."""
+
+ def test_case(self):
+ self._run_golden_case(name)
+
+ test_case.__name__ = "test_" + name
+ # Carry the case method's docstring over so verbose runs describe the
case.
+ test_case.__doc__ = case_method.__doc__
+ setattr(cls, test_case.__name__, test_case)
+
+ @classmethod
+ def case_names(cls):
+ """The declared case names, including inherited ones, sorted by
name."""
+ return [
+ name[len(_CASE_METHOD_PREFIX) :]
+ for name, _ in inspect.getmembers(cls,
predicate=inspect.isfunction)
+ if name.startswith(_CASE_METHOD_PREFIX)
+ ]
+
+ @classmethod
+ def golden_file_path(cls):
+ """Absolute path of this class's golden file, derived from its
module."""
+ return golden_file_for_input(inspect.getfile(cls))
+
+ @classmethod
+ def setup_session(cls, spark):
+ """
+ Hook: prepare the session shared by this class's cases.
+
+ Override to create the temp views and other session state the cases
+ build on.
+ """
+ pass
+
+ @classmethod
+ def setUpClass(cls):
+ cls._golden_regenerating = is_generating_golden()
+ cls._golden_actual = {}
+ cls._golden_cases = {}
+ cls._golden_session = None
+ case_names = cls.case_names()
+
+ # Read the golden file before the session is started: a malformed or
+ # stale file is worth failing on right away, and failing here leaves
+ # nothing to clean up (unittest skips tearDownClass when setUpClass
+ # raises). Regeneration writes the file from the class alone, so it
+ # neither reads nor requires an existing one.
+ if case_names:
+ cls._golden_path = cls.golden_file_path()
+ if not cls._golden_regenerating:
+ cls._golden_cases = parse_test_file(cls._golden_path)
+ assert_cases_in_sync(cls._golden_path, case_names,
list(cls._golden_cases))
+
+ super().setUpClass()
+
+ if not case_names:
+ return
+ # This mixin has to precede the session-providing test class in the
base
+ # list, so that its setUpClass body runs once that class has created
the
+ # session. Checking here rather than when the class is declared keeps
+ # legitimate chains -- a subclass with a setUpClass of its own --
working.
+ assert hasattr(cls, "spark"), (
+ "{}: no session was created; list DFGoldenTestMixin before the "
+ "session-providing test class".format(cls.__name__)
+ )
+ # The one place the session below is released. A class cleanup runs
+ # after tearDownClass, and also after a setUpClass that raised (which
+ # skips tearDownClass), so registering it before the session exists
+ # covers a failure in the setup that follows.
+ cls.addClassCleanup(cls._close_golden_session)
+ cls._golden_session = cls.spark.newSession()
+ # Golden files are generated with ANSI mode on, matching the SQL golden
+ # tests. The session is discarded with the class, so there is nothing
+ # to restore.
+ cls._golden_session.conf.set("spark.sql.ansi.enabled", "true")
+ cls.setup_session(cls._golden_session)
+
+ @classmethod
+ def tearDownClass(cls):
+ try:
+ if cls._golden_regenerating and cls.case_names():
+ cls._write_golden_file()
+ finally:
+ super().tearDownClass()
+
+ @classmethod
+ def _close_golden_session(cls):
+ """
+ Release this class's session, whenever its class cleanup gets to run.
+
+ That is after the session-providing class has stopped the session this
+ one was made from, or -- when setUpClass raised, which skips
+ tearDownClass -- before that class stopped anything. Both orders end
up
+ here, so nothing else has to release the session.
+ """
+ if cls._golden_session is None:
+ return
+ client = cls._golden_session.client
+ cls._golden_session = None
+ # Release this session server-side only while the session it was made
+ # from is alive. Stopping that one takes the local Connect server down
+ # with it (what ``stop()`` does under ``SPARK_LOCAL_REMOTE``, which is
+ # how the tests run), so there is nothing left to release, and the
+ # request would retry against a dead server until the test times out.
+ # For the same reason this must NOT call ``session.stop()`` on the
+ # session it is releasing: that would take the server down mid-suite.
+ if not cls.spark.is_stopped:
Review Comment:
**Nit (P3):** `cls.spark.is_stopped` is true here on every normal run. This
class cleanup runs after `ReusedConnectTestCase.tearDownClass` has already
called `cls.spark.stop()`, and `is_stopped` only reports that the provider's
client is closed. A stopped provider means the server is gone only under
`SPARK_LOCAL_REMOTE`, the in-process local server that CI uses. With
`SPARK_CONNECT_TESTING_REMOTE=sc://...` or the opt-in persistent local server
(`SPARK_LOCAL_CONNECT_REUSE=1`), the server keeps running. The release is still
skipped, so each golden class leaves its session, including the `testData` and
`test_agg` views, on the server until the server's session idle timeout (60
minutes by default). The previous runner released the sub-session in every
mode. `stop()` itself clears `SPARK_LOCAL_REMOTE`, so one option is to record
at setup whether the class runs on the in-process local server, and skip the
release only when it does and the provider has stopped.
**Verification:**
- **Regression:** With a providing session whose stop leaves the server
running, the class cleanup releases the golden session and then closes its
client.
- **Behavior:** With the in-process local server already stopped by the
providing class, the cleanup closes the client without attempting a release.
- **Behavior:** When setUpClass fails after the golden session exists, the
cleanup still releases the session and closes its client.
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -744,3 +752,232 @@ def _compare_case(test_case, case, actual):
got.strip("\n"),
"[{}] mismatch in `{}`".format(name, key),
)
+
+
+def is_generating_golden():
+ """Whether this run regenerates the golden files instead of checking
them."""
+ return os.environ.get("SPARK_GENERATE_GOLDEN_FILES") is not None
+
+
+def golden_file_for_input(module_file):
+ """
+ Return the golden file path for the test module at *module_file*.
+
+ Mirrors ``SQLQueryTestSuite.resultFileForInputFile``: the ``inputs``
+ directory becomes ``results`` and ``.out`` is appended, so a module and its
+ golden file are named alike and there is nothing to keep in sync by hand.
+ """
+ inputs_dir, filename = os.path.split(os.path.abspath(module_file))
+ base_dir, dir_name = os.path.split(inputs_dir)
+ assert dir_name == _INPUTS_DIR, (
+ "{}: a golden test module must live in the `{}` directory, next to the
"
+ "`{}` directory holding the golden files".format(module_file,
_INPUTS_DIR, _RESULTS_DIR)
+ )
+ return os.path.join(base_dir, _RESULTS_DIR, filename + ".out")
+
+
+def assert_cases_in_sync(test_file, declared, golden):
+ """
+ Assert that the golden file describes exactly the declared cases, in order.
+
+ Each test asserts against its own block, so a case the golden file has
never
+ heard of (or one it still remembers after the method was deleted or
renamed)
+ would otherwise go unnoticed.
+ """
+ if declared == golden:
+ return
+ missing = [name for name in declared if name not in golden]
+ extra = [name for name in golden if name not in declared]
+ if missing:
+ detail = "cases with no block in the golden file: " + ",
".join(missing)
+ elif extra:
+ detail = "blocks in the golden file with no case method: " + ",
".join(extra)
+ else:
+ detail = "the golden file lists the cases in a different order"
+ raise AssertionError(
+ "{}: golden file is out of sync with the test class ({}); "
+ "regenerate the golden files".format(test_file, detail)
+ )
+
+
+# ---------------------------------------------------------------------------
+# Test class integration
+# ---------------------------------------------------------------------------
+
+
+class DFGoldenTestMixin:
+ """
+ Mixin turning a class of case methods into DataFrame golden file tests.
+
+ Mix into a session-providing test case, listing this class first so its
+ ``setUpClass`` runs once the session exists::
+
+ class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):
+ def _test_group_by_count(self, spark):
+ return
spark.table("testData").groupBy(col("a")).agg(count(col("b")))
+
+ Every ``_test_<case>`` method declares one case and returns the DataFrame
+ under test; a ``test_<case>`` method is registered for each, so cases run,
+ report and can be selected individually like any other unittest test. The
+ golden file is derived from the test module (see
+ :func:`golden_file_for_input`), so there is nothing to declare.
+
+ The cases of a class share one Spark Connect session (``newSession()`` off
+ the session the test class provides, the Connect counterpart of
+ ``SQLQueryTestSuite``'s per-file ``newSession()``), prepared once by
+ :meth:`setup_session`. State created there -- temp views, UDFs, session
+ confs -- is discarded with the session and cannot leak into other classes.
+ """
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ # Only the cases this class declares: an inherited one already has its
+ # test method on the class that declares it.
+ for attr, method in list(vars(cls).items()):
+ if attr.startswith(_CASE_METHOD_PREFIX) and
inspect.isfunction(method):
+ cls._register_case_test(attr[len(_CASE_METHOD_PREFIX) :],
method)
+
+ @classmethod
+ def _register_case_test(cls, name, case_method):
+ """Add the unittest method that runs the case *name*."""
+
+ def test_case(self):
+ self._run_golden_case(name)
+
+ test_case.__name__ = "test_" + name
+ # Carry the case method's docstring over so verbose runs describe the
case.
+ test_case.__doc__ = case_method.__doc__
+ setattr(cls, test_case.__name__, test_case)
+
+ @classmethod
+ def case_names(cls):
+ """The declared case names, including inherited ones, sorted by
name."""
+ return [
+ name[len(_CASE_METHOD_PREFIX) :]
+ for name, _ in inspect.getmembers(cls,
predicate=inspect.isfunction)
+ if name.startswith(_CASE_METHOD_PREFIX)
+ ]
+
+ @classmethod
+ def golden_file_path(cls):
+ """Absolute path of this class's golden file, derived from its
module."""
+ return golden_file_for_input(inspect.getfile(cls))
Review Comment:
**Nit (P3):** The results file depends only on the module, but its `source`
header and the case list that `assert_cases_in_sync` checks describe exactly
one class. A second golden class in the same module therefore resolves to the
same `results/test_<topic>.py.out`. Examples are a
`GroupByNonAnsiGoldenTests(GroupByGoldenTests)` that reruns the cases with ANSI
off, or a base class with cases plus a subclass that adds more; a stub module
confirmed that both classes get the same path. With
`SPARK_GENERATE_GOLDEN_FILES` set, whichever class is torn down last overwrites
the file. When verifying, the other class fails with a message to regenerate,
and regenerating reproduces the conflict. Subclassing is otherwise supported
(`case_names()` includes inherited cases), so nothing tells someone adding such
a class that it needs its own module.
**Recommended change:** Make the framework refuse, with a clear message, a
second golden test class that resolves to the same results file within a test
run, and document that each golden test class needs its own
inputs/test_<topic>.py module.
**Why this works:** When a golden class with cases is set up, the mixin
records the results file it resolves to together with the class's qualified
name. If a different golden class has already claimed that file in the same
process, setUpClass fails before the session starts, naming both classes and
telling the author to move one of them into its own module. A class that is set
up again keeps its own claim, and only the copy of a doubly imported module
whose tests run is ever set up.
**Scope:** Add a per-run claim check on results files to the mixin's
setUpClass, and state the one-class-per-module rule in the framework docstrings.
**Compatibility:** Existing single-class modules keep the
inputs/test_<topic>.py to results/test_<topic>.py.out mapping, and their golden
files are unchanged.
**Risks:** The claim must compare classes by qualified name and resolved
file, not by object identity, so a class set up again in the same process, or
the second copy of a doubly imported module, is not mistaken for a conflicting
class.
**Constraints:** The check runs only for classes that declare cases, at run
time, and must not reject a golden subclass placed in a different module, whose
results file differs.
**Exclusions:**
- Supporting several golden classes in one module, which would need
per-class results files, is left out.
**Success:** Setting up a second golden class whose results file another
golden class already uses in the same run fails before any case runs, with a
message that names both classes and the fix. A single golden class per module,
and golden subclasses placed in their own modules, run and regenerate exactly
as before. The framework docs state that each golden test class needs its own
inputs/test_<topic>.py module.
**Verification:**
- **Regression:** With two golden classes that resolve to the same results
file in one run, the second fails at setup with the clear message, and
regeneration never replaces the first class's outputs with the second's.
- **Behavior:** A golden subclass defined in a different module resolves to
its own results file and runs and regenerates normally.
- **Compatibility:** Running a golden module through the standard test
runner, which imports it under two names, raises no false conflict.
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -18,23 +18,51 @@
"""
Framework for DataFrame API golden file tests, analogous to SQLQueryTestSuite
for SQL.
-A test is described by a ``.test`` file which doubles as the golden file: the
-expected outputs are stored inline and rewritten in place when golden files are
-regenerated (``SPARK_GENERATE_GOLDEN_FILES=1``).
+A golden test is a pair of files, laid out like the SQL golden tests under
+``sql/core/src/test/resources/sql-tests``::
-``.test`` file format::
+ inputs/test_<topic>.py the test module declaring the cases
+ results/test_<topic>.py.out their expected outputs
+
+Everything a case needs in order to run -- the DataFrame program, its name, its
+tags -- lives in the Python class, so cases are ordinary code that can be read,
+imported and stepped through; the file under ``results`` is purely generated
+output, rewritten in place when golden files are regenerated
+(``SPARK_GENERATE_GOLDEN_FILES=1``).
+
+Test module::
+
+ class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):
+ @classmethod
+ def setup_session(cls, spark):
+ spark.sql("CREATE OR REPLACE TEMPORARY VIEW testData AS ...")
+
+ @unordered
+ def _test_group_by_count(self, spark):
+ \"\"\"Aggregate with non-empty GroupBy expressions.\"\"\"
+ return
spark.table("testData").groupBy(col("a")).agg(count(col("b")))
+
+Each ``_test_<case>`` method builds and returns the DataFrame of one case, and
+:class:`DFGoldenTestMixin` registers a ``test_<case>`` method for it. Cases
are
+therefore ordinary unittest tests: they are reported individually and can be
run
+one at a time::
+
+ python/run-tests --testnames
"pyspark.sql.tests.df_golden.inputs.test_group_by \\
+ GroupByGoldenTests.test_group_by_count"
+
+Golden file format::
--! name
__file_metadata__
--! source
- df_golden/group_by
+ pyspark.sql.tests.df_golden.inputs.test_group_by.GroupByGoldenTests
!-- end
--! name
- range + select + filter + order
- --! script
- scripts/group_by/range_select.py
+ group_by_count
Review Comment:
**Nit (P3):** The example is now named `group_by_count` and tagged
`unordered`, but its body is still the old `range + select + filter + order`
case: a plan rooted at `Sort [k#x ASC NULLS FIRST], true`, schema
`struct<k:bigint>`, and one row `k = 1`. That contradicts the rule further down
that `unordered` is for results without a global sort. It also doesn't match
the real `group_by_count` block in `results/test_group_by.py.out`, which has an
`Aggregate [a#x], ...` plan, `struct<a:int,count(b):bigint>`, and four rows. An
abbreviated copy of that block would make the example consistent.
**Verification:**
- **Inspection:** The example's plan, schema and result agree with its case
name and tags, and with the docstring's rule that unordered marks results
without a global sort.
##########
python/pyspark/sql/tests/df_golden/test_df_golden_framework.py:
##########
@@ -510,25 +482,168 @@ def
test_format_value_refuses_tab_or_newline_in_string(self):
# -- regeneration ----------------------------------------------------
- def test_regenerate_replaces_expected_sections_and_carries_identity(self):
- old = {
- "name": "c",
- "tags": "unordered",
- "script": "scripts/a.py",
- "expected_optimized_output": "old base",
- "expected_output_schema": "old schema",
- }
- actual = {
- "expected_optimized_output": "new base",
- "expected_output_schema": "new schema",
- }
- new = _regenerate_case(old, actual)
- # Name / tags / script are carried over; expected_* come from this run.
- self.assertEqual(new["name"], "c")
- self.assertEqual(new["tags"], "unordered")
- self.assertEqual(new["script"], "scripts/a.py")
- self.assertEqual(new["expected_optimized_output"], "new base")
- self.assertEqual(new["expected_output_schema"], "new schema")
+ def test_compare_case_checks_tags(self):
Review Comment:
**Nit (P3):** This section used to hold the regeneration test. It now holds
a comparison test, and nothing exercises regeneration. The removed tests
covered how regeneration replaced sections and tolerated stale or invalid
files. The new path (`setUpClass` skipping the parse, `_run_golden_case`
collecting outputs, `tearDownClass` -> `_write_golden_file` and its partial-run
guard) never runs in a test: `_fake_golden_class` pops
`SPARK_GENERATE_GOLDEN_FILES`, and no CI job sets it. A change that drops the
`source` header or the tags, removes the `assert not missing` guard, or makes
regeneration parse the old file would pass every test. It would show up only
the next time someone regenerates. The fake-session harness could run the
registered tests with the variable set and check the written file, and this
comparison test could move to the case-comparison section.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -744,3 +752,232 @@ def _compare_case(test_case, case, actual):
got.strip("\n"),
"[{}] mismatch in `{}`".format(name, key),
)
+
+
+def is_generating_golden():
+ """Whether this run regenerates the golden files instead of checking
them."""
+ return os.environ.get("SPARK_GENERATE_GOLDEN_FILES") is not None
+
+
+def golden_file_for_input(module_file):
+ """
+ Return the golden file path for the test module at *module_file*.
+
+ Mirrors ``SQLQueryTestSuite.resultFileForInputFile``: the ``inputs``
+ directory becomes ``results`` and ``.out`` is appended, so a module and its
+ golden file are named alike and there is nothing to keep in sync by hand.
+ """
+ inputs_dir, filename = os.path.split(os.path.abspath(module_file))
+ base_dir, dir_name = os.path.split(inputs_dir)
+ assert dir_name == _INPUTS_DIR, (
+ "{}: a golden test module must live in the `{}` directory, next to the
"
+ "`{}` directory holding the golden files".format(module_file,
_INPUTS_DIR, _RESULTS_DIR)
+ )
+ return os.path.join(base_dir, _RESULTS_DIR, filename + ".out")
+
+
+def assert_cases_in_sync(test_file, declared, golden):
+ """
+ Assert that the golden file describes exactly the declared cases, in order.
+
+ Each test asserts against its own block, so a case the golden file has
never
+ heard of (or one it still remembers after the method was deleted or
renamed)
+ would otherwise go unnoticed.
+ """
+ if declared == golden:
+ return
+ missing = [name for name in declared if name not in golden]
+ extra = [name for name in golden if name not in declared]
+ if missing:
+ detail = "cases with no block in the golden file: " + ",
".join(missing)
+ elif extra:
+ detail = "blocks in the golden file with no case method: " + ",
".join(extra)
+ else:
+ detail = "the golden file lists the cases in a different order"
+ raise AssertionError(
+ "{}: golden file is out of sync with the test class ({}); "
+ "regenerate the golden files".format(test_file, detail)
+ )
+
+
+# ---------------------------------------------------------------------------
+# Test class integration
+# ---------------------------------------------------------------------------
+
+
+class DFGoldenTestMixin:
+ """
+ Mixin turning a class of case methods into DataFrame golden file tests.
+
+ Mix into a session-providing test case, listing this class first so its
+ ``setUpClass`` runs once the session exists::
+
+ class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):
+ def _test_group_by_count(self, spark):
+ return
spark.table("testData").groupBy(col("a")).agg(count(col("b")))
+
+ Every ``_test_<case>`` method declares one case and returns the DataFrame
+ under test; a ``test_<case>`` method is registered for each, so cases run,
+ report and can be selected individually like any other unittest test. The
+ golden file is derived from the test module (see
+ :func:`golden_file_for_input`), so there is nothing to declare.
+
+ The cases of a class share one Spark Connect session (``newSession()`` off
+ the session the test class provides, the Connect counterpart of
+ ``SQLQueryTestSuite``'s per-file ``newSession()``), prepared once by
+ :meth:`setup_session`. State created there -- temp views, UDFs, session
+ confs -- is discarded with the session and cannot leak into other classes.
+ """
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ # Only the cases this class declares: an inherited one already has its
+ # test method on the class that declares it.
+ for attr, method in list(vars(cls).items()):
Review Comment:
**Nit (P3):** This loop registers only the `_test_` methods in the class's
own namespace, but `case_names()` walks the whole MRO. Take a case that comes
from a plain base class, such as `class Shared:` with `_test_shared`, mixed
into `class G(Shared, DFGoldenTestMixin, ReusedConnectTestCase)`.
`case_names()` returns `['own', 'shared']`, but only `test_own` is registered
(checked against the mixin itself). Regeneration then refuses with 'these cases
did not run (a failing case, or a run filtered to a subset): shared', and
verification requires a `shared` block that no run can produce. The comment
above holds only when the base class is itself a golden class. Registering
every case from `case_names()` that has no inherited test method would cover
plain bases too.
**Verification:**
- **Regression:** For a golden class that mixes in a plain class holding a
case method, case_names() and the registered test methods list the same cases,
and regeneration does not refuse.
- **Behavior:** Cases inherited from a golden base class are still
registered once, on the class that declares them.
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -744,3 +752,232 @@ def _compare_case(test_case, case, actual):
got.strip("\n"),
"[{}] mismatch in `{}`".format(name, key),
)
+
+
+def is_generating_golden():
+ """Whether this run regenerates the golden files instead of checking
them."""
+ return os.environ.get("SPARK_GENERATE_GOLDEN_FILES") is not None
+
+
+def golden_file_for_input(module_file):
+ """
+ Return the golden file path for the test module at *module_file*.
+
+ Mirrors ``SQLQueryTestSuite.resultFileForInputFile``: the ``inputs``
+ directory becomes ``results`` and ``.out`` is appended, so a module and its
+ golden file are named alike and there is nothing to keep in sync by hand.
+ """
+ inputs_dir, filename = os.path.split(os.path.abspath(module_file))
+ base_dir, dir_name = os.path.split(inputs_dir)
+ assert dir_name == _INPUTS_DIR, (
+ "{}: a golden test module must live in the `{}` directory, next to the
"
+ "`{}` directory holding the golden files".format(module_file,
_INPUTS_DIR, _RESULTS_DIR)
+ )
+ return os.path.join(base_dir, _RESULTS_DIR, filename + ".out")
+
+
+def assert_cases_in_sync(test_file, declared, golden):
+ """
+ Assert that the golden file describes exactly the declared cases, in order.
+
+ Each test asserts against its own block, so a case the golden file has
never
+ heard of (or one it still remembers after the method was deleted or
renamed)
+ would otherwise go unnoticed.
+ """
+ if declared == golden:
+ return
+ missing = [name for name in declared if name not in golden]
+ extra = [name for name in golden if name not in declared]
+ if missing:
+ detail = "cases with no block in the golden file: " + ",
".join(missing)
+ elif extra:
+ detail = "blocks in the golden file with no case method: " + ",
".join(extra)
+ else:
+ detail = "the golden file lists the cases in a different order"
+ raise AssertionError(
+ "{}: golden file is out of sync with the test class ({}); "
+ "regenerate the golden files".format(test_file, detail)
+ )
+
+
+# ---------------------------------------------------------------------------
+# Test class integration
+# ---------------------------------------------------------------------------
+
+
+class DFGoldenTestMixin:
+ """
+ Mixin turning a class of case methods into DataFrame golden file tests.
+
+ Mix into a session-providing test case, listing this class first so its
+ ``setUpClass`` runs once the session exists::
+
+ class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):
+ def _test_group_by_count(self, spark):
+ return
spark.table("testData").groupBy(col("a")).agg(count(col("b")))
+
+ Every ``_test_<case>`` method declares one case and returns the DataFrame
+ under test; a ``test_<case>`` method is registered for each, so cases run,
+ report and can be selected individually like any other unittest test. The
+ golden file is derived from the test module (see
+ :func:`golden_file_for_input`), so there is nothing to declare.
+
+ The cases of a class share one Spark Connect session (``newSession()`` off
+ the session the test class provides, the Connect counterpart of
+ ``SQLQueryTestSuite``'s per-file ``newSession()``), prepared once by
+ :meth:`setup_session`. State created there -- temp views, UDFs, session
+ confs -- is discarded with the session and cannot leak into other classes.
+ """
+
+ def __init_subclass__(cls, **kwargs):
+ super().__init_subclass__(**kwargs)
+ # Only the cases this class declares: an inherited one already has its
+ # test method on the class that declares it.
+ for attr, method in list(vars(cls).items()):
+ if attr.startswith(_CASE_METHOD_PREFIX) and
inspect.isfunction(method):
+ cls._register_case_test(attr[len(_CASE_METHOD_PREFIX) :],
method)
+
+ @classmethod
+ def _register_case_test(cls, name, case_method):
+ """Add the unittest method that runs the case *name*."""
+
+ def test_case(self):
+ self._run_golden_case(name)
+
+ test_case.__name__ = "test_" + name
+ # Carry the case method's docstring over so verbose runs describe the
case.
+ test_case.__doc__ = case_method.__doc__
+ setattr(cls, test_case.__name__, test_case)
+
+ @classmethod
+ def case_names(cls):
+ """The declared case names, including inherited ones, sorted by
name."""
+ return [
+ name[len(_CASE_METHOD_PREFIX) :]
+ for name, _ in inspect.getmembers(cls,
predicate=inspect.isfunction)
+ if name.startswith(_CASE_METHOD_PREFIX)
+ ]
+
+ @classmethod
+ def golden_file_path(cls):
+ """Absolute path of this class's golden file, derived from its
module."""
+ return golden_file_for_input(inspect.getfile(cls))
+
+ @classmethod
+ def setup_session(cls, spark):
+ """
+ Hook: prepare the session shared by this class's cases.
+
+ Override to create the temp views and other session state the cases
+ build on.
+ """
+ pass
+
+ @classmethod
+ def setUpClass(cls):
+ cls._golden_regenerating = is_generating_golden()
+ cls._golden_actual = {}
+ cls._golden_cases = {}
+ cls._golden_session = None
+ case_names = cls.case_names()
+
+ # Read the golden file before the session is started: a malformed or
+ # stale file is worth failing on right away, and failing here leaves
+ # nothing to clean up (unittest skips tearDownClass when setUpClass
+ # raises). Regeneration writes the file from the class alone, so it
+ # neither reads nor requires an existing one.
+ if case_names:
+ cls._golden_path = cls.golden_file_path()
+ if not cls._golden_regenerating:
+ cls._golden_cases = parse_test_file(cls._golden_path)
+ assert_cases_in_sync(cls._golden_path, case_names,
list(cls._golden_cases))
+
+ super().setUpClass()
+
+ if not case_names:
+ return
+ # This mixin has to precede the session-providing test class in the
base
+ # list, so that its setUpClass body runs once that class has created
the
+ # session. Checking here rather than when the class is declared keeps
+ # legitimate chains -- a subclass with a setUpClass of its own --
working.
+ assert hasattr(cls, "spark"), (
Review Comment:
**Nit (P3):** This assertion can't catch the misordering its message
describes. With `class X(ReusedConnectTestCase, DFGoldenTestMixin)`,
`ReusedConnectTestCase.setUpClass` chains to `PySparkBaseTestCase.setUpClass`,
which doesn't call `super()`, so this `setUpClass` never runs. The registered
tests still exist, and each one fails in `_run_golden_case` with
`AttributeError: type object 'X' has no attribute '_golden_session'`
(reproduced with stub classes that mirror that chain). The assertion is reached
only when no base provides `spark` at all, as in `class X(DFGoldenTestMixin,
unittest.TestCase)`, and there reordering the bases is not the fix. A check in
`_run_golden_case`, which always runs, would report the misordering at run time
as agreed in the review discussion. This message could then describe the
missing session provider instead.
**Verification:**
- **Regression:** A class that lists the mixin after a session provider
whose class setup does not chain fails every case with the base-order message
instead of an AttributeError.
- **Behavior:** A correctly ordered class, and a subclass chain whose
intermediate class defines setUpClass, still set up and run their cases.
##########
python/pyspark/sql/tests/df_golden/test_df_golden_framework.py:
##########
@@ -510,25 +482,168 @@ def
test_format_value_refuses_tab_or_newline_in_string(self):
# -- regeneration ----------------------------------------------------
- def test_regenerate_replaces_expected_sections_and_carries_identity(self):
- old = {
- "name": "c",
- "tags": "unordered",
- "script": "scripts/a.py",
- "expected_optimized_output": "old base",
- "expected_output_schema": "old schema",
- }
- actual = {
- "expected_optimized_output": "new base",
- "expected_output_schema": "new schema",
- }
- new = _regenerate_case(old, actual)
- # Name / tags / script are carried over; expected_* come from this run.
- self.assertEqual(new["name"], "c")
- self.assertEqual(new["tags"], "unordered")
- self.assertEqual(new["script"], "scripts/a.py")
- self.assertEqual(new["expected_optimized_output"], "new base")
- self.assertEqual(new["expected_output_schema"], "new schema")
+ def test_compare_case_checks_tags(self):
+ # Tags are data: a golden file recording a tag the case no longer
carries
+ # is a mismatch, reported like any other section.
+ compare_case(self, {"name": "c", "tags": "unordered"}, {"tags":
"unordered"})
+ with self.assertRaisesRegex(AssertionError, "expected section `tags`"):
+ compare_case(self, {"name": "c", "tags": "unordered"}, {})
+
+ # -- case registration ------------------------------------------------
+
+ def test_mixin_registers_a_test_per_case_sorted_by_name(self):
+ class Cases(DFGoldenTestMixin, unittest.TestCase):
+ def _test_second(self, spark):
+ """Second case."""
+
+ def _test_first(self, spark):
+ pass
+
+ # Sorted, which is also the order unittest runs the cases in.
+ self.assertEqual(Cases.case_names(), ["first", "second"])
+ self.assertTrue(callable(Cases.test_second))
Review Comment:
**Nit (P3):** These assertions show that the methods exist and keep their
docstrings, but nothing calls one, so nothing checks that `test_<case>` runs
its own case. Dispatch is right today because `_register_case_test` binds
`name` as a parameter. If the closure moved into the `__init_subclass__` loop,
late binding would make every registered test run the last case. This test
would still pass, and so would the CI run of `inputs/test_group_by.py`, because
each test compares that one case with its own block and `assert_cases_in_sync`
checks only names. Then 36 of the 37 cases would go unchecked. Calling the
registered methods with `compute_case_outputs` patched, and asserting which
case each one ran, would catch this.
See **Shared repair plan 1** in the review body.
##########
python/pyspark/sql/tests/df_golden/regenerate.sh:
##########
@@ -33,21 +33,35 @@ for arg in "$@"; do
esac
done
-REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && git rev-parse
--show-toplevel)"
+THIS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+REPO_ROOT="$(cd "$THIS_DIR" && git rev-parse --show-toplevel)"
cd "$REPO_ROOT"
-MODULE="pyspark.sql.tests.df_golden.test_df_golden"
REL_DIR="python/pyspark/sql/tests/df_golden"
-echo ">>> Regenerating golden files..."
-SPARK_GENERATE_GOLDEN_FILES=1 python/run-tests --testnames "$MODULE"
+# Every module declaring golden cases, i.e. every test module under inputs/
with
+# a top-level class mixing in DFGoldenTestMixin. Adding one needs no change
here.
+MODULES=()
+for file in "$THIS_DIR"/inputs/test_*.py; do
+ if grep -q "^class .*(DFGoldenTestMixin" "$file"; then
Review Comment:
**Nit (P3):** This grep matches only a one-line header whose base list
starts with `DFGoldenTestMixin`. I ran it over sample headers. It selected
`class GroupByGoldenTests(DFGoldenTestMixin, ReusedConnectTestCase):` but
skipped three shapes the mixin accepts: a header wrapped across lines (as ruff
formats a long one), `class X(OtherMixin, DFGoldenTestMixin,
ReusedConnectTestCase):`, and `class X(SharedGoldenBase):`. The script still
reports success, and `--verify` re-runs only what it found. The skipped module
then fails in CI with `FileNotFoundError` or an out-of-sync error, even though
the comment above says adding a module needs no change here. Running every
`inputs/test_*.py` module would match the stated rule without parsing class
headers.
**Verification:**
- **Regression:** A module whose golden class header spans several lines,
lists another mixin first, or inherits DFGoldenTestMixin from a shared base is
included in the regenerated and verified set.
- **Behavior:** inputs/test_group_by.py is still regenerated and verified,
and an inputs/ directory without test modules still makes the script fail.
--
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]