Home > front end >  How to use Beam's PAssert.that(foo).satisfies(bar) in Scala?
How to use Beam's PAssert.that(foo).satisfies(bar) in Scala?

Time:11-29

The Beam Java API has a PAssert method satisfies which takes a function of type SerializableFunction<Iterable<T>, Void>

However, Java's Void isn't exactly the same as Scala's Unit, so the compiler complains if you pass something like PAssert.that(foo).satisfies(contents => contents.forEach(_.someListProperty.nonEmpty)).

You can add a asInstanceOf[Null] at the end of the forEach to get rid of the compilation error, but then it throws a runtime exception saying that it cannot cast the class to null.

If you also just explicitly return null at the end of the function, the test always evaluates to true, even if the predicate was false.

How can one use this function? Or is there another way to test that each individual element of a resulting PCollection satisfies a condition?

CodePudding user response:

I have the same issue with Kotlin code, I think the way to solve it is the same with Kotlin and Scala :

PAssert.that(result).satisfies(assertResult)

// OR
PAssert.that(result).satisfies(assertResult(_))

// OR
PAssert.that(result).satisfies(r => assertResult(r))


private def assertResult(result: Iterable<YouClass>): Void = {
        
    // Apply your assertions.

    null
}

I created a method taking the result Iterable and returning a Void, then in the function, I return null.

In the test and PAssert.that(foo).satisfies method, I can invoke the assertResult method in a lambda function.

CodePudding user response:

This quote from your question is the core issue:

If you also just explicitly return null at the end of the function, the test always evaluates to true, even if the predicate was false.

The idea of the function is that it should throw an exception if there is a problem, for example by using assertion methods. So your approach of adding an explicit return null at the end is the right way to use this directly in Scala. Adding a nice wrapper as in the other answer is good, too.

  • Related