Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

assertion - Scala unit test to check boolean value conversion

I am converting a column containing 1 and 0 to Boolean type and I want to add a test (using assert) if all the 1's are converted to True and all 0's are converted to False. How can I do this?

sourcedf
id    col_int
156   0
157   1

targetdf
id    col_boolean
156   false
157   true
question from:https://stackoverflow.com/questions/65904618/scala-unit-test-to-check-boolean-value-conversion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am using the mapIntToBoolean method to convert 1 and 0 to Boolean, and throw a RuntimeException if the number is not 1 or 0. Then I convert the maps to Set using toSet and use diff to check the differences.

import org.scalatest.funsuite.AnyFunSuite

class IntToBolleanConversionSpec extends AnyFunSuite {
  // one random map
  val map0: Map[Int, Int] = Map((120 -> 1), (121 -> 1), (122 -> 0), (123 -> 0))
  // two maps that suppose to be equal
  val map1: Map[Int, Int] = Map((120 -> 1), (121 -> 1), (122 -> 0), (123 -> 0), (124 -> 1))
  val map2: Map[Int, Boolean] = Map((120 -> true), (121 -> true), (122 -> false), (123 -> false), (124 -> true))

  def mapIntToBoolean(m1: Map[Int, Int]): Map[Int, Boolean] = {
    m1.map { v =>
      val newValue = {
        if (v._2 == 1) true
        else if (v._2 == 0) false
        else {
          new RuntimeException("value is not 1 or 0")
          false
        }
      }
      (v._1 -> newValue)
    }
  }

  test("test map intToBoolean converts correctly") {

    val map3: Map[Int, Boolean] = mapIntToBoolean(map1)
    map3.foreach(println)
    val diff: Map[Int, Boolean] = (map2.toSet diff map3.toSet).toMap
    println("difference must be 0")
    assertResult(0L)(diff.size)

    val map4: Map[Int, Boolean] = mapIntToBoolean(map0)
    map4.foreach(println)
    val diff1: Map[Int, Boolean] = (map2.toSet diff map4.toSet).toMap
    println("difference must be 1")
    assertResult(1L)(diff1.size)
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...