-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWebSocketTests.cs
More file actions
198 lines (169 loc) · 8.02 KB
/
Copy pathWebSocketTests.cs
File metadata and controls
198 lines (169 loc) · 8.02 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
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
using System.Net;
using Microsoft.Extensions.Hosting;
#if NET48 || NETCOREAPP2_1
using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;
#endif
namespace Tests.Middleware;
public class WebSocketTests : IDisposable
{
private TestServer _server = null!;
private void Configure(Action<GraphQLHttpMiddlewareOptions>? configureOptions = null, Action<IServiceCollection>? configureServices = null)
{
configureOptions ??= _ => { };
configureServices ??= _ => { };
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<Chat.Services.ChatService>();
services.AddGraphQL(b => b
.AddAutoSchema<Chat.Schema.Query>(s => s
.WithMutation<Chat.Schema.Mutation>()
.WithSubscription<Chat.Schema.Subscription>())
.AddSchema<Schema2>()
.AddSystemTextJson());
configureServices(services);
});
hostBuilder.Configure(app => {
app.UseWebSockets();
app.UseGraphQL("/graphql", configureOptions);
app.UseGraphQL<Schema2>("/graphql2", configureOptions);
});
_server = new TestServer(hostBuilder);
}
private class Schema2 : Schema
{
public Schema2()
{
Query = new AutoRegisteringObjectGraphType<Query2>();
}
}
private class Query2
{
public static string? Var(string? test) => test;
public static string? Ext(IResolveFieldContext context)
=> context.InputExtensions.TryGetValue("test", out var value) ? value?.ToString() : null;
}
public void Dispose() => _server?.Dispose();
private WebSocketClient BuildClient(string subProtocol = "graphql-ws")
{
var webSocketClient = _server.CreateWebSocketClient();
webSocketClient.ConfigureRequest = request => {
request.Headers["Sec-WebSocket-Protocol"] = subProtocol;
};
webSocketClient.SubProtocols.Add(subProtocol);
return webSocketClient;
}
[Fact]
public async Task NoConfiguredHandlers()
{
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<Chat.Services.ChatService>();
services.AddGraphQL(b => b
.AddSchema<Schema2>()
.AddSystemTextJson());
});
hostBuilder.Configure(app => {
app.UseWebSockets();
app.UseGraphQL<TestMiddleware>("/graphql", new object[] { new string[] { } });
});
_server = new TestServer(hostBuilder);
var webSocketClient = BuildClient();
var error = await Should.ThrowAsync<InvalidOperationException>(() => webSocketClient.ConnectAsync(new Uri(_server.BaseAddress, "/graphql"), default));
error.Message.ShouldBe("Incomplete handshake, status code: 404");
}
[Fact]
public async Task UnsupportedHandler()
{
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<Chat.Services.ChatService>();
services.AddGraphQL(b => b
.AddSchema<Schema2>()
.AddSystemTextJson());
});
hostBuilder.Configure(app => {
app.UseWebSockets();
app.UseGraphQL<TestMiddleware>("/graphql", new object[] { new string[] { "unsupported" } });
});
_server = new TestServer(hostBuilder);
var webSocketClient = BuildClient();
var error = await Should.ThrowAsync<InvalidOperationException>(() => webSocketClient.ConnectAsync(new Uri(_server.BaseAddress, "/graphql"), default));
error.Message.ShouldBe("Incomplete handshake, status code: 400");
}
private class TestMiddleware : GraphQLHttpMiddleware
{
private readonly string[] _subprotocols;
#pragma warning disable CS0618 // Type or member is obsolete
public TestMiddleware(RequestDelegate next, string[] subprotocols) : base(next, new GraphQLSerializer(), Mock.Of<IDocumentExecuter>(MockBehavior.Strict), Mock.Of<IServiceScopeFactory>(MockBehavior.Strict), new GraphQLHttpMiddlewareOptions(), Mock.Of<IHostApplicationLifetime>(MockBehavior.Strict))
#pragma warning restore CS0618 // Type or member is obsolete
{
_subprotocols = subprotocols;
}
protected override IEnumerable<string> SupportedWebSocketSubProtocols => _subprotocols;
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task AppShuttingDownReturns(bool beforeConnect)
{
var tuple = new Tuple<CancellationTokenSource, TaskCompletionSource<bool>>(new(), new());
var hostBuilder = new WebHostBuilder();
hostBuilder.ConfigureServices(services => {
services.AddSingleton<Chat.Services.ChatService>();
services.AddGraphQL(b => b
.AddSchema<Schema2>()
.AddSystemTextJson());
services.AddSingleton(tuple);
});
hostBuilder.Configure(app => {
app.UseWebSockets();
var options = new GraphQLHttpMiddlewareOptions();
options.WebSockets.ConnectionInitWaitTimeout = Timeout.InfiniteTimeSpan;
app.UseGraphQL<TestMiddleware2>("/graphql", options);
});
_server = new TestServer(hostBuilder);
var webSocketClient = BuildClient();
if (beforeConnect) {
tuple.Item1.Cancel();
using var socket = await webSocketClient.ConnectAsync(new Uri(_server.BaseAddress, "/graphql"), default);
await tuple.Item2.Task;
} else {
using var socket = await webSocketClient.ConnectAsync(new Uri(_server.BaseAddress, "/graphql"), default);
await Task.WhenAny(Task.Delay(1000), tuple.Item2.Task);
tuple.Item2.Task.IsCompleted.ShouldBeFalse();
tuple.Item1.Cancel();
await tuple.Item2.Task;
}
}
private class TestMiddleware2 : GraphQLHttpMiddleware
{
private readonly Tuple<CancellationTokenSource, TaskCompletionSource<bool>> _tuple;
#pragma warning disable CS0618 // Type or member is obsolete
public TestMiddleware2(RequestDelegate next, IGraphQLTextSerializer serializer, IDocumentExecuter<ISchema> documentExecuter, IServiceScopeFactory serviceScopeFactory, GraphQLHttpMiddlewareOptions options, Tuple<CancellationTokenSource, TaskCompletionSource<bool>> tuple)
: this(next, serializer, documentExecuter, serviceScopeFactory, options, Mock.Of<IHostApplicationLifetime>(MockBehavior.Strict), tuple)
{
}
private TestMiddleware2(RequestDelegate next, IGraphQLTextSerializer serializer, IDocumentExecuter<ISchema> documentExecuter, IServiceScopeFactory serviceScopeFactory, GraphQLHttpMiddlewareOptions options, IHostApplicationLifetime hostApplicationLifetime, Tuple<CancellationTokenSource, TaskCompletionSource<bool>> tuple)
#pragma warning restore CS0618 // Type or member is obsolete
: base(next, serializer, documentExecuter, serviceScopeFactory, options, hostApplicationLifetime)
{
Mock.Get(hostApplicationLifetime).Setup(x => x.ApplicationStopping).Returns(tuple.Item1.Token);
_tuple = tuple;
}
protected override async Task HandleWebSocketAsync(HttpContext context, RequestDelegate next)
{
await base.HandleWebSocketAsync(context, next);
// this test also verifies that OCE isn't thrown when the app stopping token is triggered
// because otherwise this line wouldn't run
_tuple.Item2.SetResult(true);
}
}
[Fact]
public async Task Disabled()
{
Configure(o => o.HandleWebSockets = false);
var webSocketClient = BuildClient();
var error = await Should.ThrowAsync<InvalidOperationException>(() => webSocketClient.ConnectAsync(new Uri(_server.BaseAddress, "/graphql"), default));
error.Message.ShouldBe("Incomplete handshake, status code: 404");
}
}