我的 ScalaCheck 代码中出现了一个非常罕见但可重复的 MalformedInputException。
除了“偶尔”之外,我无法完美地确定它,或者获得可靠的复制品,但这是我认为会产生问题的代码:
// Generate varying Unicode characters:
val unicodeCharacter = Gen.choose(Char.MinValue, Char.MaxValue).filter(Character.isDefined)
// Generate varying Unicode strings across all legal characters::
def unicodeGenerator(generator: Gen[Char] = unicodeCharacter, minimum: Int = 5, maximum: Int = 20): Gen[String] = Gen.chooseNum(minimum, maximum).flatMap { n =>
Gen.sequence[String, Char](List.fill(n)(generator))
}
// The unit test that I think is occasionally blowing up:
"random strings longer than 20 characters" ! prop { (s: String) => { s.length > 20 must beTrue } }.setGen(unicodeGenerator(unicodeCharacter, 21, 30))
这是我见过的例外:
Exception in thread "Thread-391" java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:285)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:135)
at java.io.Writer.write(Writer.java:157)
at scala.xml.XML$.write(XML.scala:108)
at scala.xml.XML$$anonfun$save$2.apply$mcV$sp(XML.scala:91)
at scala.xml.XML$$anonfun$save$2.apply(XML.scala:91)
at scala.xml.XML$$anonfun$save$2.apply(XML.scala:91)
at scala.util.control.Exception$Catch.apply(Exception.scala:102)
at scala.xml.XML$.save(XML.scala:90)
at sbt.JUnitXmlTestsListener.writeSuite(JUnitXmlTestsListener.scala:170)
at sbt.JUnitXmlTestsListener.endGroup(JUnitXmlTestsListener.scala:159)
at sbt.React$$anonfun$react$8.apply(ForkTests.scala:133)
at sbt.React$$anonfun$react$8.apply(ForkTests.scala:133)
at scala.collection.immutable.List.foreach(List.scala:318)
at sbt.React.react(ForkTests.scala:133)
at sbt.ForkTests$$anonfun$mainTestTask$1$Acceptor$2$.run(ForkTests.scala:74)
at java.lang.Thread.run(Thread.java:745)
Internal error when running tests: sbt.ForkMain$Run$RunAborted: java.net.SocketException: Broken pipe
任何人都知道是什么原因造成的,更重要的是如何可靠地预防它?