diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/GeneratedCodeAssertions.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/GeneratedCodeAssertions.scala
index 655d3d080e9..ef5ceb659ea 100644
--- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/GeneratedCodeAssertions.scala
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/GeneratedCodeAssertions.scala
@@ -19,6 +19,10 @@
package org.apache.texera.amber.operator
+import org.apache.texera.amber.core.tuple.{AttributeType, Schema}
+import org.apache.texera.amber.core.workflow.PortIdentity
+import org.scalatest.Assertion
+
import java.nio.charset.StandardCharsets
import java.util.Base64
@@ -58,6 +62,31 @@ private[operator] trait GeneratedCodeAssertionChecks
error.getMessage should include(phrase)
error
}
+
+ protected final def expectedHtmlOutputSchema(
+ op: PythonOperatorDescriptor
+ ): Map[PortIdentity, Schema] =
+ Map(op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING))
+
+ protected final def assertHtmlOutputSchema(
+ op: PythonOperatorDescriptor,
+ inputSchemas: Map[PortIdentity, Schema] = Map.empty
+ )(implicit pos: Position): Assertion = {
+ val schemas = op.getOutputSchemas(inputSchemas)
+ schemas should have size 1
+ val (portId, schema) = schemas.head
+ portId shouldBe op.operatorInfo.outputPorts.head.id
+ schema.getAttributes should have length 1
+ schema.getAttributes.head.getName shouldBe "html-content"
+ schema.getAttributes.head.getType shouldBe AttributeType.STRING
+ }
+
+ protected final def expectEmptyFieldError(fieldFragment: String)(body: => Any)(implicit
+ pos: Position
+ ): Assertion = {
+ val ex = expectError[AssertionError]("cannot be empty")(body)
+ fieldPart(ex.getMessage) should include(fieldFragment)
+ }
}
// EncodableString columns are always base64-wrapped in .encode mode
diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ChartPythonTestSupport.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ChartPythonTestSupport.scala
new file mode 100644
index 00000000000..f760b047193
--- /dev/null
+++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ChartPythonTestSupport.scala
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.texera.amber.operator.visualization
+
+import org.apache.texera.amber.util.PythonTestSupport.{requirePython, withDriver}
+import org.scalatest.Assertions.withClue
+import org.scalatest.matchers.should.Matchers._
+
+private[visualization] object ChartPythonTestSupport {
+
+ /** Parses `"CASE Reason is: "
+ withClue(s"Driver output:\n$output\n") {
+ exitCode shouldBe 0
+ output should include(s"CASE empty ${page}input table is empty.$title is not available.
Reason is: " - withClue(s"Driver output:\n$output\n") { - exitCode shouldBe 0 - output should include(s"CASE empty ${page}input table is empty.
") - output should include( - s"CASE every_row_holed ${page}value column contains only non-positive numbers or nulls." - ) - output should include("CASE filled CHART") - } - } + "Figure Factory Table" + ) } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDescSpec.scala index 3a4c56241c9..e04727e045a 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/filledAreaPlot/FilledAreaPlotOpDescSpec.scala @@ -19,12 +19,12 @@ package org.apache.texera.amber.operator.visualization.filledAreaPlot -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.{ + parseCaseVerdicts, + verifyStandaloneChartCases, + withPytexeraTableDriver } +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages import org.apache.texera.amber.core.tuple.{AttributeType, Schema} import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorMetadataGenerator @@ -203,33 +203,8 @@ class FilledAreaPlotOpDescSpec // Driver executed by the runtime test below. It stubs only the pytexera import seam // (base class, decorator, and type aliases); the generated module itself runs unmodified, // including the real pandas groupby guard and plotly rendering. - private val runtimeDriverScript: String = - """import base64 - |import sys - |import types - |from typing import Iterator, Optional - | - |import pandas as pd - | - |class UDFTableOperator: - | def decode_python_template(self, data): - | return base64.b64decode(data).decode("utf-8") - | - |stub = types.ModuleType("pytexera") - |stub.UDFTableOperator = UDFTableOperator - |stub.overrides = lambda fn: fn - |stub.Table = pd.DataFrame - |stub.TableLike = object - |stub.Iterator = Iterator - |stub.Optional = Optional - |sys.modules["pytexera"] = stub - | - |ns = {"__name__": "generated_filled_area_plot"} - |with open(sys.argv[1], encoding="utf-8") as f: - | exec(compile(f.read(), sys.argv[1], "exec"), ns) - |op = ns["ProcessTableOperator"]() - | - |def make_df(n_groups, disjoint): + private val runtimeDriverBody: String = + """def make_df(n_groups, disjoint): | rows = [] | for i in range(n_groups): | xs = range(101, 111) if i in disjoint else range(1, 11) @@ -261,32 +236,20 @@ class FilledAreaPlotOpDescSpec | verdict = "MISSING" | else: | verdict = "CHART" - | print("CASE %s %s" % (cid, verdict)) - |""".stripMargin + | print("CASE %s %s" % (cid, verdict))""".stripMargin it should "enforce the five-percent tolerance at runtime boundaries" taggedAs NeedsPythonPackages in { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - - withDriver( - python, - "filled_area_plot_op_", - "filled_area_plot_driver_", + withPytexeraTableDriver( + "filled_area_plot", generatedGuardCode(), - runtimeDriverScript, - "Runtime verification driver timed out after 120s" + "generated_filled_area_plot", + "ProcessTableOperator", + runtimeDriverBody, + timeoutMessage = "Runtime verification driver timed out after 120s" ) { (exitCode, output) => withClue(s"Driver output:\n$output\n") { exitCode shouldBe 0 - val verdicts = "CASE (\\S+) (\\S+)".r - .findAllMatchIn(output) - .map(m => m.group(1) -> m.group(2)) - .toMap - verdicts shouldBe Map( + parseCaseVerdicts(output) shouldBe Map( "b19_1" -> "FALLBACK", // 1/19 disjoint = 5.3% > 5% "b20_1" -> "CHART", // exactly 5.0%, tolerance is strict > "b40_1" -> "CHART", // 2.5%: the original floored-tolerance bug @@ -351,66 +314,27 @@ class FilledAreaPlotOpDescSpec // and 8 are past it. "FilledAreaPlotOpDesc.generateStandaloneCode" should "refuse the same tables the operator refuses" taggedAs NeedsPythonPackages in { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - opDesc.x = "x" opDesc.y = "y" opDesc.lineGroup = "grp" - withDriver( - python, - "filled_area_standalone_", - "filled_area_boundary_", + verifyStandaloneChartCases( + "filled_area", opDesc.generateStandaloneCode(), - boundaryDriverScript, - "Boundary driver timed out after 120s" - ) { (exitCode, output) => - withClue(s"Driver output:\n$output\n") { - exitCode shouldBe 0 - val verdicts = "CASE (\\S+) (\\S+)".r - .findAllMatchIn(output) - .map(m => m.group(1) -> m.group(2)) - .toMap - verdicts shouldBe Map("7" -> "CHART", "8" -> "FALLBACK") - } - } + // 150 line groups, as many of them disjoint from the first as the case name says. + casesScript = """def _boundary_frame(disjoint): + | rows = [] + | for index in range(150): + | value = "z%03d" % index if 1 <= index <= disjoint else "a" + | rows.append({"x": value, "y": 1.0, "grp": "g%03d" % index}) + | rows.append({"x": value, "y": 2.0, "grp": "g%03d" % index}) + | return pd.DataFrame(rows) + | + |cases = {str(disjoint): _boundary_frame(disjoint) for disjoint in (7, 8)}""".stripMargin, + verdictBody = + """ verdict = "FALLBACK" if "not shared across all line groups" in page else "CHART"""".stripMargin, + expectedVerdicts = Map("7" -> "CHART", "8" -> "FALLBACK"), + plotlyScopeBinding = Some(("plotly.express", "px")), + timeoutMessage = "Boundary driver timed out after 120s" + ) } - - // Runs the exported block over 150 line groups, as many of them disjoint from - // the first as the case names, and reports the page it wrote. - private val boundaryDriverScript: String = - """import pathlib - |import sys - |import tempfile - | - |import pandas as pd - |import plotly.express as px - | - |# The module and the page are both UTF-8, which Windows does not read by - |# default. - |source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") - | - |for disjoint in (7, 8): - | rows = [] - | for index in range(150): - | value = "z%03d" % index if 1 <= index <= disjoint else "a" - | rows.append({"x": value, "y": 1.0, "grp": "g%03d" % index}) - | rows.append({"x": value, "y": 2.0, "grp": "g%03d" % index}) - | directory = tempfile.mkdtemp() - | scope = { - | "in1df": pd.DataFrame(rows), - | "outputHtml": directory + "/chart.html", - | "outputJson": directory + "/chart.json", - | "pd": pd, - | "px": px, - | } - | exec(compile(source, "standalone", "exec"), scope) - | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8") - | verdict = "FALLBACK" if "not shared across all line groups" in page else "CHART" - | print("CASE %d %s" % (disjoint, verdict)) - |""".stripMargin } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDescSpec.scala index 4076da4cbb0..1aac93c4483 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/funnelPlot/FunnelPlotOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.funnelPlot -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -46,13 +45,7 @@ class FunnelPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks "FunnelPlotOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { val op = configured - val schemas = op.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe op.operatorInfo.outputPorts.head.id - schema.getAttributes should have length 1 - schema.getAttributes.head.getName shouldBe "html-content" - schema.getAttributes.head.getType shouldBe AttributeType.STRING + assertHtmlOutputSchema(op) } "FunnelPlotOpDesc.generatePythonCode" should "render a UDFTableOperator source with runtime decode sites for x and y" in { @@ -96,15 +89,13 @@ class FunnelPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks it should "throw AssertionError naming the X Column when only x is missing" in { val op = new FunnelPlotOpDesc op.y = "count" - val ex = expectError[AssertionError]("cannot be empty")(op.generatePythonCode()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(op.generatePythonCode()) } it should "throw AssertionError naming the Y Column when only y is missing" in { val op = new FunnelPlotOpDesc op.x = "stage" - val ex = expectError[AssertionError]("cannot be empty")(op.generatePythonCode()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(op.generatePythonCode()) } it should "carry the configured x and y columns (as runtime decode payloads) in the generated code" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDescSpec.scala index 44f7388d6f4..dc2014fef12 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/gaugeChart/GaugeChartOpDescSpec.scala @@ -19,20 +19,15 @@ package org.apache.texera.amber.operator.visualization.gaugeChart -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} -import org.apache.texera.amber.core.tuple.{AttributeType, Schema} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.verifyStandaloneChartCases +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -class GaugeChartOpDescSpec extends AnyFlatSpec with Matchers { +class GaugeChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "GaugeChartOpDesc.operatorInfo" should "advertise the name and Financial visualization group" in { @@ -55,9 +50,7 @@ class GaugeChartOpDescSpec extends AnyFlatSpec with Matchers { "GaugeChartOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new GaugeChartOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "GaugeChartOpDesc.generatePythonCode" should "emit a Plotly Indicator figure" in { @@ -138,77 +131,34 @@ class GaugeChartOpDescSpec extends AnyFlatSpec with Matchers { // pandas as a KeyError and ends the whole exported run, not just this chart. "GaugeChartOpDesc.generateStandaloneCode" should "answer what it cannot draw the way the operator answers it" taggedAs NeedsPythonPackages in { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - val d = new GaugeChartOpDesc d.value = "score" - withDriver( - python, - "gauge_standalone_", - "gauge_driver_", + verifyStandaloneChartCases( + "gauge", d.generateStandaloneCode(), - driverScript, - "Gauge driver timed out after 120s" - ) { (exitCode, output) => - withClue(s"Driver output:\n$output\n") { - exitCode shouldBe 0 - val verdicts = "CASE (\\S+) (\\S+)".r - .findAllMatchIn(output) - .map(m => m.group(1) -> m.group(2)) - .toMap - verdicts shouldBe Map( - "missing" -> "GENERAL_ERROR", - "empty" -> "EMPTY", - "nulls" -> "NO_ROWS", - "good" -> "CHART" - ) - } - } + casesScript = """cases = { + | "good": pd.DataFrame({"score": [42.0]}), + | "missing": pd.DataFrame({"other": [42.0]}), + | "empty": pd.DataFrame({"score": []}), + | "nulls": pd.DataFrame({"score": [None, None]}), + |}""".stripMargin, + verdictBody = """ if "General error" in page: + | verdict = "GENERAL_ERROR" + | elif "Input table is empty" in page: + | verdict = "EMPTY" + | elif "No non-null rows" in page: + | verdict = "NO_ROWS" + | elif "Gauge chart is not available" in page: + | verdict = "OTHER_PAGE" + | else: + | verdict = "CHART"""".stripMargin, + expectedVerdicts = Map( + "missing" -> "GENERAL_ERROR", + "empty" -> "EMPTY", + "nulls" -> "NO_ROWS", + "good" -> "CHART" + ), + timeoutMessage = "Gauge driver timed out after 120s" + ) } - - // Runs the exported block over one frame per case and reports the page it - // wrote, so a branch that raises instead of answering fails here. - private val driverScript: String = - """import pathlib - |import sys - |import tempfile - | - |import pandas as pd - | - |source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") - | - |cases = { - | "good": pd.DataFrame({"score": [42.0]}), - | "missing": pd.DataFrame({"other": [42.0]}), - | "empty": pd.DataFrame({"score": []}), - | "nulls": pd.DataFrame({"score": [None, None]}), - |} - | - |for name, frame in cases.items(): - | directory = tempfile.mkdtemp() - | scope = { - | "in1df": frame, - | "outputHtml": directory + "/chart.html", - | "outputJson": directory + "/chart.json", - | "pd": pd, - | } - | exec(compile(source, "standalone", "exec"), scope) - | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8") - | if "General error" in page: - | verdict = "GENERAL_ERROR" - | elif "Input table is empty" in page: - | verdict = "EMPTY" - | elif "No non-null rows" in page: - | verdict = "NO_ROWS" - | elif "Gauge chart is not available" in page: - | verdict = "OTHER_PAGE" - | else: - | verdict = "CHART" - | print("CASE %s %s" % (name, verdict)) - |""".stripMargin } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDescSpec.scala index fe234489ff0..4b4662a58ff 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/heatMap/HeatMapOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.heatMap -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -47,13 +46,7 @@ class HeatMapOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "HeatMapOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { val op = configured - val schemas = op.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe op.operatorInfo.outputPorts.head.id - schema.getAttributes should have length 1 - schema.getAttributes.head.getName shouldBe "html-content" - schema.getAttributes.head.getType shouldBe AttributeType.STRING + assertHtmlOutputSchema(op) } "HeatMapOpDesc.generatePythonCode" should "render a UDFTableOperator source with three runtime decode sites for x/y/value" in { @@ -68,23 +61,20 @@ class HeatMapOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { it should "throw AssertionError naming the X column when everything is empty" in { val op = new HeatMapOpDesc - val ex = expectError[AssertionError]("cannot be empty")(op.generatePythonCode()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(op.generatePythonCode()) } it should "throw AssertionError naming the Y column when only x is set" in { val op = new HeatMapOpDesc op.x = "ax" - val ex = expectError[AssertionError]("cannot be empty")(op.generatePythonCode()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(op.generatePythonCode()) } it should "throw AssertionError naming the Values column when x and y are set" in { val op = new HeatMapOpDesc op.x = "ax" op.y = "ay" - val ex = expectError[AssertionError]("cannot be empty")(op.generatePythonCode()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(op.generatePythonCode()) } it should "carry the configured x/y/value columns (as runtime decode payloads) in the generated code" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDescSpec.scala index abbea350513..53e3f414aa6 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/hierarchychart/HierarchyChartOpDescSpec.scala @@ -45,13 +45,11 @@ class HierarchyChartOpDescSpec } it should "throw AssertionError naming the Value Column when value is left empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(opDesc.manipulateTable()) } it should "throw AssertionError naming the hierarchy when the hierarchy path is empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("hierarchy") + expectEmptyFieldError("hierarchy")(opDesc.createPlotlyFigure()) } it should "render hierarchy attributes and the value column when fully configured" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDescSpec.scala index d73ab8bccdf..7feacba3eac 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram/HistogramChartOpDescSpec.scala @@ -40,8 +40,7 @@ class HistogramChartOpDescSpec } it should "throw AssertionError naming the Value Column when value is left empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(opDesc.createPlotlyFigure()) } it should "throw AssertionError with a non-blank message via generatePythonCode when value is empty" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDescSpec.scala index 2da2d35f264..8ea5d6d3096 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/histogram2d/Histogram2DOpDescSpec.scala @@ -25,17 +25,17 @@ import org.apache.texera.amber.util.PythonTestSupport.{ configuredPython, runSource } -import org.apache.texera.amber.core.tuple.{AttributeType, Schema} +import org.apache.texera.amber.core.tuple.Schema import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.pyStringLiteral import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks import java.nio.file.Files -class Histogram2DOpDescSpec extends AnyFlatSpec with Matchers { +class Histogram2DOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { private def configured(): Histogram2DOpDesc = { val d = new Histogram2DOpDesc @@ -65,10 +65,9 @@ class Histogram2DOpDescSpec extends AnyFlatSpec with Matchers { "Histogram2DOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new Histogram2DOpDesc - val out = op.getOutputSchemas(Map(op.operatorInfo.inputPorts.head.id -> Schema())) - out shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas( + Map(op.operatorInfo.inputPorts.head.id -> Schema()) + ) shouldBe expectedHtmlOutputSchema(op) } "Histogram2DOpDesc.generatePythonCode" should "reject a non-positive bin count" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDescSpec.scala index c1483365ebe..370ca2b541f 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/lineChart/LineChartOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.lineChart -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -58,13 +57,7 @@ class LineChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks "LineChartOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { val op = configured - val schemas = op.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe op.operatorInfo.outputPorts.head.id - schema.getAttributes should have length 1 - schema.getAttributes.head.getName shouldBe "html-content" - schema.getAttributes.head.getType shouldBe AttributeType.STRING + assertHtmlOutputSchema(op) } "LineChartOpDesc.generatePythonCode" should "render Python source with runtime decode sites for both labels" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDescSpec.scala index 7fc97d1ad41..26c50f4cb01 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/networkGraph/NetworkGraphOpDescSpec.scala @@ -35,20 +35,17 @@ class NetworkGraphOpDescSpec } it should "throw AssertionError naming the Source Column when both fields are empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("source") + expectEmptyFieldError("source")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Destination Column when only source is set" in { opDesc.source = "from_node" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("destination") + expectEmptyFieldError("destination")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Source Column when only destination is set" in { opDesc.destination = "to_node" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("source") + expectEmptyFieldError("source")(opDesc.manipulateTable()) } it should "render both configured columns when source and destination are set" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDescSpec.scala index 61ac9755e75..7bc0ba2f66b 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/parallelCoordinatesPlot/ParallelCoordinatesPlotOpDescSpec.scala @@ -19,14 +19,13 @@ package org.apache.texera.amber.operator.visualization.parallelCoordinatesPlot -import org.apache.texera.amber.core.tuple.{AttributeType, Schema} import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks -class ParallelCoordinatesPlotOpDescSpec extends AnyFlatSpec with Matchers { +class ParallelCoordinatesPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "ParallelCoordinatesPlotOpDesc.operatorInfo" should "advertise the name and Scientific visualization group" in { @@ -45,9 +44,7 @@ class ParallelCoordinatesPlotOpDescSpec extends AnyFlatSpec with Matchers { "ParallelCoordinatesPlotOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new ParallelCoordinatesPlotOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "ParallelCoordinatesPlotOpDesc.generatePythonCode" should diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDescSpec.scala index 75660a07154..f4be0b0b588 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/polarChart/PolarChartOpDescSpec.scala @@ -19,20 +19,15 @@ package org.apache.texera.amber.operator.visualization.polarChart -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} -import org.apache.texera.amber.core.tuple.{AttributeType, Schema} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.verifyStandaloneChartCases +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers -class PolarChartOpDescSpec extends AnyFlatSpec with Matchers { +class PolarChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "PolarChartOpDesc.operatorInfo" should "advertise the name and Scientific visualization group" in { @@ -53,9 +48,7 @@ class PolarChartOpDescSpec extends AnyFlatSpec with Matchers { "PolarChartOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new PolarChartOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "PolarChartOpDesc.generatePythonCode" should "emit a Plotly Scatterpolargl figure" in { @@ -83,78 +76,34 @@ class PolarChartOpDescSpec extends AnyFlatSpec with Matchers { // np.issubdtype cannot interpret; the check must draw them, not raise. "PolarChartOpDesc.generateStandaloneCode" should "draw nullable numeric columns and refuse non-numeric ones" taggedAs NeedsPythonPackages in { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - val d = new PolarChartOpDesc d.r = "r" d.theta = "theta" - withDriver( - python, - "polar_standalone_", - "polar_driver_", + verifyStandaloneChartCases( + "polar", d.generateStandaloneCode(), - driverScript, - "Polar driver timed out after 120s" - ) { (exitCode, output) => - withClue(s"Driver output:\n$output\n") { - exitCode shouldBe 0 - val verdicts = "CASE (\\S+) (\\S+)".r - .findAllMatchIn(output) - .map(m => m.group(1) -> m.group(2)) - .toMap - verdicts shouldBe Map( - "numpy" -> "CHART", - "nullable" -> "CHART", - "boolean" -> "NOT_NUMERIC", - "text" -> "NOT_NUMERIC" - ) - } - } + casesScript = """cases = { + | "numpy": pd.DataFrame({"r": [1, 2], "theta": [0, 90]}), + | "nullable": pd.DataFrame( + | {"r": pd.array([1, 2], dtype="Int64"), "theta": pd.array([0, 90], dtype="Int64")} + | ), + | "boolean": pd.DataFrame({"r": [True, False], "theta": [0, 90]}), + | "text": pd.DataFrame({"r": [1, 2], "theta": ["a", "b"]}), + |}""".stripMargin, + verdictBody = """ if "Selected columns must be numeric" in page: + | verdict = "NOT_NUMERIC" + | elif "Reason is: " - withClue(s"Driver output:\n$output\n") { - exitCode shouldBe 0 - output should include(s"CASE empty ${page}input table is empty.
") - output should include( - s"CASE every_row_holed ${page}value column contains only non-positive numbers or nulls." - ) - output should include("CASE filled CHART") - } - } + "Tables Plot" + ) } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDescSpec.scala index 6e6c3357c1d..32d98458e77 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryContour/TernaryContourOpDescSpec.scala @@ -44,32 +44,28 @@ class TernaryContourOpDescSpec opDesc.secondVariable = "var_b" opDesc.thirdVariable = "var_c" opDesc.fourthVariable = "var_d" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("1") + expectEmptyFieldError("1")(opDesc.manipulateTable()) } it should "throw AssertionError naming Variable 2 when only it is missing" in { opDesc.firstVariable = "var_a" opDesc.thirdVariable = "var_c" opDesc.fourthVariable = "var_d" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("2") + expectEmptyFieldError("2")(opDesc.manipulateTable()) } it should "throw AssertionError naming Variable 3 when only it is missing" in { opDesc.firstVariable = "var_a" opDesc.secondVariable = "var_b" opDesc.fourthVariable = "var_d" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("3") + expectEmptyFieldError("3")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Measured Value when only it is missing" in { opDesc.firstVariable = "var_a" opDesc.secondVariable = "var_b" opDesc.thirdVariable = "var_c" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("measured value") + expectEmptyFieldError("measured value")(opDesc.manipulateTable()) } it should "render all four configured variables when set" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDescSpec.scala index d544e6d7469..74671f6fdfc 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ternaryPlot/TernaryPlotOpDescSpec.scala @@ -43,22 +43,19 @@ class TernaryPlotOpDescSpec it should "throw AssertionError naming Variable 1 when only it is missing" in { opDesc.secondVariable = "var_b" opDesc.thirdVariable = "var_c" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("1") + expectEmptyFieldError("1")(opDesc.manipulateTable()) } it should "throw AssertionError naming Variable 2 when only it is missing" in { opDesc.firstVariable = "var_a" opDesc.thirdVariable = "var_c" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("2") + expectEmptyFieldError("2")(opDesc.manipulateTable()) } it should "throw AssertionError naming Variable 3 when only it is missing" in { opDesc.firstVariable = "var_a" opDesc.secondVariable = "var_b" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("3") + expectEmptyFieldError("3")(opDesc.manipulateTable()) } it should "render all three configured variables when set" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDescSpec.scala index fe2fb7dfb95..009e836f43b 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/treeplot/TreePlotOpDescSpec.scala @@ -19,12 +19,8 @@ package org.apache.texera.amber.operator.visualization.treeplot -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.withPytexeraTableDriver +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -62,33 +58,8 @@ class TreePlotOpDescSpec extends AnyFlatSpec with BeforeAndAfter with GeneratedC // Driver executed by the runtime test below. It stubs only the pytexera import seam; // the generated module runs unmodified, and the layout is called directly so the // positions it computes are what is read, rather than a rendered picture. - private val runtimeDriverScript: String = - """import base64 - |import sys - |import types - |from typing import Iterator, Optional - | - |import pandas as pd - | - |class UDFTableOperator: - | def decode_python_template(self, data): - | return base64.b64decode(data).decode("utf-8") - | - |stub = types.ModuleType("pytexera") - |stub.UDFTableOperator = UDFTableOperator - |stub.overrides = lambda fn: fn - |stub.Table = pd.DataFrame - |stub.TableLike = object - |stub.Iterator = Iterator - |stub.Optional = Optional - |sys.modules["pytexera"] = stub - | - |ns = {"__name__": "generated_tree_plot"} - |with open(sys.argv[1], encoding="utf-8") as f: - | exec(compile(f.read(), sys.argv[1], "exec"), ns) - |op = ns["ProcessTableOperator"]() - | - |cases = [ + private val runtimeDriverBody: String = + """cases = [ | ("tree", [("a", "b"), ("a", "c"), ("b", "d"), ("b", "e")]), | ("shared", [("a", "c"), ("b", "c")]), | ("cycle", [("a", "b"), ("b", "c"), ("c", "a")]), @@ -101,28 +72,20 @@ class TreePlotOpDescSpec extends AnyFlatSpec with BeforeAndAfter with GeneratedC | placed = " ".join( | "%s=%g,%g" % (label, x, y) for label, (x, y) in zip(labels, coords) | ) - | print("CASE %s %s" % (cid, placed)) - |""".stripMargin + | print("CASE %s %s" % (cid, placed))""".stripMargin /** `label -> (x, y)` per case, read out of the driver's output. One run for the * whole suite: the driver lays every case out in the same process. */ private lazy val layouts: Map[String, Map[String, (Double, Double)]] = { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - opDesc.edgeListColumn = "edge_pairs" - withDriver( - python, - "tree_plot_op_", - "tree_plot_driver_", + withPytexeraTableDriver( + "tree_plot", opDesc.generatePythonCode(), - runtimeDriverScript, - "Layout driver timed out after 120s" + "generated_tree_plot", + "ProcessTableOperator", + runtimeDriverBody, + timeoutMessage = "Layout driver timed out after 120s" ) { (exitCode, output) => withClue(s"Driver output:\n$output\n") { exitCode shouldBe 0 diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/volcanoPlot/VolcanoPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/volcanoPlot/VolcanoPlotOpDescSpec.scala index a31641bd503..fee910f3399 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/volcanoPlot/VolcanoPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/volcanoPlot/VolcanoPlotOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.volcanoPlot -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, OperatorMetadataGenerator} import org.apache.texera.amber.util.JSONUtils.objectMapper @@ -35,6 +34,63 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck op } + private def configured(init: VolcanoPlotOpDesc => Unit): VolcanoPlotOpDesc = { + val op = configured + init(op) + op + } + + private def withThresholds( + sig: Option[Double] = Some(0.05), + eff: Option[Double] = Some(1.0), + color: Boolean = true + ): VolcanoPlotOpDesc = + configured { op => + op.significanceThreshold = sig + op.effectSizeThreshold = eff + op.colorBySignificance = color + } + + private def assertBlankHoverIgnored(render: VolcanoPlotOpDesc => String): Unit = + Seq(" ", "\t", " \n ").foreach(b => + render(configured(_.hoverName = b)) shouldBe render(configured) + ) + + private def assertBlankLabelsIgnored(render: VolcanoPlotOpDesc => String): Unit = + render(configured { op => op.title = " "; op.xLabel = "\t"; op.yLabel = " \n " }) shouldBe + render(configured) + + private def assertLabels( + code: String, + encode: String => String, + title: String, + xLabel: String, + yLabel: String + ): Unit = { + code should include(s"title=${encode(title)}") + code should include(s"xaxis_title=${encode(xLabel)}") + code should include(s"yaxis_title=${encode(yLabel)}") + // The color bar follows the x label, since both show the effect column. + code should include(s"coloraxis_colorbar_title_text=${encode(xLabel)}") + } + + private def assertDefaultLabelsAbsent(code: String, encode: String => String): Unit = + Seq( + s"title=${encode("Volcano Plot")}", + s"xaxis_title=${encode("log2fc")}", + s"yaxis_title=${encode("-log10(pvalue)")}", + s"coloraxis_colorbar_title_text=${encode("log2fc")}" + ).foreach(code should not include _) + + private def pyLiteral(s: String): String = + "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + + private val customTitle = "TITLE_SENT \"quoted\" 火山" + private val customXLabel = "X_LBL_SENT log₂ fold change" + private val customYLabel = "Y_LBL_SENT -log₁₀(BH-adjusted p) \\ back\\slash" + private def withCustomLabels: VolcanoPlotOpDesc = + configured { op => op.title = customTitle; op.xLabel = customXLabel; op.yLabel = customYLabel } + private val hline = """fig.add_hline(y=-np.log10(0.05), line_dash="dash", line_color="gray")""" private val vlines = """fig.add_vline(x=1.0, line_dash="dash", line_color="gray") @@ -77,13 +133,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck "VolcanoPlotOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { val op = configured - val schemas = op.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe op.operatorInfo.outputPorts.head.id - schema.getAttributes should have length 1 - schema.getAttributes.head.getName shouldBe "html-content" - schema.getAttributes.head.getType shouldBe AttributeType.STRING + assertHtmlOutputSchema(op) } "VolcanoPlotOpDesc.generatePythonCode" should "render a UDFTableOperator source that decodes both column references" in { @@ -111,25 +161,17 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck it should "answer a set hover column that the table lacks with the operator's error page" in { // Like the two required columns, and unlike plotly's uncaught ValueError. - val op = configured - op.hoverName = "gene" - val code = op.generatePythonCode() + val code = configured(_.hoverName = "gene").generatePythonCode() code should include(s"if ${decoded("gene")} not in table.columns:") code should include("""self.render_error("Missing hover column in table.")""") } it should "treat a whitespace-only hover column as empty" in { - Seq(" ", "\t", " \n ").foreach { blank => - val op = configured - op.hoverName = blank - op.generatePythonCode() shouldBe configured.generatePythonCode() - } + assertBlankHoverIgnored(_.generatePythonCode()) } it should "use the configured hover column instead of the first column" in { - val op = configured - op.hoverName = "gene" - val code = op.generatePythonCode() + val code = configured(_.hoverName = "gene").generatePythonCode() code should include(s"hover_name=${decoded("gene")},") code should not include "hover_name=table.columns[0]" // Exactly two decode sites more than the default: the presence check and the @@ -138,10 +180,9 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "route a hover column with quotes and non-ASCII text through the decoder" in { - val op = configured - op.hoverName = "HOVER_SENT \"gene\" 基因" - val code = op.generatePythonCode() - code should include(s"hover_name=${decoded(op.hoverName)},") + val hover = "HOVER_SENT \"gene\" 基因" + val code = configured(_.hoverName = hover).generatePythonCode() + code should include(s"hover_name=${decoded(hover)},") code should not include "HOVER_SENT" } @@ -153,10 +194,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "draw both cut-offs while keeping the continuous coloring when the toggle is off" in { - val op = configured - op.significanceThreshold = Some(0.05) - op.effectSizeThreshold = Some(1.0) - val code = op.generatePythonCode() + val code = withThresholds(color = false).generatePythonCode() code should include(hline) code should include(vlines) assertContinuousColoring(code) @@ -164,11 +202,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck it should "skip a significance threshold that has no -log10 (zero or negative)" in { Seq(0.0, -0.01).foreach { bad => - val op = configured - op.significanceThreshold = Some(bad) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds(sig = Some(bad)).generatePythonCode() code should not include "add_hline" code should not include "np.log10(0.0)" code should not include "np.log10(-0.01)" @@ -183,11 +217,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck // A negative cut-off would flip the Up and Down comparisons and call small // effects significant; zero is the same boundary and is ruled out too. Seq(0.0, -1.0).foreach { bad => - val op = configured - op.significanceThreshold = Some(0.05) - op.effectSizeThreshold = Some(bad) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds(eff = Some(bad)).generatePythonCode() code should not include "add_vline" code should include(hline) assertContinuousColoring(code) @@ -195,22 +225,14 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "skip a significance threshold above one, whose line would sit below the axis" in { - val op = configured - op.significanceThreshold = Some(2.0) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds(sig = Some(2.0)).generatePythonCode() code should not include "add_hline" code should include(vlines) assertContinuousColoring(code) } it should "color Up, Down and Not significant when both thresholds are set and the toggle is on" in { - val op = configured - op.significanceThreshold = Some(0.05) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds().generatePythonCode() // Strict comparisons on the selected p-value column and the effect column: // a point exactly on a cut-off is not significant. code should include("significant = table[self.decode_python_template(") @@ -235,11 +257,8 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck // of that name before px reads the table; as the effect column, the x axis would // show the category labels. Labelling the category column Significance as well would // give two hover lines one label, and px would show only one of them. - val op = configured + val op = withThresholds() op.effectColumn = "Significance" - op.significanceThreshold = Some(0.05) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true Seq(op.generatePythonCode(), op.generateStandaloneCode()).foreach { code => code should not include """table["Significance"] =""" code should include(categoryColumn) @@ -254,11 +273,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "accept a significance threshold of exactly one, the schema maximum, and draw it at y = 0" in { - val op = configured - op.significanceThreshold = Some(1.0) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds(sig = Some(1.0)).generatePythonCode() code should include("""fig.add_hline(y=-np.log10(1.0), line_dash="dash", line_color="gray")""") code should include(vlines) code should include("color=significance_column,") @@ -275,11 +290,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck (java.lang.Double.MIN_VALUE, 1.0, "4.9E-324", "1.0") ).foreach { case (sig, eff, sigLit, effLit) => - val op = configured - op.significanceThreshold = Some(sig) - op.effectSizeThreshold = Some(eff) - op.colorBySignificance = true - val code = op.generatePythonCode() + val code = withThresholds(sig = Some(sig), eff = Some(eff)).generatePythonCode() val literals = emittedLiterals .findAllMatchIn(code) .map(m => Option(m.group(1)).getOrElse(m.group(2))) @@ -294,33 +305,23 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "fall back to the continuous coloring when the toggle is on but a threshold is missing" in { - val onlySignificance = configured - onlySignificance.significanceThreshold = Some(0.05) - onlySignificance.colorBySignificance = true - val sigCode = onlySignificance.generatePythonCode() + val sigCode = withThresholds(eff = None).generatePythonCode() sigCode should include(hline) sigCode should not include "add_vline" assertContinuousColoring(sigCode) - val onlyEffect = configured - onlyEffect.effectSizeThreshold = Some(1.0) - onlyEffect.colorBySignificance = true - val effCode = onlyEffect.generatePythonCode() + val effCode = withThresholds(sig = None).generatePythonCode() effCode should include(vlines) effCode should not include "add_hline" assertContinuousColoring(effCode) - val neither = configured - neither.colorBySignificance = true - assertContinuousColoring(neither.generatePythonCode()) + assertContinuousColoring(withThresholds(sig = None, eff = None).generatePythonCode()) } it should "name the y column and its axis after the selected p-value column" in { // The y axis used to read "-log10(pvalue)" whatever column was chosen; a // figure drawn from an adjusted column must say so. - val op = configured - op.pvalueColumn = "padj" - val code = op.generatePythonCode() + val code = configured(_.pvalueColumn = "padj").generatePythonCode() code should include(s"table[${decoded("-log10(padj)")}] = -np.log10(") code should include(s"y=${decoded("-log10(padj)")}") code should include(s"yaxis_title=${decoded("-log10(padj)")}") @@ -329,66 +330,42 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "fall back to the column-derived labels when no label is set" in { - val code = configured.generatePythonCode() - code should include(s"title=${decoded("Volcano Plot")}") - code should include(s"xaxis_title=${decoded("log2fc")}") - code should include(s"yaxis_title=${decoded("-log10(pvalue)")}") - code should include(s"coloraxis_colorbar_title_text=${decoded("log2fc")}") + assertLabels( + configured.generatePythonCode(), + decoded, + "Volcano Plot", + "log2fc", + "-log10(pvalue)" + ) } it should "route every configured label through the decoder instead of the default" in { // Sentinels with quotes, a backslash and non-ASCII text: as decode sites // they cannot break the Python source, and the raw text must never // appear in it. - val op = configured - op.title = "TITLE_SENT \"quoted\" 火山" - op.xLabel = "X_LBL_SENT log₂ fold change" - op.yLabel = "Y_LBL_SENT -log₁₀(BH-adjusted p) \\ back\\slash" - val code = op.generatePythonCode() - code should include(s"title=${decoded(op.title)}") - code should include(s"xaxis_title=${decoded(op.xLabel)}") - code should include(s"yaxis_title=${decoded(op.yLabel)}") - // The color bar follows the x label, since both show the effect column. - code should include(s"coloraxis_colorbar_title_text=${decoded(op.xLabel)}") - Seq(op.title, op.xLabel, op.yLabel).foreach { sentinel => - code should not include sentinel - } + val code = withCustomLabels.generatePythonCode() + assertLabels(code, decoded, customTitle, customXLabel, customYLabel) + Seq(customTitle, customXLabel, customYLabel).foreach(code should not include _) // A set label replaces the default rather than being emitted next to it. code should not include b64("Volcano Plot") - code should not include s"xaxis_title=${decoded("log2fc")}" - code should not include s"yaxis_title=${decoded("-log10(pvalue)")}" - code should not include s"coloraxis_colorbar_title_text=${decoded("log2fc")}" + assertDefaultLabelsAbsent(code, decoded) // The y column itself keeps the derived name: a label is text on the axis, // not a column rename. code should include(s"y=${decoded("-log10(pvalue)")}") } it should "treat a whitespace-only label as empty and keep the default" in { - val op = configured - op.title = " " - op.xLabel = "\t" - op.yLabel = " \n " - op.generatePythonCode() shouldBe configured.generatePythonCode() + assertBlankLabelsIgnored(_.generatePythonCode()) } it should "treat each label independently so one set label leaves the others at their default" in { - val op = configured - op.yLabel = "Y_ONLY_SENT" - val code = op.generatePythonCode() - code should include(s"yaxis_title=${decoded("Y_ONLY_SENT")}") - code should include(s"title=${decoded("Volcano Plot")}") - code should include(s"xaxis_title=${decoded("log2fc")}") - code should include(s"coloraxis_colorbar_title_text=${decoded("log2fc")}") + val code = configured(_.yLabel = "Y_ONLY_SENT").generatePythonCode() + assertLabels(code, decoded, "Volcano Plot", "log2fc", "Y_ONLY_SENT") } it should "render a workflow saved before this change exactly as a default-constructed operator" in { - val saved = objectMapper - .readValue( - """{"operatorType":"VolcanoPlot","effectColumn":"log2fc","pvalueColumn":"pvalue"}""", - classOf[LogicalOp] - ) - .asInstanceOf[VolcanoPlotOpDesc] - saved.generatePythonCode() shouldBe configured.generatePythonCode() + readOp(""","effectColumn":"log2fc","pvalueColumn":"pvalue"""").generatePythonCode() shouldBe + configured.generatePythonCode() } "VolcanoPlotOpDesc.generateStandaloneCode" should "keep the first column as the hover label when no hover column is set" in { @@ -398,9 +375,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "use the configured hover column as a literal and check that the table has it" in { - val op = configured - op.hoverName = "gene" - val code = op.generateStandaloneCode() + val code = configured(_.hoverName = "gene").generateStandaloneCode() code should include("""hover_name="gene",""") code should not include "hover_name=table.columns[0]" // One more branch of the script's column checks, before the row filter and @@ -418,22 +393,17 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck it should "escape a hover column with quotes or a backslash rather than decode it" in { // The export has no decoder, so the name itself is in the script: a quote or a // backslash must come out escaped, or the literal would end early. - val op = configured - op.hoverName = "HOVER_SENT \"gene\" 基因" - val code = op.generateStandaloneCode() + val code = configured(_.hoverName = "HOVER_SENT \"gene\" 基因").generateStandaloneCode() code should include("hover_name=\"HOVER_SENT \\\"gene\\\" 基因\",") code should include("elif \"HOVER_SENT \\\"gene\\\" 基因\" not in in1df.columns:") code should not include "decode_python_template" - op.hoverName = "gene\\id" - op.generateStandaloneCode() should include("hover_name=\"gene\\\\id\",") + configured(_.hoverName = "gene\\id").generateStandaloneCode() should include( + "hover_name=\"gene\\\\id\"," + ) } it should "treat a whitespace-only hover column as empty" in { - Seq(" ", "\t", " \n ").foreach { blank => - val op = configured - op.hoverName = blank - op.generateStandaloneCode() shouldBe configured.generateStandaloneCode() - } + assertBlankHoverIgnored(_.generateStandaloneCode()) } it should "draw no cut-off line and keep the continuous effect-size coloring by default" in { @@ -445,11 +415,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "color Up, Down and Not significant with the column names as literals" in { - val op = configured - op.significanceThreshold = Some(0.05) - op.effectSizeThreshold = Some(1.0) - op.colorBySignificance = true - val code = op.generateStandaloneCode() + val code = withThresholds().generateStandaloneCode() code should include("""significant = table["pvalue"] < 0.05""") code should include( """[significant & (table["log2fc"] > 1.0), significant & (table["log2fc"] < -1.0)]""" @@ -480,10 +446,7 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck (Some(1e-300), Some(1e21), true) ).foreach { case (sig, eff, toggle) => - val op = configured - op.significanceThreshold = sig - op.effectSizeThreshold = eff - op.colorBySignificance = toggle + val op = withThresholds(sig, eff, toggle) val engine = op.generatePythonCode() val export = op.generateStandaloneCode() cutOffLine.findAllIn(export).toSeq shouldBe cutOffLine.findAllIn(engine).toSeq @@ -492,58 +455,42 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck } it should "name the y column and its axis after the selected p-value column" in { - val op = configured - op.pvalueColumn = "padj" - val code = op.generateStandaloneCode() + val code = configured(_.pvalueColumn = "padj").generateStandaloneCode() code should include("""table["-log10(padj)"] = -np.log10(table["padj"])""") code should include("""y="-log10(padj)",""") code should include("""yaxis_title="-log10(padj)",""") code should not include "-log10(pvalue)" // The derived y column is the one literal built from a column name rather than // taken from a field, so a quote in that name must survive the wrap and the escape. - op.pvalueColumn = "p\"adj" - val quoted = op.generateStandaloneCode() + val quoted = configured(_.pvalueColumn = "p\"adj").generateStandaloneCode() quoted should include("table[\"-log10(p\\\"adj)\"] = -np.log10(table[\"p\\\"adj\"])") quoted should include("yaxis_title=\"-log10(p\\\"adj)\",") } it should "fall back to the column-derived labels when no label is set" in { - val code = configured.generateStandaloneCode() - code should include("""title="Volcano Plot"""") - code should include("""xaxis_title="log2fc",""") - code should include("""yaxis_title="-log10(pvalue)",""") - code should include("""coloraxis_colorbar_title_text="log2fc"""") + assertLabels( + configured.generateStandaloneCode(), + pyLiteral, + "Volcano Plot", + "log2fc", + "-log10(pvalue)" + ) } it should "emit every configured label as an escaped Python literal" in { // The export has no decoder, so the text itself is in the script: a quote or // a backslash must come out escaped, or the label would end the literal early. - val op = configured - op.title = "TITLE_SENT \"quoted\" 火山" - op.xLabel = "X_LBL_SENT log₂ fold change" - op.yLabel = "Y_LBL_SENT -log₁₀(BH-adjusted p) \\ back\\slash" - val code = op.generateStandaloneCode() - code should include("title=\"TITLE_SENT \\\"quoted\\\" 火山\"") - code should include("xaxis_title=\"X_LBL_SENT log₂ fold change\",") - code should include("yaxis_title=\"Y_LBL_SENT -log₁₀(BH-adjusted p) \\\\ back\\\\slash\",") - // The color bar follows the x label, since both show the effect column. - code should include("coloraxis_colorbar_title_text=\"X_LBL_SENT log₂ fold change\"") + val code = withCustomLabels.generateStandaloneCode() + assertLabels(code, pyLiteral, customTitle, customXLabel, customYLabel) // A set label replaces the default rather than being emitted next to it. - code should not include """title="Volcano Plot"""" - code should not include """xaxis_title="log2fc"""" - code should not include """yaxis_title="-log10(pvalue)"""" - code should not include """coloraxis_colorbar_title_text="log2fc"""" + assertDefaultLabelsAbsent(code, pyLiteral) // The y column itself keeps the derived name: a label is text on the axis, // not a column rename. code should include("""y="-log10(pvalue)",""") } it should "treat a whitespace-only label as empty and keep the default" in { - val op = configured - op.title = " " - op.xLabel = "\t" - op.yLabel = " \n " - op.generateStandaloneCode() shouldBe configured.generateStandaloneCode() + assertBlankLabelsIgnored(_.generateStandaloneCode()) } /** Reads the shapes a stored workflow can hold. Without `contentAs` a JSON string @@ -554,27 +501,38 @@ class VolcanoPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionCheck .readValue(s"""{"operatorType":"VolcanoPlot"$json}""", classOf[LogicalOp]) .asInstanceOf[VolcanoPlotOpDesc] + private def assertThresholds( + json: String, + expectedSig: Option[Double], + expectedEff: Option[Double] + ): Unit = { + val op = readOp(json) + op.significanceThreshold shouldBe expectedSig + op.effectSizeThreshold shouldBe expectedEff + } + "VolcanoPlotOpDesc thresholds" should "deserialize JSON numbers" in { - val op = readOp(""","significanceThreshold":0.05,"effectSizeThreshold":1""") - op.significanceThreshold shouldBe Some(0.05) - op.effectSizeThreshold shouldBe Some(1.0) + assertThresholds( + ""","significanceThreshold":0.05,"effectSizeThreshold":1""", + Some(0.05), + Some(1.0) + ) } it should "deserialize numeric strings" in { - val op = readOp(""","significanceThreshold":"0.05","effectSizeThreshold":"1.5"""") - op.significanceThreshold shouldBe Some(0.05) - op.effectSizeThreshold shouldBe Some(1.5) + assertThresholds( + ""","significanceThreshold":"0.05","effectSizeThreshold":"1.5"""", + Some(0.05), + Some(1.5) + ) } it should "read an absent, null or blank value as unset rather than as zero" in { - readOp("").significanceThreshold shouldBe None - readOp("").effectSizeThreshold shouldBe None - val nulls = readOp(""","significanceThreshold":null,"effectSizeThreshold":null""") - nulls.significanceThreshold shouldBe None - nulls.effectSizeThreshold shouldBe None - val blanks = readOp(""","significanceThreshold":"","effectSizeThreshold":""""") - blanks.significanceThreshold shouldBe None - blanks.effectSizeThreshold shouldBe None + Seq( + "", + ""","significanceThreshold":null,"effectSizeThreshold":null""", + ""","significanceThreshold":"","effectSizeThreshold":""""" + ).foreach(assertThresholds(_, None, None)) } it should "treat a non-finite value read from JSON as unset so no Infinity or NaN reaches the Python" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDescSpec.scala index d93393508f5..8914ba75826 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/waterfallChart/WaterfallChartOpDescSpec.scala @@ -19,12 +19,8 @@ package org.apache.texera.amber.operator.visualization.waterfallChart -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.withPytexeraTableDriver +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -92,37 +88,8 @@ class WaterfallChartOpDescSpec // Driver executed by the runtime test below. It stubs only the pytexera import seam and // swaps plotly's html renderer for its json one, so the trace the generated module hands // plotly can be read back bar by bar. - private val runtimeDriverScript: String = - """import base64 - |import json - |import sys - |import types - |from typing import Iterator, Optional - | - |import pandas as pd - |import plotly.io - | - |plotly.io.to_html = lambda fig, **kwargs: fig.to_json() - | - |class UDFTableOperator: - | def decode_python_template(self, data): - | return base64.b64decode(data).decode("utf-8") - | - |stub = types.ModuleType("pytexera") - |stub.UDFTableOperator = UDFTableOperator - |stub.overrides = lambda fn: fn - |stub.Table = pd.DataFrame - |stub.TableLike = object - |stub.Iterator = Iterator - |stub.Optional = Optional - |sys.modules["pytexera"] = stub - | - |ns = {"__name__": "generated_waterfall_chart"} - |with open(sys.argv[1], encoding="utf-8") as f: - | exec(compile(f.read(), sys.argv[1], "exec"), ns) - |op = ns["ProcessTableOperator"]() - | - |cases = [ + private val runtimeDriverBody: String = + """cases = [ | ("labels", pd.DataFrame({"x_col": ["a", "b", "c", "d"], "y_col": [1, 2, 3, 4]})), | ("unsorted_numeric_x", pd.DataFrame({"x_col": [30, 10, 20], "y_col": [1, 2, 3]})), |] @@ -137,24 +104,20 @@ class WaterfallChartOpDescSpec | json.dumps(list(trace["y"])), | json.dumps(list(trace["text"])), | fig["layout"]["xaxis"]["type"], - | )) - |""".stripMargin + | ))""".stripMargin it should "plot the last row and draw the total over the whole column at runtime" taggedAs NeedsPythonPackages in { - val python = configuredPython().getOrElse( - cancel("No runnable python executable (udf.conf python.path, python3, python, py)") - ) - if (!canImport(python, "pandas", "plotly")) { - cancel(s"'$python' cannot import pandas and plotly; skipping runtime verification") - } - - withDriver( - python, - "waterfall_chart_op_", - "waterfall_chart_driver_", + withPytexeraTableDriver( + "waterfall_chart", configured().generatePythonCode(), - runtimeDriverScript, - "Runtime verification driver timed out after 120s" + "generated_waterfall_chart", + "ProcessTableOperator", + runtimeDriverBody, + setupCode = """import json + |import plotly.io + | + |plotly.io.to_html = lambda fig, **kwargs: fig.to_json()""".stripMargin, + timeoutMessage = "Runtime verification driver timed out after 120s" ) { (exitCode, output) => withClue(s"Driver output:\n$output\n") { exitCode shouldBe 0