This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/texera.git
commit 2f5212d8fadc0d55aa60ac2ccc0ba2afb93fb5f9 Author: Xinyuan Lin <[email protected]> AuthorDate: Mon Nov 2 05:46:02 2026 +0000 test(workflow-operator): deduplicate operator test suites (#9237) ### What changes were proposed in this PR? Consolidates and combines workflow operator test suite deduplication refactors across 4 test suites: | Suite | Module / File | Change Summary | Net Lines | Issue | | --- | --- | --- | ---: | --- | | `CaseSensitiveAnalyzerSpec` | `keywordSearch` | Table-drive keyword match cases via parameterized test table | -35 | Closes #9210 | | `FileScanUtilsSpec` | `source/scan/file` | Factor default-argument file scan test helper and unify stream assertion | -58 | Closes #9216 | | `HashJoinOpSpec` | `hashJoin` | Factor tuple join execution helper and unify tuple equality checks | -56 | Closes #9221 | | `UnnestStringOpExecSpec` | `unneststring` | Factor `unnest` helper, manage executor lifecycle with `try/finally`, eliminate mutable state | -48 | Closes #9236 | | **Total** | | **4 test suites refactored** | **-197** | | This PR supersedes and combines the smaller individual PRs #9211, #9217, and #9222 into #9237. ### Any related issues, documentation, discussions? Closes #9210 Closes #9216 Closes #9221 Closes #9236 Supersedes #9211, #9217, #9222. ### How was this PR tested? Verified with targeted sbt test suites, operator metadata tests, and linters: ```bash sbt "WorkflowOperator/testOnly org.apache.texera.amber.operator.source.scan.file.FileScanUtilsSpec org.apache.texera.amber.operator.hashJoin.HashJoinOpSpec org.apache.texera.amber.operator.keywordSearch.CaseSensitiveAnalyzerSpec org.apache.texera.amber.operator.unneststring.UnnestStringOpExecSpec" sbt "WorkflowOperator/testOnly org.apache.texera.amber.operator.metadata.*" sbt "WorkflowOperator/scalafmtCheck" "WorkflowOperator/Test/scalafmtCheck" "WorkflowOperator/scalafix --check" "WorkflowOperator/Test/scalafix --check" ``` All 58 tests in the 4 refactored suites passed cleanly, all 229 operator metadata tests passed, and all scalafmt / scalafix checks passed. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Antigravity (Gemini 2.5 Pro) --- .../amber/operator/hashJoin/HashJoinOpSpec.scala | 234 +++++++----------- .../keywordSearch/CaseSensitiveAnalyzerSpec.scala | 143 +++++------ .../source/scan/file/FileScanUtilsSpec.scala | 262 ++++++++------------- .../unneststring/UnnestStringOpExecSpec.scala | 182 ++++++-------- 4 files changed, 312 insertions(+), 509 deletions(-) diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala index 5f99297fb4..cbf6c609f4 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/hashJoin/HashJoinOpSpec.scala @@ -23,25 +23,24 @@ import org.apache.texera.amber.core.tuple._ import org.apache.texera.amber.core.workflow.PortIdentity import org.apache.texera.amber.operator.hashJoin.HashJoinOpDesc.HASH_JOIN_INTERNAL_KEY_NAME import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec -class HashJoinOpSpec extends AnyFlatSpec with BeforeAndAfter { + +class HashJoinOpSpec extends AnyFlatSpec { val build: Int = 0 val probe: Int = 1 - var buildOpExec: HashJoinBuildOpExec[String] = _ - var probeOpExec: HashJoinProbeOpExec[String] = _ - var opDesc: HashJoinOpDesc[String] = _ + case class JoinResult( + tuples: List[TupleLike], + onFinishTuples: List[TupleLike] + ) def getInternalHashTableSchema(buildInputSchema: Schema): Schema = { Schema() .add(HASH_JOIN_INTERNAL_KEY_NAME, AttributeType.ANY) .add(buildInputSchema) - } def tuple(name: String, n: Int = 1, i: Option[Int]): Tuple = { - Tuple .builder(schema(name, n)) .addSequentially(Array[Any](i.map(_.toString).orNull, i.map(_.toString).orNull)) @@ -52,174 +51,119 @@ class HashJoinOpSpec extends AnyFlatSpec with BeforeAndAfter { Schema() .add(new Attribute(name, AttributeType.STRING)) .add(new Attribute(name + "_" + n, AttributeType.STRING)) - } - it should "work with basic two input streams with different buildAttributeName and probeAttributeName" in { - - opDesc = new HashJoinOpDesc[String]() - opDesc.buildAttributeName = "build_1" - opDesc.probeAttributeName = "probe_1" - opDesc.joinType = JoinType.INNER - val inputSchemas = Map(PortIdentity() -> schema("build"), PortIdentity(1) -> schema("probe")) + private def runJoin( + opDesc: HashJoinOpDesc[String], + inputSchemas: Map[PortIdentity, Schema], + buildTuples: Seq[Tuple], + probeTuples: Seq[Tuple] + ): JoinResult = { val outputSchema = opDesc.getExternalOutputSchemas(inputSchemas).values.head + val descJson = objectMapper.writeValueAsString(opDesc) - buildOpExec = new HashJoinBuildOpExec[String](objectMapper.writeValueAsString(opDesc)) + val buildOpExec = new HashJoinBuildOpExec[String](descJson) buildOpExec.open() - - (0 to 7).map(i => { - assert( - buildOpExec.processTuple(tuple("build", 1, Some(i)), build).isEmpty - ) - }) - - val buildOpOutputIterator = - buildOpExec.onFinish(build) - assert(buildOpOutputIterator.hasNext) - - probeOpExec = new HashJoinProbeOpExec[String](objectMapper.writeValueAsString(opDesc)) - - probeOpExec.open() - while (buildOpOutputIterator.hasNext) { - assert( - probeOpExec - .processTuple( - buildOpOutputIterator - .next() - .asInstanceOf[SchemaEnforceable] - .enforceSchema(getInternalHashTableSchema(inputSchemas.head._2)), - build + try { + buildTuples.foreach { t => + assert(buildOpExec.processTuple(t, build).isEmpty) + } + val buildOpOutputIterator = buildOpExec.onFinish(build) + assert(buildOpOutputIterator.hasNext) + + val probeOpExec = new HashJoinProbeOpExec[String](descJson) + probeOpExec.open() + try { + while (buildOpOutputIterator.hasNext) { + assert( + probeOpExec + .processTuple( + buildOpOutputIterator + .next() + .asInstanceOf[SchemaEnforceable] + .enforceSchema(getInternalHashTableSchema(inputSchemas.head._2)), + build + ) + .isEmpty ) - .isEmpty - ) + } + assert(probeOpExec.onFinish(build).isEmpty) + + val outputTuples = probeTuples + .map(t => probeOpExec.processTuple(t, probe)) + .foldLeft(Iterator[TupleLike]())(_ ++ _) + .map(_.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) + .toList + + val onFinishTuples = probeOpExec + .onFinish(probe) + .map(_.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) + .toList + + JoinResult(outputTuples, onFinishTuples) + } finally { + probeOpExec.close() + } + } finally { + buildOpExec.close() } - assert(probeOpExec.onFinish(build).isEmpty) - - buildOpExec.close() - - val outputTuples = (5 to 9) - .map(i => probeOpExec.processTuple(tuple("probe", 1, Some(i)), probe)) - .foldLeft(Iterator[TupleLike]())(_ ++ _) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - .toList - - assert(probeOpExec.onFinish(probe).isEmpty) + } - assert(outputTuples.size == 3) - assert(outputTuples.head.getFields.length == 3) + it should "work with basic two input streams with different buildAttributeName and probeAttributeName" in { + val opDesc = new HashJoinOpDesc[String]() + opDesc.buildAttributeName = "build_1" + opDesc.probeAttributeName = "probe_1" + opDesc.joinType = JoinType.INNER + val inputSchemas = Map(PortIdentity() -> schema("build"), PortIdentity(1) -> schema("probe")) - probeOpExec.close() + val result = runJoin( + opDesc, + inputSchemas, + buildTuples = (0 to 7).map(i => tuple("build", 1, Some(i))), + probeTuples = (5 to 9).map(i => tuple("probe", 1, Some(i))) + ) + assert(result.onFinishTuples.isEmpty) + assert(result.tuples.size == 3) + assert(result.tuples.head.getFields.length == 3) } it should "work with basic two input streams with the same buildAttributeName and probeAttributeName" in { - opDesc = new HashJoinOpDesc[String]() + val opDesc = new HashJoinOpDesc[String]() opDesc.buildAttributeName = "same" opDesc.probeAttributeName = "same" opDesc.joinType = JoinType.INNER val inputSchemas = Map(PortIdentity() -> schema("same", 1), PortIdentity(1) -> schema("same", 2)) - val outputSchema = opDesc.getExternalOutputSchemas(inputSchemas).values.head - - buildOpExec = new HashJoinBuildOpExec[String](objectMapper.writeValueAsString(opDesc)) - buildOpExec.open() - - (0 to 7).map(i => { - assert( - buildOpExec.processTuple(tuple("same", 1, Some(i)), build).isEmpty - ) - }) - val buildOpOutputIterator = - buildOpExec.onFinish(build) - assert(buildOpOutputIterator.hasNext) - - probeOpExec = new HashJoinProbeOpExec[String](objectMapper.writeValueAsString(opDesc)) - probeOpExec.open() - - while (buildOpOutputIterator.hasNext) { - assert( - probeOpExec - .processTuple( - buildOpOutputIterator - .next() - .asInstanceOf[SchemaEnforceable] - .enforceSchema(getInternalHashTableSchema(inputSchemas.head._2)), - build - ) - .isEmpty - ) - } - assert(probeOpExec.onFinish(build).isEmpty) - - buildOpExec.close() - val outputTuples = (5 to 9) - .map(i => probeOpExec.processTuple(tuple("same", n = 2, Some(i)), probe)) - .foldLeft(Iterator[TupleLike]())(_ ++ _) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - .toList - - assert(probeOpExec.onFinish(probe).isEmpty) - - assert(outputTuples.size == 3) - assert(outputTuples.head.getFields.length == 3) + val result = runJoin( + opDesc, + inputSchemas, + buildTuples = (0 to 7).map(i => tuple("same", 1, Some(i))), + probeTuples = (5 to 9).map(i => tuple("same", n = 2, Some(i))) + ) - probeOpExec.close() + assert(result.onFinishTuples.isEmpty) + assert(result.tuples.size == 3) + assert(result.tuples.head.getFields.length == 3) } it should "work with basic two input streams with the same buildAttributeName and probeAttributeName with Full Outer Join" in { - opDesc = new HashJoinOpDesc[String]() + val opDesc = new HashJoinOpDesc[String]() opDesc.buildAttributeName = "same" opDesc.probeAttributeName = "same" opDesc.joinType = JoinType.FULL_OUTER val inputSchemas = Map(PortIdentity() -> schema("same", 1), PortIdentity(1) -> schema("same", 2)) - val outputSchema = opDesc.getExternalOutputSchemas(inputSchemas).values.head - buildOpExec = new HashJoinBuildOpExec[String](objectMapper.writeValueAsString(opDesc)) - buildOpExec.open() - - (0 to 7).map(i => { - assert( - buildOpExec.processTuple(tuple("same", 1, Some(i)), build).isEmpty - ) - }) - val buildOpOutputIterator = - buildOpExec.onFinish(build) - assert(buildOpOutputIterator.hasNext) - - probeOpExec = new HashJoinProbeOpExec[String](objectMapper.writeValueAsString(opDesc)) - probeOpExec.open() - - while (buildOpOutputIterator.hasNext) { - assert( - probeOpExec - .processTuple( - buildOpOutputIterator - .next() - .asInstanceOf[SchemaEnforceable] - .enforceSchema(getInternalHashTableSchema(inputSchemas.head._2)), - build - ) - .isEmpty - ) - } - assert(probeOpExec.onFinish(build).isEmpty) - - buildOpExec.close() - - assert( - (5 to 9) - .map(_ => { - probeOpExec.processTuple(tuple("same", n = 2, None), probe) - }) - .foldLeft(Iterator[TupleLike]())(_ ++ _) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - .size == 5 + val result = runJoin( + opDesc, + inputSchemas, + buildTuples = (0 to 7).map(i => tuple("same", 1, Some(i))), + probeTuples = (5 to 9).map(_ => tuple("same", n = 2, None)) ) - assert(probeOpExec.onFinish(probe).size == 8) - - probeOpExec.close() + assert(result.tuples.size == 5) + assert(result.onFinishTuples.size == 8) } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/keywordSearch/CaseSensitiveAnalyzerSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/keywordSearch/CaseSensitiveAnalyzerSpec.scala index c5a202928b..e3c730e699 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/keywordSearch/CaseSensitiveAnalyzerSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/keywordSearch/CaseSensitiveAnalyzerSpec.scala @@ -36,8 +36,11 @@ class CaseSensitiveAnalyzerSpec extends AnyFlatSpec { // versions; we follow the canonical contract to keep the spec robust. // --------------------------------------------------------------------------- - private def tokensOf(fieldName: String, input: String): List[String] = { - val analyzer = new CaseSensitiveAnalyzer + private def tokensOf( + analyzer: CaseSensitiveAnalyzer, + fieldName: String, + input: String + ): List[String] = { val stream = analyzer.tokenStream(fieldName, new StringReader(input)) val termAttr = stream.addAttribute(classOf[CharTermAttribute]) val out = ArrayBuffer.empty[String] @@ -49,83 +52,64 @@ class CaseSensitiveAnalyzerSpec extends AnyFlatSpec { stream.end() } finally { stream.close() - analyzer.close() } out.toList } - // --------------------------------------------------------------------------- - // Case preservation — the whole point of CaseSensitiveAnalyzer is to - // SKIP the lowercasing pipeline used by StandardAnalyzer. - // --------------------------------------------------------------------------- - - "CaseSensitiveAnalyzer" should "preserve case in every emitted token" in { - assert(tokensOf("body", "Hello World") == List("Hello", "World")) - } - - it should "preserve mixed-case tokens (e.g. CamelCase identifiers)" in { - assert(tokensOf("body", "FooBar BazQux") == List("FooBar", "BazQux")) - } - - it should "preserve all-uppercase tokens" in { - assert(tokensOf("body", "URL HTTP HTML") == List("URL", "HTTP", "HTML")) - } - - it should "preserve all-lowercase tokens (no upcasing either)" in { - assert(tokensOf("body", "alpha beta gamma") == List("alpha", "beta", "gamma")) - } - - // --------------------------------------------------------------------------- - // Word-boundary tokenization — the underlying tokenizer is - // StandardTokenizer (Unicode UAX#29); pin its splitting behavior. - // --------------------------------------------------------------------------- - - "CaseSensitiveAnalyzer (standard tokenizer)" should - "split on a single space" in { - assert(tokensOf("body", "a b c") == List("a", "b", "c")) - } - - it should "split on tabs and newlines" in { - assert(tokensOf("body", "a\tb\nc") == List("a", "b", "c")) - } - - it should "collapse runs of whitespace (no empty tokens emitted)" in { - assert(tokensOf("body", "a b\n\nc") == List("a", "b", "c")) - } - - // --------------------------------------------------------------------------- - // Punctuation — StandardTokenizer splits on Unicode word boundaries, so - // punctuation is a boundary and is stripped rather than kept attached. - // This is the whole point of the fix: case-sensitive matching must not - // change punctuation handling relative to the default StandardAnalyzer. - // --------------------------------------------------------------------------- - - it should - "split on punctuation and strip it (StandardTokenizer word boundaries)" in { - // `,` is a word boundary, so `"abc,def"` splits into two tokens. - assert(tokensOf("body", "abc,def") == List("abc", "def")) - // Sentence punctuation is a boundary and is dropped, not kept attached. - assert(tokensOf("body", "Hello, world!") == List("Hello", "world")) + private def tokensOf(fieldName: String, input: String): List[String] = { + val analyzer = new CaseSensitiveAnalyzer + try { + tokensOf(analyzer, fieldName, input) + } finally { + analyzer.close() + } } // --------------------------------------------------------------------------- - // Edge cases + // Tokenization test cases — preserves case (skips StandardAnalyzer lowercasing), + // splits on UAX#29 word boundaries and punctuation, collapses whitespace, + // and handles empty / whitespace edge cases. // --------------------------------------------------------------------------- - "CaseSensitiveAnalyzer (empty input)" should "produce no tokens" in { - assert(tokensOf("body", "") == Nil) - } - - it should "produce no tokens for pure-whitespace input" in { - assert(tokensOf("body", " \t\n ") == Nil) + behavior of "CaseSensitiveAnalyzer" + + private val tokenizationCases = Seq( + // Case preservation + ("preserve case in every emitted token", "Hello World", List("Hello", "World")), + ( + "preserve mixed-case tokens (e.g. CamelCase identifiers)", + "FooBar BazQux", + List("FooBar", "BazQux") + ), + ("preserve all-uppercase tokens", "URL HTTP HTML", List("URL", "HTTP", "HTML")), + ( + "preserve all-lowercase tokens (no upcasing either)", + "alpha beta gamma", + List("alpha", "beta", "gamma") + ), + // Word-boundary tokenization & whitespace collapsing (Unicode UAX#29) + ("split on a single space", "a b c", List("a", "b", "c")), + ("split on tabs and newlines", "a\tb\nc", List("a", "b", "c")), + ("collapse runs of whitespace (no empty tokens emitted)", "a b\n\nc", List("a", "b", "c")), + // Punctuation word boundaries (punctuation is stripped, not kept attached) + ("split on comma word boundary and strip punctuation", "abc,def", List("abc", "def")), + ("split on sentence punctuation and strip it", "Hello, world!", List("Hello", "world")), + // Edge cases + ("produce no tokens on empty input", "", Nil), + ("produce no tokens for pure-whitespace input", " \t\n ", Nil) + ) + + for ((description, input, expected) <- tokenizationCases) { + it should description in { + assert(tokensOf("body", input) == expected) + } } // --------------------------------------------------------------------------- // StopFilter — empty stop-word set; nothing should be filtered out. // --------------------------------------------------------------------------- - "CaseSensitiveAnalyzer (StopFilter with CharArraySet.EMPTY_SET)" should - "NOT remove common English stop words (the / and / of / a)" in { + it should "NOT remove common English stop words (the / and / of / a)" in { // StandardAnalyzer's default stop set would strip "the", "and", // "of", "a"; this analyzer is built with `CharArraySet.EMPTY_SET` // so every token survives. Pin that explicitly. @@ -140,42 +124,23 @@ class CaseSensitiveAnalyzerSpec extends AnyFlatSpec { // regardless of field name, and each call gets its own TokenStream. // --------------------------------------------------------------------------- - "CaseSensitiveAnalyzer" should - "produce the same tokens for the same input across different field names" in { + it should "produce the same tokens for the same input across different field names" in { val a = tokensOf("title", "Hello World") val b = tokensOf("body", "Hello World") assert(a == b, "field name must not change tokenization") } - it should - "return independent TokenStreams for successive tokenStream calls on the SAME analyzer instance" in { + it should "return independent TokenStreams for successive tokenStream calls on the SAME analyzer instance" in { // Reuse one analyzer across two tokenStream calls — consuming the - // first stream must not affect the second. The helper would create - // a fresh analyzer per call, masking the intra-analyzer reuse - // behavior; do the lifecycle manually here. + // first stream must not affect the second. val analyzer = new CaseSensitiveAnalyzer try { - def collect(input: String): List[String] = { - val stream = analyzer.tokenStream("body", new java.io.StringReader(input)) - val termAttr = stream.addAttribute(classOf[CharTermAttribute]) - val out = ArrayBuffer.empty[String] - try { - stream.reset() - while (stream.incrementToken()) { - out.append(termAttr.toString) - } - stream.end() - } finally { - stream.close() - } - out.toList - } - val first = collect("alpha Beta GAMMA") - val second = collect("alpha Beta GAMMA") + val first = tokensOf(analyzer, "body", "alpha Beta GAMMA") + val second = tokensOf(analyzer, "body", "alpha Beta GAMMA") assert(first == List("alpha", "Beta", "GAMMA")) assert(second == first, "second tokenStream call must not be affected by the first") // Different input on the SAME analyzer also produces correct tokens. - val third = collect("foo bar") + val third = tokensOf(analyzer, "body", "foo bar") assert(third == List("foo", "bar")) } finally { analyzer.close() diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanUtilsSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanUtilsSpec.scala index a560ad0600..96cd9b3bcd 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanUtilsSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/scan/file/FileScanUtilsSpec.scala @@ -19,6 +19,7 @@ package org.apache.texera.amber.operator.source.scan.file +import org.apache.texera.amber.core.tuple.TupleLike import org.apache.texera.amber.operator.source.scan.{FileAttributeType, FileDecodingMethod} import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec @@ -60,184 +61,127 @@ class FileScanUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll { super.afterAll() } - private def contents(tuples: Seq[org.apache.texera.amber.core.tuple.TupleLike]): Seq[Any] = + private def contents(tuples: Seq[TupleLike]): Seq[Any] = tuples.map(_.getFields.head) - "FileScanUtils.createTuplesFromFile" should - "extract every zip entry as a single-string tuple" in { - val tuples = FileScanUtils + /** Helper for createTuplesFromFile providing canonical test defaults. */ + private def scan( + fileName: String, + displayFileName: String = "d", + attributeType: FileAttributeType = FileAttributeType.STRING, + fileEncoding: FileDecodingMethod = FileDecodingMethod.UTF_8, + extract: Boolean = false, + outputFileName: Boolean = false, + fileScanOffset: Option[Int] = None, + fileScanLimit: Option[Int] = None + ): Seq[TupleLike] = { + FileScanUtils .createTuplesFromFile( - fileName = makeZip("a.txt" -> "Content A", "b.txt" -> "Content B"), - displayFileName = "ignored-when-extracting", - attributeType = FileAttributeType.SINGLE_STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = true, - outputFileName = false, - fileScanOffset = None, - fileScanLimit = None + fileName = fileName, + displayFileName = displayFileName, + attributeType = attributeType, + fileEncoding = fileEncoding, + extract = extract, + outputFileName = outputFileName, + fileScanOffset = fileScanOffset, + fileScanLimit = fileScanLimit ) .toSeq + } + + "FileScanUtils.createTuplesFromFile" should + "extract every zip entry as a single-string tuple" in { + val tuples = scan( + fileName = makeZip("a.txt" -> "Content A", "b.txt" -> "Content B"), + displayFileName = "ignored-when-extracting", + attributeType = FileAttributeType.SINGLE_STRING, + extract = true + ) assert(tuples.size == 2) assert(contents(tuples).toSet == Set("Content A", "Content B")) } it should "drop __MACOSX metadata entries when extracting" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeZip("real.txt" -> "keep me", "__MACOSX/._real.txt" -> "junk"), - displayFileName = "d", - attributeType = FileAttributeType.SINGLE_STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = true, - outputFileName = false, - fileScanOffset = None, - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeZip("real.txt" -> "keep me", "__MACOSX/._real.txt" -> "junk"), + attributeType = FileAttributeType.SINGLE_STRING, + extract = true + ) assert(contents(tuples) == Seq("keep me")) } it should "flat-map each line of an extracted entry for a per-line attribute type" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeZip("lines.txt" -> "l1\nl2\nl3"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = true, - outputFileName = false, - fileScanOffset = None, - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeZip("lines.txt" -> "l1\nl2\nl3"), + extract = true + ) assert(contents(tuples) == Seq("l1", "l2", "l3")) } it should "skip the offset lines and return all remaining lines when no limit is set" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(1), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanOffset = Some(1) + ) assert(contents(tuples) == Seq("l2", "l3", "l4", "l5")) } it should "return every line for a zero offset with no limit" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(0), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanOffset = Some(0) + ) assert(contents(tuples) == Seq("l1", "l2", "l3", "l4", "l5")) } it should "return limit lines starting at the offset when both are set" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(1), - fileScanLimit = Some(2) - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanOffset = Some(1), + fileScanLimit = Some(2) + ) assert(contents(tuples) == Seq("l2", "l3")) } it should "return the first limit lines when only a limit is set" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = None, - fileScanLimit = Some(2) - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanLimit = Some(2) + ) assert(contents(tuples) == Seq("l1", "l2")) } it should "return no tuples when the offset is past the end of the file" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(99), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanOffset = Some(99) + ) assert(contents(tuples) == Seq.empty) } it should "return no tuples for an Int.MaxValue offset without overflowing" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(Int.MaxValue), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + fileScanOffset = Some(Int.MaxValue) + ) assert(contents(tuples) == Seq.empty) } it should "apply an offset without a limit to each extracted zip entry independently" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeZip("a.txt" -> "a1\na2", "b.txt" -> "b1\nb2"), - displayFileName = "d", - attributeType = FileAttributeType.STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = true, - outputFileName = false, - fileScanOffset = Some(1), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeZip("a.txt" -> "a1\na2", "b.txt" -> "b1\nb2"), + extract = true, + fileScanOffset = Some(1) + ) assert(contents(tuples) == Seq("a2", "b2")) } it should "ignore the offset for a single-tuple attribute type" in { - val tuples = FileScanUtils - .createTuplesFromFile( - fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), - displayFileName = "d", - attributeType = FileAttributeType.SINGLE_STRING, - fileEncoding = FileDecodingMethod.UTF_8, - extract = false, - outputFileName = false, - fileScanOffset = Some(1), - fileScanLimit = None - ) - .toSeq + val tuples = scan( + fileName = makeTextFile("l1\nl2\nl3\nl4\nl5"), + attributeType = FileAttributeType.SINGLE_STRING, + fileScanOffset = Some(1) + ) assert(contents(tuples) == Seq("l1\nl2\nl3\nl4\nl5")) } @@ -284,16 +228,22 @@ class FileScanUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll { override def read(b: Array[Byte], off: Int, len: Int): Int = throw failure } + private def memoryFailureMessage( + failure: Throwable, + attributeType: FileAttributeType + ): String = { + intercept[RuntimeException] { + FileScanUtils.safeToByteArray(failingStream(failure), attributeType) + }.getMessage + } + "FileScanUtils.safeToByteArray" should "translate an out-of-memory read into advice to switch to large binary" in { - val exception = intercept[RuntimeException] { - FileScanUtils.safeToByteArray( - failingStream(new OutOfMemoryError("Requested array size exceeds VM limit")), - FileAttributeType.BINARY - ) - } assert( - exception.getMessage == + memoryFailureMessage( + new OutOfMemoryError("Requested array size exceeds VM limit"), + FileAttributeType.BINARY + ) == "File exceeds maximum safe memory size for 'binary' type. " + "Please use 'large binary' attribute type instead." ) @@ -302,28 +252,22 @@ class FileScanUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll { it should "advise splitting or chunking the file for a single-string attribute" in { // 'large binary' is meaningless for a text column, so this arm has to give // different advice from the binary one. - val exception = intercept[RuntimeException] { - FileScanUtils.safeToByteArray( - failingStream(new OutOfMemoryError("Requested array size exceeds VM limit")), - FileAttributeType.SINGLE_STRING - ) - } assert( - exception.getMessage == + memoryFailureMessage( + new OutOfMemoryError("Requested array size exceeds VM limit"), + FileAttributeType.SINGLE_STRING + ) == "File exceeds maximum safe memory size for 'single string' type. " + "Please split the file or use a chunked reading method." ) } it should "fall back to a generic hint for any other attribute type" in { - val exception = intercept[RuntimeException] { - FileScanUtils.safeToByteArray( - failingStream(new OutOfMemoryError("Requested array size exceeds VM limit")), - FileAttributeType.STRING - ) - } assert( - exception.getMessage == + memoryFailureMessage( + new OutOfMemoryError("Requested array size exceeds VM limit"), + FileAttributeType.STRING + ) == "File exceeds maximum safe memory size for 'string' type. " + "File is too large to fit in memory." ) @@ -332,13 +276,11 @@ class FileScanUtilsSpec extends AnyFlatSpec with BeforeAndAfterAll { it should "treat an IllegalArgumentException from the stream as an over-size failure too" in { // An over-large allocation surfaces as IllegalArgumentException rather than // OutOfMemoryError on some streams, so the guard catches both. - val exception = intercept[RuntimeException] { - FileScanUtils.safeToByteArray( - failingStream(new IllegalArgumentException("negative capacity")), - FileAttributeType.BINARY - ) - } - assert(exception.getMessage.startsWith("File exceeds maximum safe memory size")) + val message = memoryFailureMessage( + new IllegalArgumentException("negative capacity"), + FileAttributeType.BINARY + ) + assert(message.startsWith("File exceeds maximum safe memory size")) } it should "let an unrelated read failure propagate untouched" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/unneststring/UnnestStringOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/unneststring/UnnestStringOpExecSpec.scala index 57a97e86e2..b0018e433b 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/unneststring/UnnestStringOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/unneststring/UnnestStringOpExecSpec.scala @@ -20,225 +20,177 @@ package org.apache.texera.amber.operator.unneststring import org.apache.texera.amber.core.tuple._ -import org.apache.texera.amber.core.workflow.PortIdentity import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalatest.BeforeAndAfter import org.scalatest.flatspec.AnyFlatSpec -class UnnestStringOpExecSpec extends AnyFlatSpec with BeforeAndAfter { - val tupleSchema: Schema = Schema() + +class UnnestStringOpExecSpec extends AnyFlatSpec { + private val tupleSchema: Schema = Schema() .add(new Attribute("field1", AttributeType.STRING)) .add(new Attribute("field2", AttributeType.INTEGER)) .add(new Attribute("field3", AttributeType.STRING)) - val tuple: Tuple = Tuple + private val tuple: Tuple = Tuple .builder(tupleSchema) .add(new Attribute("field1", AttributeType.STRING), "a-b-c") .add(new Attribute("field2", AttributeType.INTEGER), 1) .add(new Attribute("field3", AttributeType.STRING), "a") .build() - var opExec: UnnestStringOpExec = _ - var opDesc: UnnestStringOpDesc = _ - var outputSchema: Schema = _ - before { - opDesc = new UnnestStringOpDesc() - opDesc.attribute = "field1" - opDesc.delimiter = "-" + private def unnest( + delimiter: String, + attribute: String = "field1", + targetTuple: Tuple = tuple + ): List[String] = { + val opDesc = new UnnestStringOpDesc() + opDesc.attribute = attribute + opDesc.delimiter = delimiter opDesc.resultAttribute = "split" + val exec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) + val schema = tupleSchema.add(new Attribute("split", AttributeType.STRING)) + exec.open() + try { + exec + .processTuple(targetTuple, 0) + .map(_.asInstanceOf[SchemaEnforceable].enforceSchema(schema).getField[String]("split")) + .toList + } finally { + exec.close() + } + } + + // Runs the operator over one value and returns the pieces it emits. + private def unnestValue(delimiter: String, value: String): List[String] = { + val input = Tuple + .builder(tupleSchema) + .add(new Attribute("field1", AttributeType.STRING), value) + .add(new Attribute("field2", AttributeType.INTEGER), 1) + .add(new Attribute("field3", AttributeType.STRING), "a") + .build() + unnest(delimiter, "field1", input) } it should "open" in { + val opDesc = new UnnestStringOpDesc() opDesc.attribute = "field1" opDesc.delimiter = "-" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head + opDesc.resultAttribute = "split" + val opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) opExec.open() - assert(opExec.flatMapFunc != null) + try { + assert(opExec.flatMapFunc != null) + } finally { + opExec.close() + } } it should "split value in the given attribute and output the split result in the result attribute, one for each tuple" in { - opDesc.attribute = "field1" - opDesc.delimiter = "-" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head - opExec.open() - val processedTuple = opExec - .processTuple(tuple, 0) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - assert(processedTuple.next().getField("split").equals("a")) - assert(processedTuple.next().getField("split").equals("b")) - assert(processedTuple.next().getField("split").equals("c")) - assertThrows[java.util.NoSuchElementException](processedTuple.next().getField("split")) - opExec.close() + assert(unnest("-") == List("a", "b", "c")) } it should "generate the correct tuple when there is no delimiter in the value" in { - opDesc.attribute = "field3" - opDesc.delimiter = "-" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head - opExec.open() - val processedTuple = opExec - .processTuple(tuple, 0) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - assert(processedTuple.next().getField("split").equals("a")) - assertThrows[java.util.NoSuchElementException](processedTuple.next().getField("split")) - opExec.close() + assert(unnest("-", attribute = "field3") == List("a")) } it should "only contain split results that are not null" in { - opDesc.attribute = "field1" - opDesc.delimiter = "/" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head - val tuple: Tuple = Tuple + val customTuple = Tuple .builder(tupleSchema) .add(new Attribute("field1", AttributeType.STRING), "//a//b/") .add(new Attribute("field2", AttributeType.INTEGER), 1) .add(new Attribute("field3", AttributeType.STRING), "a") .build() - - opExec.open() - val processedTuple = opExec - .processTuple(tuple, 0) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - assert(processedTuple.next().getField("split").equals("a")) - assert(processedTuple.next().getField("split").equals("b")) - assertThrows[java.util.NoSuchElementException](processedTuple.next().getField("split")) - opExec.close() + assert(unnest("/", targetTuple = customTuple) == List("a", "b")) } it should "produce no rows when the attribute is empty" in { - opDesc.attribute = "field1" - opDesc.delimiter = "-" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) // A blank CSV cell arrives as null. This used to throw a NullPointerException on // the toString instead of unnesting to nothing. - val tuple: Tuple = Tuple + val customTuple = Tuple .builder(tupleSchema) .add(new Attribute("field1", AttributeType.STRING), null) .add(new Attribute("field2", AttributeType.INTEGER), 1) .add(new Attribute("field3", AttributeType.STRING), "a") .build() - - opExec.open() - assert(opExec.processTuple(tuple, 0).isEmpty) - opExec.close() + assert(unnest("-", targetTuple = customTuple).isEmpty) } it should "split by regex delimiter" in { - opDesc.attribute = "field1" - opDesc.delimiter = "<\\d*>" - opExec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - outputSchema = opDesc.getExternalOutputSchemas(Map(PortIdentity() -> tupleSchema)).values.head - val tuple: Tuple = Tuple + val customTuple = Tuple .builder(tupleSchema) .add(new Attribute("field1", AttributeType.STRING), "<>a<1>b<12>") .add(new Attribute("field2", AttributeType.INTEGER), 1) .add(new Attribute("field3", AttributeType.STRING), "a") .build() - - opExec.open() - val processedTuple = opExec - .processTuple(tuple, 0) - .map(tupleLike => tupleLike.asInstanceOf[SchemaEnforceable].enforceSchema(outputSchema)) - assert(processedTuple.next().getField("split").equals("a")) - assert(processedTuple.next().getField("split").equals("b")) - assertThrows[java.util.NoSuchElementException](processedTuple.next().getField("split")) - opExec.close() - } - - // Runs the operator over one value and returns the pieces it emits. - private def unnest(delimiter: String, value: String): List[String] = { - opDesc.attribute = "field1" - opDesc.delimiter = delimiter - val exec = new UnnestStringOpExec(objectMapper.writeValueAsString(opDesc)) - // Built directly, not propagated: schema propagation now rejects the degenerate patterns - // (`.`, `|`) whose runtime behavior the tests below pin. - val schema = tupleSchema.add(new Attribute("split", AttributeType.STRING)) - val input = Tuple - .builder(tupleSchema) - .add(new Attribute("field1", AttributeType.STRING), value) - .add(new Attribute("field2", AttributeType.INTEGER), 1) - .add(new Attribute("field3", AttributeType.STRING), "a") - .build() - exec.open() - val pieces = exec - .processTuple(input, 0) - .map(_.asInstanceOf[SchemaEnforceable].enforceSchema(schema).getField[String]("split")) - .toList - exec.close() - pieces + assert(unnest("<\\d*>", targetTuple = customTuple) == List("a", "b")) } // The presets the delimiter picker offers in regex mode, exactly as it stores them. "UnnestStringOpExec with the picker's presets" should "split on a comma" in { - assert(unnest(",", "a,b,c") == List("a", "b", "c")) + assert(unnestValue(",", "a,b,c") == List("a", "b", "c")) } it should "split on a tab written as the regex escape" in { - assert(unnest("\\t", "a\tb\tc") == List("a", "b", "c")) + assert(unnestValue("\\t", "a\tb\tc") == List("a", "b", "c")) } it should "split on a tab stored as the literal character by an older workflow" in { - assert(unnest("\t", "a\tb\tc") == List("a", "b", "c")) + assert(unnestValue("\t", "a\tb\tc") == List("a", "b", "c")) } it should "split on a semicolon" in { - assert(unnest(";", "a;b;c") == List("a", "b", "c")) + assert(unnestValue(";", "a;b;c") == List("a", "b", "c")) } it should "split on an escaped pipe" in { - assert(unnest("\\|", "a|b|c") == List("a", "b", "c")) + assert(unnestValue("\\|", "a|b|c") == List("a", "b", "c")) } it should "split on any run of whitespace" in { - assert(unnest("\\s+", "a b\t c\nd") == List("a", "b", "c", "d")) + assert(unnestValue("\\s+", "a b\t c\nd") == List("a", "b", "c", "d")) } it should "split on a new line written as the regex escape" in { - assert(unnest("\\n", "a\nb\nc") == List("a", "b", "c")) + assert(unnestValue("\\n", "a\nb\nc") == List("a", "b", "c")) } "UnnestStringOpExec with a custom regex" should "split on a character class" in { - assert(unnest("[,;]", "a,b;c") == List("a", "b", "c")) + assert(unnestValue("[,;]", "a,b;c") == List("a", "b", "c")) } it should "absorb the spaces around a comma" in { - assert(unnest("\\s*,\\s*", "a , b, c") == List("a", "b", "c")) + assert(unnestValue("\\s*,\\s*", "a , b, c") == List("a", "b", "c")) } it should "split on a multi-character delimiter" in { - assert(unnest("::", "a::b::c") == List("a", "b", "c")) + assert(unnestValue("::", "a::b::c") == List("a", "b", "c")) } it should "split on an escaped dot and keep the text between dots" in { - assert(unnest("\\.", "a.b.c") == List("a", "b", "c")) + assert(unnestValue("\\.", "a.b.c") == List("a", "b", "c")) } it should "drop everything for an unescaped dot, which matches every character" in { // Why the operator rejects it at compile time: every piece is empty. - assert(unnest(".", "a.b.c") == List()) + assert(unnestValue(".", "a.b.c") == List()) } it should "leave only the line breaks of a multi-line value for an unescaped dot" in { - assert(unnest(".", "ab\ncd\r\ne") == List("\n", "\r\n")) + assert(unnestValue(".", "ab\ncd\r\ne") == List("\n", "\r\n")) } it should "leave only the line breaks of a multi-line value for anything but a line feed" in { - assert(unnest("[^\\n]", "ab\ncd") == List("\n")) + assert(unnestValue("[^\\n]", "ab\ncd") == List("\n")) } it should "split every character apart for a bare pipe, the empty alternation" in { // The operator rejects this pattern at compile time; this pins what it would have done. - assert(unnest("|", "abc") == List("a", "b", "c")) + assert(unnestValue("|", "abc") == List("a", "b", "c")) } it should "split on a non-ASCII delimiter" in { - assert(unnest("•", "a•b•c") == List("a", "b", "c")) + assert(unnestValue("•", "a•b•c") == List("a", "b", "c")) } it should "accept Java-only syntax such as a possessive quantifier" in { - assert(unnest(",++", "a,,b,c") == List("a", "b", "c")) + assert(unnestValue(",++", "a,,b,c") == List("a", "b", "c")) } }
