我有以下代碼,用于(sha)在火花資料幀中散列列:
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions.{sha2,lit, col}
object hashing {
def process(hashFieldNames: List[String])(df: DataFrame) = {
hashFieldNames.foldLeft(df) { case (df, hashField) =>
df.withColumn(hashField, sha2(col(hashField), 256))
}
}
}
現在在一個單獨的檔案中,我正在hashing.process使用AnyWordSpec測驗測驗我,如下所示:
"The hashing .process " should {
// some cases here that complete succesfully
"fail to hash a spark dataframe due to type mismatch " in {
val goodColumns = Seq("language", "usersCount", "ID", "personalData")
val badDataSample =
Seq(
("Java", "20000", 2, "happy"),
("Python", "100000", 3, "happy"),
("Scala", "3000", 1, "jolly")
)
val badDf =
spark.sparkContext.parallelize(badDataSample).toDF(goodColumns: _*)
val thrown = intercept[org.apache.spark.sql.AnalysisException] {
val hashedResultDf =
hashing.process(hashFieldNames)(badDf)
}
assert (thrown.getMessage === // some lengthy error message that I do not want to copy paste in its entirety.
通常,據我所知,人們希望對整個錯誤訊息進行硬編碼,以確保它確實如我們所料。但是,訊息很長,我想知道是否沒有更好的方法。
基本上,我有兩個問題:
a.) 僅匹配錯誤訊息的開頭部分然后使用正則運算式是否被認為是一種好習慣?我在想這樣的事情:thrown.getMessage === "[cannot resolve sha2(ID, 256) due to data type mismatch: argument 1 requires binary type, however, ID is of int type.;" regexpattern \;(.*))
b.) 如果 a.) 被認為是一種 hacky 方法,您對如何正確執行此操作有任何可行的建議嗎?
注意:上面的代碼可能會出現小錯誤,我將其改編為 SO 帖子。但你應該明白這一點。
uj5u.com熱心網友回復:
好的,回答我自己的問題。我現在這樣解決了:
"fail to hash a spark dataframe due to type mismatch " in {
val goodColumns = Seq("language", "usersCount", "ID", "personalData")
val badDataSample =
Seq(
("Java", "20000", 2, "happy"),
("Python", "100000", 3, "happy"),
("Scala", "3000", 1, "jolly")
)
val badDf =
spark.sparkContext.parallelize(badDataSample).toDF(goodColumns: _*)
//val expectedErrorMessageSubstring = "sha2(`ID`, 256)' due to data type mismatch: argument 1 requires binary type".r
val thrownExcepetion = intercept[org.apache.spark.sql.AnalysisException] {
IngestionHashing.process(hashFieldNames)(badDf)
}
thrownExcepetion.getMessage should include regex "type mismatch: argument 1 requires binary type"
}
保留此帖子以獲取潛在的建議/改進。根據https://github.com/databricks/scala-style-guide#intercepting-exceptions解決方案仍然不理想。
uj5u.com熱心網友回復:
您不應該斷言例外訊息(除非它們是向用戶顯示的,或者下游依賴于它們)。如果拋出例外是合同的一部分,那么您應該拋出具有給定錯誤代碼的特定型別之一,并且測驗應該斷言這一點。如果不是,那么誰在乎資訊說了什么?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472156.html
上一篇:沒有作業節點的PySparkshell如何運行作業?
下一篇:僅顯示前20行
