-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathProtocolTests.cs
More file actions
116 lines (83 loc) · 3.04 KB
/
ProtocolTests.cs
File metadata and controls
116 lines (83 loc) · 3.04 KB
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
using GenHTTP.Api.Content;
using GenHTTP.Api.Protocol;
using GenHTTP.Modules.Basics;
using GenHTTP.Modules.IO;
namespace GenHTTP.Testing.Acceptance.Engine;
[TestClass]
public sealed class ProtocolTests
{
/// <summary>
/// As a client I can stream data to the server.
/// </summary>
[TestMethod]
[MultiEngineTest]
public async Task TestPost(TestEngine engine)
{
var recorder = new ValueRecorder();
const string str = "From client with ❤";
await using var runner = await TestHost.RunAsync(recorder.Wrap(), engine: engine);
var request = runner.GetRequest();
request.Method = HttpMethod.Post;
request.Content = new StringContent(str);
using var _ = await runner.GetResponseAsync(request);
Assert.AreEqual(str, recorder.Value);
}
/// <summary>
/// As a client I can submit large data.
/// </summary>
[TestMethod]
[MultiEngineTest]
public async Task TestPutLarge(TestEngine engine)
{
await using var runner = await TestHost.RunAsync(new ContentLengthResponder().Wrap(), engine: engine);
using var content = new MemoryStream();
var random = new Random();
var buffer = new byte[65536];
for (var i = 0; i < 20; i++) // 1.3 MB
{
random.NextBytes(buffer);
content.Write(buffer, 0, buffer.Length);
}
content.Seek(0, SeekOrigin.Begin);
var request = runner.GetRequest();
request.Method = HttpMethod.Put;
request.Content = new StreamContent(content);
using var response = await runner.GetResponseAsync(request);
Assert.AreEqual("1310720", await response.GetContentAsync());
}
private class ValueRecorder : IHandler
{
public string? Value { get; private set; }
public ValueTask PrepareAsync() => ValueTask.CompletedTask;
public ValueTask<IResponse?> HandleAsync(IRequest request)
{
if (request.Content is not null)
{
using var reader = new StreamReader(request.Content);
Value = reader.ReadToEnd();
}
return new ValueTask<IResponse?>(request.Respond().Build());
}
}
private class ContentLengthResponder : IHandler
{
public ValueTask PrepareAsync() => ValueTask.CompletedTask;
public ValueTask<IResponse?> HandleAsync(IRequest request)
{
int read;
var total = 0;
if (request.Content != null)
{
var buffer = new byte[4096];
while ((read = request.Content.Read(buffer, 0, buffer.Length)) > 0)
{
total += read;
}
}
return request.Respond()
.Content(total.ToString())
.Type(ContentType.TextPlain)
.BuildTask();
}
}
}