@@ -5,6 +5,8 @@ import MessagePack.Code
55import org .scalatest .prop .PropertyChecks
66import java .io .ByteArrayOutputStream
77import java .math .BigInteger
8+ import xerial .core .io .IOUtil
9+ import java .nio .CharBuffer
810
911/**
1012 * Created on 2014/05/07.
@@ -146,6 +148,52 @@ class MessagePackTest extends MessagePackSpec {
146148 }
147149 }
148150
151+ " report errors when packing/unpacking malformed strings" taggedAs(" malformed" ) in {
152+ // Create 100 malformed UTF8 Strings
153+ val r = new Random (0 )
154+ val malformedStrings = Iterator .continually{
155+ val b = new Array [Byte ](10 )
156+ r.nextBytes(b)
157+ b
158+ }
159+ .filter(b => ! isValidUTF8(new String (b))).take(100 )
160+
161+ for (malformedBytes <- malformedStrings) {
162+ // Pack tests
163+ val malformed = new String (malformedBytes)
164+ IOUtil .withResource(new MessagePacker (new ByteArrayOutputStream )) { packer =>
165+ try {
166+ packer.packString(malformed)
167+ fail(" should report error when malformed input string is found" )
168+ }
169+ catch {
170+ case e : MessageStringCodingException => // OK
171+ case other : Exception => fail(other)
172+ }
173+ }
174+ // Unpack tests
175+ val b = new ByteArrayOutputStream ()
176+ val packer = new MessagePacker (b)
177+ packer.packRawStringHeader(malformedBytes.length)
178+ packer.writePayload(malformedBytes)
179+ packer.close()
180+ val packed = b.toByteArray
181+
182+ IOUtil .withResource(new MessageUnpacker (packed)) { unpacker =>
183+ try {
184+ unpacker.unpackString()
185+ fail(" Should report error when malformed input string is found" )
186+ }
187+ catch {
188+ case e : MessageStringCodingException => // OK
189+ case other : Exception => fail(other)
190+ }
191+ }
192+ }
193+
194+ }
195+
196+
149197 " pack/unpack binary" taggedAs (" binary" ) in {
150198 forAll { (v : Array [Byte ]) =>
151199 check(v, { packer => packer.packBinaryHeader(v.length); packer.writePayload(v)}, { unpacker =>
0 commit comments