Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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 <id> <verdict>"` 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"<h1>$title is not available.</h1><p>Reason is: "
withClue(s"Driver output:\n$output\n") {
exitCode shouldBe 0
output should include(s"CASE empty ${page}input table is empty.</p>")
output should include(
s"CASE every_row_holed ${page}value column contains only non-positive numbers or nulls.</p>"
)
output should include("CASE filled CHART")
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading