zio icon indicating copy to clipboard operation
zio copied to clipboard

String diff fails with NPE when one of the Strings is null

Open nightscape opened this issue 2 years ago • 3 comments

When comparing a String with null the Differ fails with a NullPointerException. Minimal repro:

import zio.Scope
import zio.test._
object StringDiffTest extends ZIOSpecDefault {
  override def spec: ZSpec[TestEnvironment with Scope, Any] =
    test("String diffing fails") {
      assertTrue("" == null)
    }
}

The reason is that DiffInstances#stringDiff tries to split the Strings at newlines, which won't work for null.

I know using null is not a best practice, but sometimes one doesn't have a choice when interacting with Java APIs... I would propose adding a special case for null at the beginning of the diffing, but I'm open to other suggestions.

nightscape avatar May 03 '22 15:05 nightscape

Ah! That's no good. Thanks for the report! What version of ZIO are you on, by the way?

kitlangton avatar May 03 '22 18:05 kitlangton

This is the behavior in RC6

import zio.test._

object StringDiffTest extends ZIOSpecDefault {
  override def spec: Spec[Any, Nothing] =
    test("String diffing fails") {
      assertTrue("" == null)
    }
}
runSpec
  - String diffing fails
    ✗ ERROR: java.lang.NullPointerException: Cannot invoke "String.split(String)" because "x" is null
      zio.test.diff.DiffInstances.zio$test$diff$DiffInstances$$$anonfun$stringDiff$1(Diff.scala:45)
      zio.test.diff.DiffInstances$$anonfun$stringDiff$6.diff(Diff.scala:41)
      zio.test.diff.DiffInstances$$anonfun$stringDiff$6.diff(Diff.scala:41)
      zio.test.internal.SmartAssertions$.$anonfun$equalTo$1(SmartAssertions.scala:286)
    "" == null
    at AnotherOne.scala:7
    ````

calvinlfer avatar May 03 '22 19:05 calvinlfer

👍 I'll add a null check before triggering diffs! You're a bug reproducing machine @calvinlfer! Henceforth, you shall be known as The Minimizer.

kitlangton avatar May 03 '22 19:05 kitlangton