Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FormPipeReaderTests.cs « test « WebUtilities « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a34deb1d925f75d4399d07cf99d04c4c07d50c2c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using Microsoft.Extensions.Primitives;

namespace Microsoft.AspNetCore.WebUtilities
{
    public class FormPipeReaderTests
    {
        [Fact]
        public async Task ReadFormAsync_EmptyKeyAtEndAllowed()
        {
            var bodyPipe = await MakePipeReader("=bar");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("bar", formCollection[""].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_EmptyKeyWithAdditionalEntryAllowed()
        {
            var bodyPipe = await MakePipeReader("=bar&baz=2");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("bar", formCollection[""].ToString());
            Assert.Equal("2", formCollection["baz"].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_EmptyValueAtEndAllowed()
        {
            var bodyPipe = await MakePipeReader("foo=");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("", formCollection["foo"].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_EmptyValueWithoutEqualsAtEndAllowed()
        {
            var bodyPipe = await MakePipeReader("foo");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("", formCollection["foo"].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_EmptyValueWithAdditionalEntryAllowed()
        {
            var bodyPipe = await MakePipeReader("foo=&baz=2");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("", formCollection["foo"].ToString());
            Assert.Equal("2", formCollection["baz"].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_EmptyValueWithoutEqualsWithAdditionalEntryAllowed()
        {
            var bodyPipe = await MakePipeReader("foo&baz=2");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal("", formCollection["foo"].ToString());
            Assert.Equal("2", formCollection["baz"].ToString());
        }

        [Fact]
        public async Task ReadFormAsync_ValueContainsInvalidCharacters_Throw()
        {
            var bodyPipe = await MakePipeReader("%00");

            var exception = await Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe)));

            Assert.Equal("The form value contains invalid characters.", exception.Message);
            Assert.IsType<InvalidOperationException>(exception.InnerException);
        }

        [Fact]
        public async Task ReadFormAsync_ValueCountLimitMet_Success()
        {
            var bodyPipe = await MakePipeReader("foo=1&bar=2&baz=3");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 });

            Assert.Equal("1", formCollection["foo"].ToString());
            Assert.Equal("2", formCollection["bar"].ToString());
            Assert.Equal("3", formCollection["baz"].ToString());
            Assert.Equal(3, formCollection.Count);
        }

        [Fact]
        public async Task ReadFormAsync_ValueCountLimitExceeded_Throw()
        {
            var content = "foo=1&baz=2&bar=3&baz=4&baf=5";
            var bodyPipe = await MakePipeReader(content);

            var exception = await Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 }));
            Assert.Equal("Form value count limit 3 exceeded.", exception.Message);

            // The body pipe is still readable and has not advanced.
            var readResult = await bodyPipe.ReadAsync();
            Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray());
        }

        [Fact]
        public async Task ReadFormAsync_ValueCountLimitExceededSameKey_Throw()
        {
            var content = "baz=1&baz=2&baz=3&baz=4";
            var bodyPipe = await MakePipeReader(content);

            var exception = await Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueCountLimit = 3 }));
            Assert.Equal("Form value count limit 3 exceeded.", exception.Message);


            // The body pipe is still readable and has not advanced.
            var readResult = await bodyPipe.ReadAsync();
            Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray());
        }

        [Fact]
        public async Task ReadFormAsync_KeyLengthLimitMet_Success()
        {
            var bodyPipe = await MakePipeReader("fooooooooo=1&bar=2&baz=3&baz=4");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { KeyLengthLimit = 10 });

            Assert.Equal("1", formCollection["fooooooooo"].ToString());
            Assert.Equal("2", formCollection["bar"].ToString());
            Assert.Equal("3,4", formCollection["baz"].ToString());
            Assert.Equal(3, formCollection.Count);
        }

        [Fact]
        public async Task ReadFormAsync_KeyLengthLimitExceeded_Throw()
        {
            var content = "foo=1&baz12345678=2";
            var bodyPipe = await MakePipeReader(content);

            var exception = await Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe) { KeyLengthLimit = 10 }));
            Assert.Equal("Form key length limit 10 exceeded.", exception.Message);

            // The body pipe is still readable and has not advanced.
            var readResult = await bodyPipe.ReadAsync();
            Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray());
        }

        [Fact]
        public async Task ReadFormAsync_ValueLengthLimitMet_Success()
        {
            var bodyPipe = await MakePipeReader("foo=1&bar=1234567890&baz=3&baz=4");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe) { ValueLengthLimit = 10 });

            Assert.Equal("1", formCollection["foo"].ToString());
            Assert.Equal("1234567890", formCollection["bar"].ToString());
            Assert.Equal("3,4", formCollection["baz"].ToString());
            Assert.Equal(3, formCollection.Count);
        }

        [Fact]
        public async Task ReadFormAsync_ValueLengthLimitExceeded_Throw()
        {
            var content = "foo=1&baz=12345678901";
            var bodyPipe = await MakePipeReader(content);

            var exception = await Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe) { ValueLengthLimit = 10 }));
            Assert.Equal("Form value length limit 10 exceeded.", exception.Message);

            // The body pipe is still readable and has not advanced.
            var readResult = await bodyPipe.ReadAsync();
            Assert.Equal(Encoding.UTF8.GetBytes(content), readResult.Buffer.ToArray());
        }

        [Fact]
        public async Task ReadFormAsync_ValueLengthLimitExceededAcrossBufferBoundary_Throw()
        {
            Pipe bodyPipe = new Pipe();

            var content1 = "foo=1&baz=1234567890";
            var content2 = "1";

            await bodyPipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(content1));
            await bodyPipe.Writer.FlushAsync();

            var readTask = Assert.ThrowsAsync<InvalidDataException>(
                () => ReadFormAsync(new FormPipeReader(bodyPipe.Reader) { ValueLengthLimit = 10 }));

            await bodyPipe.Writer.WriteAsync(Encoding.UTF8.GetBytes(content2));
            bodyPipe.Writer.Complete();

            var exception = await readTask;
            Assert.Equal("Form value length limit 10 exceeded.", exception.Message);

            // The body pipe is still readable and has not advanced.
            var readResult = await bodyPipe.Reader.ReadAsync();
            Assert.Equal(Encoding.UTF8.GetBytes("baz=12345678901"), readResult.Buffer.ToArray());
        }

        // https://en.wikipedia.org/wiki/Percent-encoding
        [Theory]
        [InlineData("++=hello", "  ", "hello")]
        [InlineData("a=1+1", "a", "1 1")]
        [InlineData("%22%25%2D%2E%3C%3E%5C%5E%5F%60%7B%7C%7D%7E=%22%25%2D%2E%3C%3E%5C%5E%5F%60%7B%7C%7D%7E", "\"%-.<>\\^_`{|}~", "\"%-.<>\\^_`{|}~")]
        [InlineData("a=%41", "a", "A")] // ascii encoded hex
        [InlineData("a=%C3%A1", "a", "\u00e1")] // utf8 code points
        [InlineData("a=%u20AC", "a", "%u20AC")] // utf16 not supported
        public async Task ReadForm_Decoding(string formData, string key, string expectedValue)
        {
            var bodyPipe = await MakePipeReader(text: formData);

            var form = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Equal(expectedValue, form[key]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_SingleSegmentWorks(Encoding encoding)
        {
            var readOnlySequence = new ReadOnlySequence<byte>(encoding.GetBytes("foo=bar&baz=boo"));

            KeyValueAccumulator accumulator = default;
            var formReader = new FormPipeReader(null!, encoding);

            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(2, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_Works(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
            Assert.Equal("", dict["t"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_LimitsCanBeLarge(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.KeyLengthLimit = int.MaxValue;
            formReader.ValueLengthLimit = int.MaxValue;
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: false);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
            Assert.Equal("", dict["t"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_SplitAcrossSegmentsWorks(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
            Assert.Equal("", dict["t"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_SplitAcrossSegmentsWorks_LimitsCanBeLarge(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.KeyLengthLimit = int.MaxValue;
            formReader.ValueLengthLimit = int.MaxValue;
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: false);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
            Assert.Equal("", dict["t"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_MultiSegmentWithArrayPoolAcrossSegmentsWorks(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("foo=bar&baz=bo" + new string('a', 128)));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(2, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("bo" + new string('a', 128), dict["baz"]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_MultiSegmentSplitAcrossSegmentsWithPlusesWorks(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("+++=+++&++++=++++&+="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("    ", dict["    "]);
            Assert.Equal("   ", dict["   "]);
            Assert.Equal("", dict[" "]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_DecodedPlusesWorks(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(encoding.GetBytes("++%2B=+++%2B&++++=++++&+="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(3, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("    ", dict["    "]);
            Assert.Equal("   +", dict["  +"]);
            Assert.Equal("", dict[" "]);
        }

        [Theory]
        [MemberData(nameof(Encodings))]
        public void TryParseFormValues_SplitAcrossSegmentsThatNeedDecodingWorks(Encoding encoding)
        {
            var readOnlySequence = ReadOnlySequenceFactory.SegmentPerByteFactory.CreateWithContent(encoding.GetBytes("\"%-.<>\\^_`{|}~=\"%-.<>\\^_`{|}~&\"%-.<>\\^_`{|}=wow"));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!, encoding);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(2, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("\"%-.<>\\^_`{|}~", dict["\"%-.<>\\^_`{|}~"]);
            Assert.Equal("wow", dict["\"%-.<>\\^_`{|}"]);
        }

        [Fact]
        public void TryParseFormValues_MultiSegmentFastPathWorks()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=bar&"), Encoding.UTF8.GetBytes("baz=boo"));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            Assert.Equal(2, accumulator.KeyCount);
            var dict = accumulator.GetResults();
            Assert.Equal("bar", dict["foo"]);
            Assert.Equal("boo", dict["baz"]);
        }

        [Fact]
        public void TryParseFormValues_ExceedKeyLengthThrows()
        {
            var readOnlySequence = ReadOnlySequenceFactory.SingleSegmentFactory.CreateWithContent(Encoding.UTF8.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.KeyLengthLimit = 2;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form key length limit 2 exceeded.", exception.Message);
        }

        [Fact]
        public void TryParseFormValues_ExceedKeyLengthThrowsInSplitSegment()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&ba"), Encoding.UTF8.GetBytes("z=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.KeyLengthLimit = 2;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form key length limit 2 exceeded.", exception.Message);
        }

        [Fact]
        public void TryParseFormValues_ExceedValueLengthThrows()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=bar&baz=boo&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.ValueLengthLimit = 2;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form value length limit 2 exceeded.", exception.Message);
        }

        [Fact]
        public void TryParseFormValues_ExceedValueLengthThrowsInSplitSegment()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&t="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.ValueLengthLimit = 2;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form value length limit 2 exceeded.", exception.Message);
        }

        [Fact]
        public void TryParseFormValues_ExceedKeyLengthThrowsInSplitSegmentEnd()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&asdfasdfasd="));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.KeyLengthLimit = 10;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form key length limit 10 exceeded.", exception.Message);
        }

        [Fact]
        public void TryParseFormValues_ExceedValueLengthThrowsInSplitSegmentEnd()
        {
            var readOnlySequence = ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("foo=ba&baz=bo"), Encoding.UTF8.GetBytes("o&t=asdfasdfasd"));

            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!);
            formReader.ValueLengthLimit = 10;

            var exception = Assert.Throws<InvalidDataException>(() => formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true));
            Assert.Equal("Form value length limit 10 exceeded.", exception.Message);
        }

        [Fact]
        public async Task ResetPipeWorks()
        {
            // Same test that is in the benchmark
            var pipe = new Pipe();
            var bytes = Encoding.UTF8.GetBytes("foo=bar&baz=boo");

            for (var i = 0; i < 1000; i++)
            {
                pipe.Writer.Write(bytes);
                pipe.Writer.Complete();
                var formReader = new FormPipeReader(pipe.Reader);
                await formReader.ReadFormAsync();
                pipe.Reader.Complete();
                pipe.Reset();
            }
        }

        [Theory]
        [MemberData(nameof(IncompleteFormKeys))]
        public void ParseFormWithIncompleteKeyWhenIsFinalBlockSucceeds(ReadOnlySequence<byte> readOnlySequence)
        {
            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!)
            {
                KeyLengthLimit = 3
            };

            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            IDictionary<string, StringValues> values = accumulator.GetResults();
            Assert.Contains("fo", values);
            Assert.Equal("bar", values["fo"]);
            Assert.Contains("ba", values);
            Assert.Equal("", values["ba"]);
        }

        [Theory]
        [MemberData(nameof(IncompleteFormValues))]
        public void ParseFormWithIncompleteValueWhenIsFinalBlockSucceeds(ReadOnlySequence<byte> readOnlySequence)
        {
            KeyValueAccumulator accumulator = default;

            var formReader = new FormPipeReader(null!)
            {
                ValueLengthLimit = 3
            };

            formReader.ParseFormValues(ref readOnlySequence, ref accumulator, isFinalBlock: true);
            Assert.True(readOnlySequence.IsEmpty);

            IDictionary<string, StringValues> values = accumulator.GetResults();
            Assert.Contains("fo", values);
            Assert.Equal("bar", values["fo"]);
            Assert.Contains("b", values);
            Assert.Equal("", values["b"]);
        }

        [Fact]
        public async Task ReadFormAsync_AccumulatesEmptyKeys()
        {
            var bodyPipe = await MakePipeReader("&&&");

            var formCollection = await ReadFormAsync(new FormPipeReader(bodyPipe));

            Assert.Single(formCollection);
        }

        public static TheoryData<ReadOnlySequence<byte>> IncompleteFormKeys =>
            new TheoryData<ReadOnlySequence<byte>>
            {
                { ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&b"), Encoding.UTF8.GetBytes("a"))  },
                { new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("fo=bar&ba")) }
            };

        public static TheoryData<ReadOnlySequence<byte>> IncompleteFormValues =>
            new TheoryData<ReadOnlySequence<byte>>
            {
                { ReadOnlySequenceFactory.CreateSegments(Encoding.UTF8.GetBytes("fo=bar&b"), Encoding.UTF8.GetBytes("="))  },
                { new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes("fo=bar&b=")) }
            };

        public static TheoryData<Encoding> Encodings =>
                 new TheoryData<Encoding>
                 {
                     { Encoding.UTF8 },
                     { Encoding.UTF32 },
                     { Encoding.ASCII },
                     { Encoding.Unicode }
                 };

        internal virtual Task<Dictionary<string, StringValues>> ReadFormAsync(FormPipeReader reader)
        {
            return reader.ReadFormAsync();
        }

        private static async Task<PipeReader> MakePipeReader(string text)
        {
            var formContent = Encoding.UTF8.GetBytes(text);
            Pipe bodyPipe = new Pipe();

            await bodyPipe.Writer.WriteAsync(formContent);

            // Complete the writer so the reader will complete after processing all data.
            bodyPipe.Writer.Complete();
            return bodyPipe.Reader;
        }
    }
}