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 "` lines emitted by Python chart test drivers. */ + def parseCaseVerdicts(output: String): Map[String, String] = + "CASE (\\S+) (\\S+)".r + .findAllMatchIn(output) + .map(m => m.group(1) -> m.group(2)) + .toMap + + /** Runs a generated operator module inside a minimal stubbed `pytexera` environment and + * executes `driverBody` with the instantiated operator bound to `op`. + */ + def withPytexeraTableDriver[A]( + prefix: String, + generatedCode: => String, + moduleName: String, + operatorClass: String, + driverBody: String, + setupCode: String = "", + timeoutMessage: String = "Runtime driver timed out after 120s" + )(check: (Int, String) => A): A = { + val python = requirePython("pandas", "plotly") + val setupBlock = if (setupCode.isEmpty) "" else setupCode + "\n\n" + val driver = + s"""import base64 + |import sys + |import types + |from typing import Iterator, Optional + | + |import pandas as pd + |${setupBlock}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__": "$moduleName"} + |with open(sys.argv[1], encoding="utf-8") as f: + | exec(compile(f.read(), sys.argv[1], "exec"), ns) + |op = ns["$operatorClass"]() + | + |$driverBody + |""".stripMargin + withDriver( + python, + s"${prefix}_op_", + s"${prefix}_driver_", + generatedCode, + driver, + timeoutMessage + )(check) + } + + /** Runs generated standalone chart code once per `cases` entry, classifies each rendered HTML + * output via `verdictBody` (assigning `verdict`), and asserts `parseCaseVerdicts(output)`. + * Each run reads back the page it wrote, so a branch that raises instead of answering shows up + * as a failure rather than as a missing file. + */ + def verifyStandaloneChartCases( + prefix: String, + standaloneCode: => String, + casesScript: String, + verdictBody: String, + expectedVerdicts: Map[String, String], + plotlyScopeBinding: Option[(String, String)] = None, + timeoutMessage: String = "Runtime driver timed out after 120s" + ): Unit = { + val python = requirePython("pandas", "plotly") + val plotlyImport = + plotlyScopeBinding.map { case (mod, alias) => s"import $mod as $alias\n" }.getOrElse("") + val plotlyScope = + plotlyScopeBinding + .map { case (_, alias) => "\n \"" + alias + "\": " + alias + "," } + .getOrElse("") + val driver = + s"""import pathlib + |import sys + |import tempfile + | + |import pandas as pd + |${plotlyImport} + |# 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") + | + |$casesScript + | + |for name, frame in cases.items(): + | directory = tempfile.mkdtemp() + | scope = { + | "in1df": frame, + | "outputHtml": directory + "/chart.html", + | "outputJson": directory + "/chart.json", + | "pd": pd,$plotlyScope + | } + | exec(compile(source, "standalone", "exec"), scope) + | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8").strip() + |$verdictBody + | print("CASE %s %s" % (name, verdict)) + |""".stripMargin + withDriver( + python, + s"${prefix}_standalone_", + s"${prefix}_driver_", + standaloneCode, + driver, + timeoutMessage + ) { (exitCode, output) => + withClue(s"Driver output:\n$output\n") { + exitCode shouldBe 0 + parseCaseVerdicts(output) shouldBe expectedVerdicts + } + } + } + + private val runtimeDriverBody: String = + """cases = [ + | ("empty", pd.DataFrame({"col_one": [], "col_two": []})), + | ("every_row_holed", pd.DataFrame({"col_one": [1.0, None], "col_two": [None, "b"]})), + | ("filled", pd.DataFrame({"col_one": [1, 2], "col_two": ["a", "b"]})), + |] + |for cid, df in cases: + | page = list(op.process_table(df, 0))[0]["html-content"] + | print("CASE %s %s" % (cid, page if "not available" in page else "CHART"))""".stripMargin + + def verifyTableChartCases(prefix: String, generatedCode: => String, title: String): Unit = { + withPytexeraTableDriver( + prefix, + generatedCode, + "generated_table_chart", + "TableChartOperator", + runtimeDriverBody + ) { (exitCode, output) => + val page = s"

$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") + } + } + } +} diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDescSpec.scala index 12831a0fc09..465c043ec19 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/IcicleChart/IcicleChartOpDescSpec.scala @@ -42,8 +42,7 @@ class IcicleChartOpDescSpec } 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 "throw AssertionError naming the Value Column in manipulateTable when value is left empty" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ImageViz/ImageVisualizerOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ImageViz/ImageVisualizerOpDescSpec.scala index 08c8930773f..b291e79ff67 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ImageViz/ImageVisualizerOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ImageViz/ImageVisualizerOpDescSpec.scala @@ -62,13 +62,7 @@ class ImageVisualizerOpDescSpec "ImageVisualizerOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { opDesc.binaryContent = "image_bytes" - val schemas = opDesc.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe opDesc.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(opDesc) } it should "throw AssertionError with a 'cannot be empty' message when binaryContent is an empty string" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDescSpec.scala index 71ed9835dcf..6fa92c9f801 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/barChart/BarChartOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.barChart -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.LogicalOp import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.apache.texera.amber.util.JSONUtils.objectMapper @@ -66,13 +65,7 @@ class BarChartOpDescSpec extends AnyFlatSpec with BeforeAndAfter with GeneratedC "BarChartOpDesc.getOutputSchemas" should "return a single-port schema with an html-content STRING column" in { opDesc.value = "v" opDesc.fields = "f" - val schemas = opDesc.getOutputSchemas(Map.empty) - schemas should have size 1 - val (portId, schema) = schemas.head - portId shouldBe opDesc.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(opDesc) } "BarChartOpDesc.generatePythonCode" should "render a UDFTableOperator source with runtime decode sites for value AND fields" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDescSpec.scala index d9ed4fc2aed..ae773887929 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bubbleChart/BubbleChartOpDescSpec.scala @@ -93,27 +93,23 @@ class BubbleChartOpDescSpec it should "throw AssertionError naming the X-Column when only xValue is missing" in { opDesc.yValue = "column2" opDesc.zValue = "column3" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.createPlotlyFigure()) } it should "throw AssertionError naming the Y-Column when only yValue is missing" in { opDesc.xValue = "column1" opDesc.zValue = "column3" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(opDesc.createPlotlyFigure()) } it should "throw AssertionError naming the Z-Column when only zValue is missing" in { opDesc.xValue = "column1" opDesc.yValue = "column2" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("z") + expectEmptyFieldError("z")(opDesc.createPlotlyFigure()) } it should "throw AssertionError with a per-field message in manipulateTable when fields are missing" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.manipulateTable()) } it should "render all three columns in manipulateTable when configured" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDescSpec.scala index 9f41638b8e2..9603cd4fc95 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/bulletChart/BulletChartOpDescSpec.scala @@ -19,15 +19,14 @@ package org.apache.texera.amber.operator.visualization.bulletChart -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.metadata.OperatorGroupConstants import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks import java.util import java.util.{List => JList} -class BulletChartOpDescSpec extends AnyFlatSpec with Matchers { +class BulletChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { private def configured: BulletChartOpDesc = { val op = new BulletChartOpDesc @@ -49,13 +48,7 @@ class BulletChartOpDescSpec extends AnyFlatSpec with Matchers { "BulletChartOpDesc.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) } "BulletChartOpDesc.generatePythonCode" should "render Python source with a runtime decode site for the value column" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDescSpec.scala index cdaabd3bc30..8fcc5e29aca 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/candlestickChart/CandlestickChartOpDescSpec.scala @@ -19,14 +19,14 @@ package org.apache.texera.amber.operator.visualization.candlestickChart -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.util.JSONUtils.objectMapper import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks -class CandlestickChartOpDescSpec extends AnyFlatSpec with Matchers { +class CandlestickChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { private def configured(): CandlestickChartOpDesc = { val d = new CandlestickChartOpDesc @@ -59,10 +59,9 @@ class CandlestickChartOpDescSpec extends AnyFlatSpec with Matchers { "CandlestickChartOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new CandlestickChartOpDesc - 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) } "CandlestickChartOpDesc.generatePythonCode" should "emit a Plotly Candlestick figure" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDescSpec.scala index 4165bd73b53..ad2e462de94 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/carpetPlot/CarpetPlotOpDescSpec.scala @@ -19,20 +19,15 @@ package org.apache.texera.amber.operator.visualization.carpetPlot -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 CarpetPlotOpDescSpec extends AnyFlatSpec with Matchers { +class CarpetPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "CarpetPlotOpDesc.operatorInfo" should "advertise the name and Scientific visualization group" in { @@ -54,9 +49,7 @@ class CarpetPlotOpDescSpec extends AnyFlatSpec with Matchers { "CarpetPlotOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new CarpetPlotOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "CarpetPlotOpDesc.generatePythonCode" should "emit a Plotly Carpet figure" in { @@ -75,40 +68,44 @@ class CarpetPlotOpDescSpec extends AnyFlatSpec with Matchers { // astype as a ValueError, both of them ending the whole exported run. "CarpetPlotOpDesc.generateStandaloneCode" should "write the page the operator yields for input it cannot plot" 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 CarpetPlotOpDesc d.a = "ax" d.b = "bx" d.y = "yx" - withDriver( - python, - "carpet_standalone_", - "carpet_driver_", + verifyStandaloneChartCases( + "carpet", d.generateStandaloneCode(), - driverScript, - "Carpet 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" -> "COLUMN_NOT_FOUND", - "words" -> "NOT_NUMERIC", - "empty" -> "EMPTY", - "nulls" -> "NO_VALID_ROWS", - "good" -> "CHART" - ) - } - } + casesScript = """cases = { + | "good": pd.DataFrame({"ax": [1.0, 2.0], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), + | "missing": pd.DataFrame({"ax": [1.0], "yx": [3.0]}), + | "words": pd.DataFrame({"ax": ["one", "two"], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), + | "empty": pd.DataFrame({"ax": [], "bx": [], "yx": []}), + | "nulls": pd.DataFrame({"ax": [None, None], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), + |}""".stripMargin, + verdictBody = """ # An answer page is the whole file and opens with the heading, where a + | # chart is a plotly document that happens to contain any wording. + | if not page.startswith("

"): + | verdict = "CHART" + | elif page.startswith("

Column '"): + | verdict = "COLUMN_NOT_FOUND" + | elif page.startswith("

Error converting input columns"): + | verdict = "NOT_NUMERIC" + | elif page.startswith("

Input table is empty"): + | verdict = "EMPTY" + | elif page.startswith("

No valid rows"): + | verdict = "NO_VALID_ROWS" + | else: + | verdict = "OTHER_PAGE"""".stripMargin, + expectedVerdicts = Map( + "missing" -> "COLUMN_NOT_FOUND", + "words" -> "NOT_NUMERIC", + "empty" -> "EMPTY", + "nulls" -> "NO_VALID_ROWS", + "good" -> "CHART" + ), + plotlyScopeBinding = Some(("plotly.graph_objects", "go")), + timeoutMessage = "Carpet driver timed out after 120s" + ) } // The generated code the operator emits for the native path, which the pages @@ -135,55 +132,4 @@ class CarpetPlotOpDescSpec extends AnyFlatSpec with Matchers { c.b shouldBe "bx" c.y shouldBe "yx" } - - // Runs the exported block over one frame per case and reports the page it - // wrote, so a branch that raises instead of answering shows up as a failure - // rather than as a missing file. - private val driverScript: String = - """import pathlib - |import sys - |import tempfile - | - |import pandas as pd - |import plotly.graph_objects as go - | - |# 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") - | - |cases = { - | "good": pd.DataFrame({"ax": [1.0, 2.0], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), - | "missing": pd.DataFrame({"ax": [1.0], "yx": [3.0]}), - | "words": pd.DataFrame({"ax": ["one", "two"], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), - | "empty": pd.DataFrame({"ax": [], "bx": [], "yx": []}), - | "nulls": pd.DataFrame({"ax": [None, None], "bx": [1.0, 2.0], "yx": [3.0, 4.0]}), - |} - | - |for name, frame in cases.items(): - | directory = tempfile.mkdtemp() - | scope = { - | "in1df": frame, - | "outputHtml": directory + "/chart.html", - | "outputJson": directory + "/chart.json", - | "pd": pd, - | "go": go, - | } - | exec(compile(source, "standalone", "exec"), scope) - | # An answer page is the whole file and opens with the heading, where a - | # chart is a plotly document that happens to contain any wording. - | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8").strip() - | if not page.startswith("

"): - | verdict = "CHART" - | elif page.startswith("

Column '"): - | verdict = "COLUMN_NOT_FOUND" - | elif page.startswith("

Error converting input columns"): - | verdict = "NOT_NUMERIC" - | elif page.startswith("

Input table is empty"): - | verdict = "EMPTY" - | elif page.startswith("

No valid rows"): - | verdict = "NO_VALID_ROWS" - | else: - | verdict = "OTHER_PAGE" - | print("CASE %s %s" % (name, verdict)) - |""".stripMargin } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDescSpec.scala index 8ef10ce64cd..bf77dce2ab3 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/choroplethMap/ChoroplethMapOpDescSpec.scala @@ -35,28 +35,24 @@ class ChoroplethMapOpDescSpec } it should "throw AssertionError naming the Locations Column when both fields are empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("location") + expectEmptyFieldError("location")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Color Column when only locations is set" in { opDesc.locations = "iso_code" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("color") + expectEmptyFieldError("color")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Locations Column when only color is set" in { opDesc.color = "intensity" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("location") + expectEmptyFieldError("location")(opDesc.manipulateTable()) } it should "throw AssertionError with a per-field message in createPlotlyFigure when only locations is set" in { // The compound assert(locations.nonEmpty && color.nonEmpty) is being split // per-field; the failing message should name the field that is missing. opDesc.locations = "iso_code" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("color") + expectEmptyFieldError("color")(opDesc.createPlotlyFigure()) } it should "render both configured columns when locations and color are set" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDescSpec.scala index 263aff03dfb..2344d719c23 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/contourPlot/ContourPlotOpDescSpec.scala @@ -19,14 +19,13 @@ package org.apache.texera.amber.operator.visualization.contourPlot -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 ContourPlotOpDescSpec extends AnyFlatSpec with Matchers { +class ContourPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "ContourPlotOpDesc.operatorInfo" should "advertise the name and Scientific visualization group" in { @@ -51,10 +50,7 @@ class ContourPlotOpDescSpec extends AnyFlatSpec with Matchers { "produce a single html-content STRING column keyed by the declared output port" in { val op = new ContourPlotOpDesc // getOutputSchemas ignores its input; pass empty to prove that. - val out = op.getOutputSchemas(Map.empty) - out shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "ContourPlotOpDesc" should "round-trip its column fields through the polymorphic base" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDescSpec.scala index 74d94562a1f..22b7648bfa3 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dendrogram/DendrogramOpDescSpec.scala @@ -39,22 +39,19 @@ class DendrogramOpDescSpec // createDendrogram() is private; generatePythonCode() is the public // entry point that reaches its asserts. it should "throw AssertionError naming the X column when all fields are empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.generatePythonCode()) } it should "throw AssertionError naming the Y column when only xVal and labels are set" in { opDesc.xVal = "coord_a" opDesc.labels = "label_col" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(opDesc.generatePythonCode()) } it should "throw AssertionError naming the Labels column when only xVal and yVal are set" in { opDesc.xVal = "coord_a" opDesc.yVal = "coord_b" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("label") + expectEmptyFieldError("label")(opDesc.generatePythonCode()) } it should "generate python code carrying all three configured columns" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDescSpec.scala index 03f32310e01..e375a837f85 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/dumbbellPlot/DumbbellPlotOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.dumbbellPlot -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 @@ -50,9 +49,7 @@ class DumbbellPlotOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChec "DumbbellPlotOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new DumbbellPlotOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "DumbbellPlotOpDesc.generatePythonCode" should "emit a Plotly Scatter (dumbbell) figure" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDescSpec.scala index f424ba4a81d..654b1faac8a 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/ecdfPlot/ECDFPlotOpDescSpec.scala @@ -64,13 +64,11 @@ class ECDFPlotOpDescSpec extends AnyFlatSpec with BeforeAndAfter with GeneratedC } it should "throw AssertionError naming the Value Column when valueColumn is left empty (manipulateTable)" 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 Value Column when valueColumn is left empty (createPlotlyFigure)" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(opDesc.createPlotlyFigure()) } it should "carry the configured value column through manipulateTable and the generated code" in { @@ -113,14 +111,7 @@ class ECDFPlotOpDescSpec extends AnyFlatSpec with BeforeAndAfter with GeneratedC "emit a single html-content STRING column keyed by the declared output port" in { opDesc.valueColumn = "score" val inputPort = opDesc.operatorInfo.inputPorts.head.id - val out = opDesc.getOutputSchemas( - Map(inputPort -> Schema().add("score", AttributeType.DOUBLE)) - ) - - out.keySet shouldBe Set(opDesc.operatorInfo.outputPorts.head.id) - val schema = out(opDesc.operatorInfo.outputPorts.head.id) - schema.getAttributeNames should contain theSameElementsAs List("html-content") - schema.getAttribute("html-content").getType shouldBe AttributeType.STRING + assertHtmlOutputSchema(opDesc, Map(inputPort -> Schema().add("score", AttributeType.DOUBLE))) } it should "ignore the input schema entirely (the plot output shape is fixed)" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDescSpec.scala index 8b9e7d60926..45ff07baa21 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/figureFactoryTable/FigureFactoryTableOpDescSpec.scala @@ -19,12 +19,8 @@ package org.apache.texera.amber.operator.visualization.figureFactoryTable -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.verifyTableChartCases +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -95,66 +91,12 @@ class FigureFactoryTableOpDescSpec // Stubs only the pytexera import seam, then hands the operator a table that arrives // empty, one whose every row has a hole in a chosen column, and one that draws. // Both empty branches call self.render_error, which once was not defined. - 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_table_chart"} - |with open(sys.argv[1], encoding="utf-8") as f: - | exec(compile(f.read(), sys.argv[1], "exec"), ns) - |op = ns["TableChartOperator"]() - | - |cases = [ - | ("empty", pd.DataFrame({"col_one": [], "col_two": []})), - | ("every_row_holed", pd.DataFrame({"col_one": [1.0, None], "col_two": [None, "b"]})), - | ("filled", pd.DataFrame({"col_one": [1, 2], "col_two": ["a", "b"]})), - |] - |for cid, df in cases: - | page = list(op.process_table(df, 0))[0]["html-content"] - | print("CASE %s %s" % (cid, page if "not available" in page else "CHART")) - |""".stripMargin - it should "render its message when the table is empty or every row has a hole" 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") - withColumns() - withDriver( - python, - "figure_factory_table_op_", - "figure_factory_table_driver_", + verifyTableChartCases( + "figure_factory_table", opDesc.generatePythonCode(), - runtimeDriverScript, - "Runtime driver timed out after 120s" - ) { (exitCode, output) => - val page = "

Figure Factory Table 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 "

" in page: + | verdict = "OTHER_PAGE" + | else: + | verdict = "CHART"""".stripMargin, + expectedVerdicts = Map( + "numpy" -> "CHART", + "nullable" -> "CHART", + "boolean" -> "NOT_NUMERIC", + "text" -> "NOT_NUMERIC" + ), + plotlyScopeBinding = Some(("plotly.graph_objects", "go")), + timeoutMessage = "Polar driver timed out after 120s" + ) } - - // Runs the exported block over one frame per case and reports the page it - // wrote, so a check that raises instead of answering fails here. - private val driverScript: String = - """import pathlib - |import sys - |import tempfile - | - |import pandas as pd - |import plotly.graph_objects as go - | - |source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") - | - |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"]}), - |} - | - |for name, frame in cases.items(): - | directory = tempfile.mkdtemp() - | scope = { - | "in1df": frame, - | "outputHtml": directory + "/chart.html", - | "outputJson": directory + "/chart.json", - | "pd": pd, - | "go": go, - | } - | exec(compile(source, "standalone", "exec"), scope) - | page = pathlib.Path(scope["outputHtml"]).read_text(encoding="utf-8") - | if "Selected columns must be numeric" in page: - | verdict = "NOT_NUMERIC" - | elif "

" 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/quiverPlot/QuiverPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDescSpec.scala index be7799aaaeb..44095e5304e 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/quiverPlot/QuiverPlotOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.quiverPlot -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 @@ -52,9 +51,7 @@ class QuiverPlotOpDescSpec extends AnyFlatSpec with EncodedGeneratedCodeAssertio "QuiverPlotOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new QuiverPlotOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "QuiverPlotOpDesc.generatePythonCode" should diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDescSpec.scala index 239ca3b0044..f960bfdc36f 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarChart/RadarChartOpDescSpec.scala @@ -35,37 +35,32 @@ class RadarChartOpDescSpec } it should "throw AssertionError naming the Name Column when nothing is configured" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("name") + expectEmptyFieldError("name")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Value Columns when only nameColumn is set (null list)" in { opDesc.nameColumn = "entity" // valueColumns defaults to null; the assert guards null before nonEmpty - 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 Value Columns when the list is explicitly empty" in { opDesc.nameColumn = "entity" opDesc.valueColumns = List() - 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 Value Columns in createPlotlyFigure when the list is unset" in { // createPlotlyFigure now guards valueColumns directly (null-safe), so // calling it on an unconfigured operator fails fast with a message // instead of an NPE from mapping over null. - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(opDesc.createPlotlyFigure()) } it should "throw AssertionError naming the Value Columns in createPlotlyFigure when the list is explicitly empty" in { opDesc.nameColumn = "entity" opDesc.valueColumns = List() - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("value") + expectEmptyFieldError("value")(opDesc.createPlotlyFigure()) } it should "render the name column and all value columns when configured" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDescSpec.scala index e731f831aa1..b68ac2943f8 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/radarPlot/RadarPlotOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.visualization.radarPlot -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 @@ -53,9 +52,7 @@ class RadarPlotOpDescSpec extends AnyFlatSpec with EncodedGeneratedCodeAssertion "RadarPlotOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new RadarPlotOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "RadarPlotOpDesc.generatePythonCode" should diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDescSpec.scala index 706c39a2896..e6d21d574ef 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/rangeSlider/RangeSliderOpDescSpec.scala @@ -19,17 +19,16 @@ package org.apache.texera.amber.operator.visualization.rangeSlider -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 com.kjetland.jackson.jsonSchema.annotations.JsonSchemaInject import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks import scala.jdk.CollectionConverters._ -class RangeSliderOpDescSpec extends AnyFlatSpec with Matchers { +class RangeSliderOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "RangeSliderOpDesc.operatorInfo" should "advertise the name and Basic visualization group" in { @@ -50,9 +49,7 @@ class RangeSliderOpDescSpec extends AnyFlatSpec with Matchers { "RangeSliderOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new RangeSliderOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "RangeSliderOpDesc.generatePythonCode" should "emit a Plotly Scatter figure" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDescSpec.scala index d22ac2b489c..d45c7e5aaf5 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/sankeyDiagram/SankeyDiagramOpDescSpec.scala @@ -19,14 +19,13 @@ package org.apache.texera.amber.operator.visualization.sankeyDiagram -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 SankeyDiagramOpDescSpec extends AnyFlatSpec with Matchers { +class SankeyDiagramOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "SankeyDiagramOpDesc.operatorInfo" should "advertise the name and Basic visualization group" in { @@ -49,9 +48,7 @@ class SankeyDiagramOpDescSpec extends AnyFlatSpec with Matchers { "SankeyDiagramOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new SankeyDiagramOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "SankeyDiagramOpDesc.generatePythonCode" should "emit a Plotly Sankey figure" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDescSpec.scala index a54352ccf1e..d87a0c80e49 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatter3DChart/Scatter3dChartOpDescSpec.scala @@ -37,22 +37,19 @@ class Scatter3dChartOpDescSpec // createPlotlyFigure() is private; generatePythonCode() is the public // entry point that reaches its asserts. it should "throw AssertionError naming the X Column when all fields are empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.generatePythonCode()) } it should "throw AssertionError naming the Y Column when only x and z are set" in { opDesc.x = "col_x" opDesc.z = "col_z" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(opDesc.generatePythonCode()) } it should "throw AssertionError naming the Z Column when only x and y are set" in { opDesc.x = "col_x" opDesc.y = "col_y" - val ex = expectError[AssertionError]("cannot be empty")(opDesc.generatePythonCode()) - fieldPart(ex.getMessage) should include("z") + expectEmptyFieldError("z")(opDesc.generatePythonCode()) } it should "generate python code carrying all three configured columns" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterPlotOpDescSpec.scala index d64cd20e46a..6f2541d9ce0 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/scatterplot/ScatterPlotOpDescSpec.scala @@ -46,20 +46,17 @@ class ScatterPlotOpDescSpec } it should "throw AssertionError naming the X-Column when both columns are empty" in { - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.manipulateTable()) } it should "throw AssertionError naming the Y-Column when only xColumn is set" in { setPrivateField("xColumn", "scatter_x") - val ex = expectError[AssertionError]("cannot be empty")(opDesc.manipulateTable()) - fieldPart(ex.getMessage) should include("y") + expectEmptyFieldError("y")(opDesc.manipulateTable()) } it should "throw AssertionError with a per-field message in createPlotlyFigure when only yColumn is set" in { setPrivateField("yColumn", "scatter_y") - val ex = expectError[AssertionError]("cannot be empty")(opDesc.createPlotlyFigure()) - fieldPart(ex.getMessage) should include("x") + expectEmptyFieldError("x")(opDesc.createPlotlyFigure()) } it should "render both configured columns when xColumn and yColumn are set" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDescSpec.scala index 4869289eb5c..afdc86b77a2 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/stripChart/StripChartOpDescSpec.scala @@ -19,14 +19,13 @@ package org.apache.texera.amber.operator.visualization.stripChart -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 StripChartOpDescSpec extends AnyFlatSpec with Matchers { +class StripChartOpDescSpec extends AnyFlatSpec with GeneratedCodeAssertionChecks { "StripChartOpDesc.operatorInfo" should "advertise the name and Statistical visualization group" in { @@ -49,9 +48,7 @@ class StripChartOpDescSpec extends AnyFlatSpec with Matchers { "StripChartOpDesc.getOutputSchemas" should "produce a single html-content STRING column keyed by the declared output port" in { val op = new StripChartOpDesc - op.getOutputSchemas(Map.empty) shouldBe Map( - op.operatorInfo.outputPorts.head.id -> Schema().add("html-content", AttributeType.STRING) - ) + op.getOutputSchemas(Map.empty) shouldBe expectedHtmlOutputSchema(op) } "StripChartOpDesc.generatePythonCode" should "emit a Plotly px.strip figure" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDescSpec.scala index e2474cc07bb..cb57a9a20b5 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/visualization/tablesChart/TablesPlotOpDescSpec.scala @@ -19,12 +19,8 @@ package org.apache.texera.amber.operator.visualization.tablesChart -import org.apache.texera.amber.util.PythonTestSupport.{ - NeedsPythonPackages, - canImport, - configuredPython, - withDriver -} +import org.apache.texera.amber.operator.visualization.ChartPythonTestSupport.verifyTableChartCases +import org.apache.texera.amber.util.PythonTestSupport.NeedsPythonPackages import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec import org.apache.texera.amber.operator.GeneratedCodeAssertionChecks @@ -88,66 +84,12 @@ class TablesPlotOpDescSpec // Stubs only the pytexera import seam, then hands the operator a table that arrives // empty, one whose every row has a hole in a chosen column, and one that draws. // Both empty branches call self.render_error, which once was not defined. - 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_table_chart"} - |with open(sys.argv[1], encoding="utf-8") as f: - | exec(compile(f.read(), sys.argv[1], "exec"), ns) - |op = ns["TableChartOperator"]() - | - |cases = [ - | ("empty", pd.DataFrame({"col_one": [], "col_two": []})), - | ("every_row_holed", pd.DataFrame({"col_one": [1.0, None], "col_two": [None, "b"]})), - | ("filled", pd.DataFrame({"col_one": [1, 2], "col_two": ["a", "b"]})), - |] - |for cid, df in cases: - | page = list(op.process_table(df, 0))[0]["html-content"] - | print("CASE %s %s" % (cid, page if "not available" in page else "CHART")) - |""".stripMargin - it should "render its message when the table is empty or every row has a hole" 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") - opDesc.includedColumns = List(column("col_one"), column("col_two")) - withDriver( - python, - "tables_plot_op_", - "tables_plot_driver_", + verifyTableChartCases( + "tables_plot", opDesc.generatePythonCode(), - runtimeDriverScript, - "Runtime driver timed out after 120s" - ) { (exitCode, output) => - val page = "

Tables Plot 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") - } - } + "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