dtenedor commented on code in PR #57691:
URL: https://github.com/apache/spark/pull/57691#discussion_r4554992655
##########
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:
Done in be67341. The misordering is now reported by `_run_golden_case`,
which always runs: with the mixin listed after a provider whose `setUpClass`
does not chain there is no golden session, and every case fails with a message
saying to list `DFGoldenTestMixin` before the session-providing test class,
instead of an `AttributeError`. The assertion in `setUpClass` is kept for the
case it can see, and its message now describes the missing session provider.
Tests:
`test_mixin_listed_after_the_session_provider_is_reported_by_each_case`,
`test_mixin_without_a_session_provider_is_reported`, and
`test_mixin_allows_a_subclass_to_define_set_up_class`, which now runs the chain
instead of only declaring it.
##########
python/pyspark/sql/tests/df_golden/df_golden.py:
##########
@@ -744,3 +752,225 @@ 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 "spark" in vars(cls), (
+ "{}: no session was created; list DFGoldenTestMixin before the "
+ "session-providing test class".format(cls.__name__)
+ )
+ try:
+ 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")
Review Comment:
Follow-up from the spark-test review, in be67341: a stopped providing
session means the server is gone only when that session started it in this
process. `_close_golden_session` therefore skips `release_session()` only in
that case, and still releases against a server that outlives the provider
(`SPARK_CONNECT_TESTING_REMOTE`, or the persistent local server), which would
otherwise keep the golden session and its temp views until they idle out. It
remains the one place the session is released.
##########
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:
Done in be67341. The new `DFGoldenTestMixinTests` runs golden test classes
through a real unittest runner over a fake session, with
`SPARK_GENERATE_GOLDEN_FILES` set where a test needs it.
`test_regeneration_writes_the_golden_file_from_the_run` checks the written file
(the `source` header, cases sorted by name, tags), starting from an old file
that is not a golden file at all.
`test_regeneration_refuses_a_run_that_skipped_a_case` checks that a partial run
fails and leaves the previous file untouched. `test_compare_case_checks_tags`
moved to the case-comparison section.
Each change this comment lists was also tried against these tests: dropping
the `source` header or the tags, removing the partial-run guard, and making
regeneration parse the old file each make one of them fail.
##########
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:
Done in be67341: the example is now an abbreviated copy of the real
`group_by_count` block in `results/test_group_by.py.out` (an `Aggregate` plan,
`struct<a:int,count(b):bigint>`, four rows), so it agrees with its name, its
`unordered` tag and the rule on `unordered` further down.
##########
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:
Done in be67341: the script runs every `inputs/test_*.py` module and no
longer looks at class headers.
Checked in a scratch repository with a stubbed `python/run-tests`: modules
with a wrapped header, with another mixin listed first, and with the mixin
inherited from a shared base are all included in both the regeneration and the
`--verify` run, and an `inputs/` directory without test modules still fails.
Against a real build, `regenerate.sh --verify` rewrites
`results/test_group_by.py.out` byte for byte.
##########
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:
Done in be67341. `setUpClass` records whether the providing session started
the Connect server in this process (`SPARK_LOCAL_REMOTE`, read at setup because
`stop()` clears it), and `_close_golden_session` skips `release_session()` only
when it did and that session has stopped. A server that outlives the provider
(`SPARK_CONNECT_TESTING_REMOTE`, or the persistent local server) gets the
release.
Running this against a standalone Connect server showed that the release
needed one more fix to take effect: the cleanup dropped its last reference to
the golden session before releasing it, and a Connect `SparkSession` closes its
client when it is garbage collected, so `release_session()` failed with
`NO_ACTIVE_SESSION` and the error was swallowed. The session is now held until
the release is done. On that server the golden session used to stay queryable,
`testData` view included, after the class finished; it is now refused with
`INVALID_HANDLE.SESSION_CLOSED`.
Tests, in the new `DFGoldenTestMixinTests`, which runs golden test classes
through a real unittest runner over a fake session:
`test_session_is_released_when_the_server_outlives_the_provider`,
`test_session_release_is_skipped_once_the_in_process_server_stopped` and
`test_session_is_released_when_set_up_class_fails`. The fake session closes its
client when collected, like the real one.
##########
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:
Done in be67341. `__init_subclass__` now walks `case_names()` and registers
a test for every case that is declared on the class itself or has no test
method yet, so a case from a plain base class is run as well as counted. A case
inherited from a golden base class keeps the one test method on the class that
declares it.
Tests: `test_mixin_registers_cases_declared_on_a_plain_base_class` asserts
that `case_names()` and the test methods the loader finds are the same;
`test_mixin_inherits_cases_from_base_classes` still covers the golden base
class.
##########
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:
Done in be67341: `test_registered_tests_each_run_their_own_case` runs the
registered tests of a two-case class with `compute_case_outputs` patched and
asserts which case method each one ran. Making every registered test run the
last case, as a late-binding closure would, fails it.
##########
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:
Done in be67341, following the recommended change. A golden file belongs to
the first class that claims it in a test run (`claim_golden_file`, called from
`setUpClass` before the file is read or a session is started). A second class
resolving to the same file fails at setup with a message that names both
classes and says to give each golden test class its own
`inputs/test_<topic>.py` module, so regeneration can no longer replace the
first class's outputs. The claim compares the resolved file and the class name,
not the class object, so a class that is set up again keeps its file. The
module and mixin docstrings state the one-class-per-module rule.
Tests: `test_second_class_resolving_to_a_golden_file_is_refused` and
`test_class_set_up_again_keeps_its_golden_file`. Also checked:
`python/run-tests`, which imports the module under two names, runs
`inputs/test_group_by.py` without a conflict, and a golden subclass placed in
another module resolves to its own results file and regenerates and verifies
normally.
--
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]