Add test case for growing beyond buffer size in Utf8JsonWriter (#28409) (#36917)
authorJosh Schreuder <joshschreuder@gmail.com>
Mon, 21 Sep 2020 21:45:22 +0000 (07:45 +1000)
committerGitHub <noreply@github.com>
Mon, 21 Sep 2020 21:45:22 +0000 (14:45 -0700)
* Add test case for growing beyond buffer size in Utf8JsonWriter (#28409)

* Update with review feedback

Co-authored-by: Josh Schreuder <josh.schreuder@gmail.com>
src/libraries/System.Text.Json/tests/Utf8JsonWriterTests.cs

index 5ff5373..9e966bf 100644 (file)
@@ -1381,6 +1381,31 @@ namespace System.Text.Json.Tests
             Assert.Equal(expectedString, actualString);
         }
 
+        [Theory]
+        [InlineData(true, true)]
+        [InlineData(true, false)]
+        [InlineData(false, true)]
+        [InlineData(false, false)]
+        public void GrowBeyondBufferSize(bool formatted, bool skipValidation)
+        {
+            const int InitialGrowthSize = 256;
+            var output = new FixedSizedBufferWriter(InitialGrowthSize);
+            var options = new JsonWriterOptions { Indented = formatted, SkipValidation = skipValidation };
+
+            byte[] utf8String = Encoding.UTF8.GetBytes("this is a string long enough to overflow the buffer and cause an exception to be thrown.");
+
+            using var jsonUtf8 = new Utf8JsonWriter(output, options);
+
+            jsonUtf8.WriteStartArray();
+
+            while (jsonUtf8.BytesPending < InitialGrowthSize - utf8String.Length)
+            {
+                jsonUtf8.WriteStringValue(utf8String);
+            }
+
+            Assert.Throws<InvalidOperationException>(() => jsonUtf8.WriteStringValue(utf8String));
+        }
+
         private static async Task WriteLargeToStreamHelper(Stream stream, JsonWriterOptions options)
         {
             const int SyncWriteThreshold = 25_000;