|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.sql |
| 19 | + |
| 20 | +import java.util.TimeZone |
| 21 | + |
| 22 | +import scala.jdk.CollectionConverters._ |
| 23 | +import scala.language.implicitConversions |
| 24 | + |
| 25 | +import org.scalatest.Assertions |
| 26 | + |
| 27 | +import org.apache.spark.util.{SparkErrorUtils, SparkStringUtils} |
| 28 | +import org.apache.spark.util.ArrayImplicits._ |
| 29 | + |
| 30 | +trait CheckAnswerHelper extends Assertions { |
| 31 | + |
| 32 | + /** |
| 33 | + * Runs the plan and makes sure the answer matches the expected result. |
| 34 | + * |
| 35 | + * @param df the DataFrame to be executed |
| 36 | + * @param expectedAnswer the expected result in a Seq of Rows. |
| 37 | + */ |
| 38 | + protected def checkAnswer(df: => DataFrame, expectedAnswer: Seq[Row]): Unit = { |
| 39 | + getErrorMessageInCheckAnswer(df, expectedAnswer) match { |
| 40 | + case Some(errorMessage) => fail(errorMessage) |
| 41 | + case None => |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + protected def checkAnswer(df: => DataFrame, expectedAnswer: Row): Unit = { |
| 46 | + checkAnswer(df, Seq(expectedAnswer)) |
| 47 | + } |
| 48 | + |
| 49 | + protected def checkAnswer(df: => DataFrame, expectedAnswer: DataFrame): Unit = { |
| 50 | + checkAnswer(df, expectedAnswer.collect().toImmutableArraySeq) |
| 51 | + } |
| 52 | + |
| 53 | + protected def checkAnswer(df: => DataFrame, expectedAnswer: Array[Row]): Unit = { |
| 54 | + checkAnswer(df, expectedAnswer.toImmutableArraySeq) |
| 55 | + } |
| 56 | + |
| 57 | + protected def checkAnswer(df: DataFrame, expectedAnswer: java.util.List[Row]): Unit = { |
| 58 | + checkAnswer(df, expectedAnswer.asScala.toSeq) |
| 59 | + } |
| 60 | + |
| 61 | + protected def isDfSorted(df: DataFrame): Boolean |
| 62 | + |
| 63 | + /** |
| 64 | + * Runs the plan and makes sure the answer matches the expected result. |
| 65 | + * If there was exception during the execution or the contents of the DataFrame does not |
| 66 | + * match the expected result, an error message will be returned. Otherwise, a None will |
| 67 | + * be returned. |
| 68 | + * |
| 69 | + * @param df the DataFrame to be executed |
| 70 | + * @param expectedAnswer the expected result in a Seq of Rows. |
| 71 | + */ |
| 72 | + private def getErrorMessageInCheckAnswer( |
| 73 | + df: DataFrame, |
| 74 | + expectedAnswer: Seq[Row]): Option[String] = { |
| 75 | + val sparkAnswer = try df.collect().toSeq catch { |
| 76 | + case e: Exception => |
| 77 | + val errorMessage = |
| 78 | + s""" |
| 79 | + |Exception thrown while executing query: |
| 80 | + |${df.queryExecution} |
| 81 | + |== Exception == |
| 82 | + |$e |
| 83 | + |${SparkErrorUtils.stackTraceToString(e)} |
| 84 | + """.stripMargin |
| 85 | + return Some(errorMessage) |
| 86 | + } |
| 87 | + |
| 88 | + sameRows(expectedAnswer, sparkAnswer, isDfSorted(df)).map { results => |
| 89 | + s""" |
| 90 | + |Results do not match for query: |
| 91 | + |Timezone: ${TimeZone.getDefault} |
| 92 | + |Timezone Env: ${sys.env.getOrElse("TZ", "")} |
| 93 | + | |
| 94 | + |${df.queryExecution} |
| 95 | + |== Results == |
| 96 | + |$results |
| 97 | + """.stripMargin |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + private def prepareAnswer(answer: Seq[Row], isSorted: Boolean): Seq[Row] = { |
| 102 | + // Converts data to types that we can do equality comparison using Scala collections. |
| 103 | + // For BigDecimal type, the Scala type has a better definition of equality test (similar to |
| 104 | + // Java's java.math.BigDecimal.compareTo). |
| 105 | + // For binary arrays, we convert it to Seq to avoid of calling java.util.Arrays.equals for |
| 106 | + // equality test. |
| 107 | + val converted: Seq[Row] = answer.map(prepareRow) |
| 108 | + if (!isSorted) converted.sortBy(_.toString()) else converted |
| 109 | + } |
| 110 | + |
| 111 | + // We need to call prepareRow recursively to handle schemas with struct types. |
| 112 | + private def prepareRow(row: Row): Row = { |
| 113 | + Row.fromSeq(row.toSeq.map { |
| 114 | + case null => null |
| 115 | + case bd: java.math.BigDecimal => BigDecimal(bd) |
| 116 | + // Equality of WrappedArray differs for AnyVal and AnyRef in Scala 2.12.2+ |
| 117 | + case seq: Seq[_] => seq.map { |
| 118 | + case b: java.lang.Byte => b.byteValue |
| 119 | + case s: java.lang.Short => s.shortValue |
| 120 | + case i: java.lang.Integer => i.intValue |
| 121 | + case l: java.lang.Long => l.longValue |
| 122 | + case f: java.lang.Float => f.floatValue |
| 123 | + case d: java.lang.Double => d.doubleValue |
| 124 | + case x => x |
| 125 | + } |
| 126 | + // Convert array to Seq for easy equality check. |
| 127 | + case b: Array[_] => b.toSeq |
| 128 | + case r: Row => prepareRow(r) |
| 129 | + // SPARK-51349: "null" and null had the same precedence in sorting |
| 130 | + case "null" => "__null_string__" |
| 131 | + case o => o |
| 132 | + }) |
| 133 | + } |
| 134 | + |
| 135 | + private def genError( |
| 136 | + expectedAnswer: Seq[Row], |
| 137 | + sparkAnswer: Seq[Row], |
| 138 | + isSorted: Boolean = false): String = { |
| 139 | + val getRowType: Option[Row] => String = row => |
| 140 | + row.map(row => |
| 141 | + if (row.schema == null) { |
| 142 | + "struct<>" |
| 143 | + } else { |
| 144 | + s"${row.schema.catalogString}" |
| 145 | + }).getOrElse("struct<>") |
| 146 | + |
| 147 | + s""" |
| 148 | + |== Results == |
| 149 | + |${ |
| 150 | + SparkStringUtils.sideBySide( |
| 151 | + s"== Correct Answer - ${expectedAnswer.size} ==" +: |
| 152 | + getRowType(expectedAnswer.headOption) +: |
| 153 | + prepareAnswer(expectedAnswer, isSorted).map(_.toString()), |
| 154 | + s"== Spark Answer - ${sparkAnswer.size} ==" +: |
| 155 | + getRowType(sparkAnswer.headOption) +: |
| 156 | + prepareAnswer(sparkAnswer, isSorted).map(_.toString())).mkString("\n") |
| 157 | + } |
| 158 | + """.stripMargin |
| 159 | + } |
| 160 | + |
| 161 | + private def compare(obj1: Any, obj2: Any): Boolean = (obj1, obj2) match { |
| 162 | + case (null, null) => true |
| 163 | + case (null, _) => false |
| 164 | + case (_, null) => false |
| 165 | + case (a: Array[_], b: Array[_]) => |
| 166 | + a.length == b.length && a.zip(b).forall { case (l, r) => compare(l, r)} |
| 167 | + case (a: Map[_, _], b: Map[_, _]) => |
| 168 | + a.size == b.size && a.keys.forall { aKey => |
| 169 | + b.keys.find(bKey => compare(aKey, bKey)).exists(bKey => compare(a(aKey), b(bKey))) |
| 170 | + } |
| 171 | + case (a: Iterable[_], b: Iterable[_]) => |
| 172 | + a.size == b.size && a.zip(b).forall { case (l, r) => compare(l, r)} |
| 173 | + case (a: Product, b: Product) => |
| 174 | + compare(a.productIterator.toSeq, b.productIterator.toSeq) |
| 175 | + case (a: Row, b: Row) => |
| 176 | + compare(a.toSeq, b.toSeq) |
| 177 | + // 0.0 == -0.0, turn float/double to bits before comparison, to distinguish 0.0 and -0.0. |
| 178 | + // in some hardware NaN can be represented with different bits, so first check for it |
| 179 | + case (a: Double, b: Double) => |
| 180 | + a.isNaN && b.isNaN || |
| 181 | + java.lang.Double.doubleToRawLongBits(a) == java.lang.Double.doubleToRawLongBits(b) |
| 182 | + case (a: Float, b: Float) => |
| 183 | + a.isNaN && b.isNaN || |
| 184 | + java.lang.Float.floatToRawIntBits(a) == java.lang.Float.floatToRawIntBits(b) |
| 185 | + case (a, b) => a == b |
| 186 | + } |
| 187 | + |
| 188 | + private def sameRows( expectedAnswer: Seq[Row], |
| 189 | + sparkAnswer: Seq[Row], |
| 190 | + isSorted: Boolean = false): Option[String] = { |
| 191 | + if (!compare(prepareAnswer(expectedAnswer, isSorted), prepareAnswer(sparkAnswer, isSorted))) { |
| 192 | + return Some(genError(expectedAnswer, sparkAnswer, isSorted)) |
| 193 | + } |
| 194 | + None |
| 195 | + } |
| 196 | +} |
0 commit comments