-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathGrpcServiceTests.cs
313 lines (266 loc) · 12.5 KB
/
GrpcServiceTests.cs
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
# if NETCOREAPP3_1
using Grpc.Core;
using ProtoBuf.Grpc.Server;
using System;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Grpc.Net.Client;
using ProtoBuf.Grpc.Client;
using ProtoBuf.Grpc.Configuration;
using Xunit;
using Grpc.Core.Interceptors;
using Xunit.Abstractions;
using System.Runtime.CompilerServices;
using ProtoBuf.Meta;
namespace protobuf_net.Grpc.Test.Integration
{
[DataContract]
public class Apply
{
public Apply() { }
public Apply(int x, int y) => (X, Y) = (x, y);
[DataMember(Order = 1)]
public int X { get; set; }
[DataMember(Order = 2)]
public int Y { get; set; }
}
[DataContract]
public class ApplyResponse
{
public ApplyResponse() { }
public ApplyResponse(int result) => Result = result;
[DataMember(Order = 1)]
public int Result { get; set; }
}
public class ApplyServices : IGrpcService
{
public Task<ApplyResponse> Add(Apply request) => Task.FromResult(new ApplyResponse(request.X + request.Y));
public Task<ApplyResponse> Mul(Apply request) => Task.FromResult(new ApplyResponse(request.X * request.Y));
public Task<ApplyResponse> Sub(Apply request) => Task.FromResult(new ApplyResponse(request.X - request.Y));
public Task<ApplyResponse> Div(Apply request) => Task.FromResult(new ApplyResponse(request.X / request.Y));
}
[Service]
public interface IInterceptedService
{
ValueTask<ApplyResponse> Add(Apply request);
}
public class InterceptedService : IInterceptedService
{
public ValueTask<ApplyResponse> Add(Apply request) => new ValueTask<ApplyResponse>(new ApplyResponse(request.X + request.Y));
}
[Serializable]
public class AdhocRequest
{
public int X { get; set; }
public int Y { get; set; }
}
[Serializable]
public class AdhocResponse
{
public int Z { get; set; }
}
[Service]
public interface IAdhocService
{
AdhocResponse AdhocMethod(AdhocRequest request);
}
public class AdhocService : IAdhocService
{
public AdhocResponse AdhocMethod(AdhocRequest request)
=> new AdhocResponse { Z = request.X + request.Y };
}
static class AdhocConfig
{
public static ClientFactory ClientFactory { get; }
= ClientFactory.Create(BinderConfiguration.Create(new[] {
// we'll allow multiple marshallers to take a stab; protobuf-net first,
// then try BinaryFormatter for anything that protobuf-net can't handle
ProtoBufMarshallerFactory.Default,
#pragma warning disable CS0618 // Type or member is obsolete
BinaryFormatterMarshallerFactory.Default, // READ THE NOTES ON NOT DOING THIS
#pragma warning restore CS0618 // Type or member is obsolete
}));
}
public class GrpcServiceFixture : IAsyncDisposable
{
public const int Port = 10042;
private readonly Server _server;
private readonly Interceptor _interceptor;
public ITestOutputHelper? Output { get; set; }
public void Log(string message) => Output?.WriteLine(message);
public GrpcServiceFixture()
{
_interceptor = new TestInterceptor(this);
#pragma warning disable CS0618 // Type or member is obsolete
BinaryFormatterMarshallerFactory.I_Have_Read_The_Notes_On_Not_Using_BinaryFormatter = true;
BinaryFormatterMarshallerFactory.I_Promise_Not_To_Do_This = true; // signed: Marc Gravell
#pragma warning restore CS0618 // Type or member is obsolete
_server = new Server
{
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
_server.Services.AddCodeFirst(new ApplyServices());
_server.Services.AddCodeFirst(new AdhocService(), AdhocConfig.ClientFactory);
_server.Services.AddCodeFirst(new InterceptedService(), interceptors: new[] { _interceptor });
_server.Start();
}
public async ValueTask DisposeAsync()
{
await _server.ShutdownAsync();
}
}
public class TestInterceptor : Interceptor
{
private readonly GrpcServiceFixture _parent;
public void Log(string message) => _parent?.Log(message);
public TestInterceptor(GrpcServiceFixture parent) => _parent = parent;
private static string Me([CallerMemberName] string? caller = null) => caller ?? "(unknown)";
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
{
Log($"> {Me()}");
var result = await base.UnaryServerHandler(request, context, continuation);
Log($"< {Me()}");
return result;
}
}
public class GrpcServiceTests : IClassFixture<GrpcServiceFixture>, IDisposable
{
private readonly GrpcServiceFixture _fixture;
public GrpcServiceTests(GrpcServiceFixture fixture, ITestOutputHelper log)
{
_fixture = fixture;
if (fixture != null) fixture.Output = log;
}
private void Log(string message) => _fixture?.Log(message);
public void Dispose()
{
if (_fixture != null) _fixture.Output = null;
}
private static readonly ProtoBufMarshallerFactory
EnableContextualSerializer = (ProtoBufMarshallerFactory)ProtoBufMarshallerFactory.Create(userState: new object()),
DisableContextualSerializer = (ProtoBufMarshallerFactory)ProtoBufMarshallerFactory.Create(options: ProtoBufMarshallerFactory.Options.DisableContextualSerializer, userState: new object());
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task CanCallAllApplyServicesUnaryAsync(bool disableContextual)
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new Apply { X = 6, Y = 3 };
var marshaller = disableContextual ? DisableContextualSerializer : EnableContextualSerializer;
var client = new GrpcClient(http, nameof(ApplyServices), BinderConfiguration.Create(new[] { marshaller }));
Assert.Equal(nameof(ApplyServices), client.ToString());
#if DEBUG
var uplevelReadsBefore = marshaller.UplevelBufferReadCount;
var uplevelWritesBefore = marshaller.UplevelBufferWriteCount;
Log($"Buffer usage before: {uplevelReadsBefore}/{uplevelWritesBefore}");
#endif
var response = await client.UnaryAsync<Apply, ApplyResponse>(request, nameof(ApplyServices.Add));
Assert.Equal(9, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, nameof(ApplyServices.Mul));
Assert.Equal(18, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, nameof(ApplyServices.Sub));
Assert.Equal(3, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, nameof(ApplyServices.Div));
Assert.Equal(2, response.Result);
#if DEBUG
var uplevelReadsAfter = marshaller.UplevelBufferReadCount;
var uplevelWritesAfter = marshaller.UplevelBufferWriteCount;
Log($"Buffer usage after: {uplevelReadsAfter}/{uplevelWritesAfter}");
#if PROTOBUFNET_BUFFERS
bool expectContextual = true;
#else
bool expectContextual = false;
#endif
if (disableContextual) expectContextual = false;
if (expectContextual)
{
Assert.True(uplevelReadsBefore < uplevelReadsAfter);
Assert.True(uplevelWritesBefore < uplevelWritesAfter);
}
else
{
Assert.Equal(uplevelReadsBefore, uplevelReadsAfter);
Assert.Equal(uplevelWritesBefore, uplevelWritesAfter);
}
#endif
}
[Fact]
public async Task CanCallAllApplyServicesTypedUnaryAsync()
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new Apply { X = 6, Y = 3 };
var client = http.CreateGrpcService(typeof(ApplyServices));
Assert.Equal(nameof(ApplyServices), client.ToString());
var response = await client.UnaryAsync<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Add)));
Assert.Equal(9, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Mul)));
Assert.Equal(18, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Sub)));
Assert.Equal(3, response.Result);
response = await client.UnaryAsync<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Div)));
Assert.Equal(2, response.Result);
static MethodInfo GetMethod(string name) => typeof(ApplyServices).GetMethod(name)!;
}
[Fact]
public void CanCallAllApplyServicesUnarySync()
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new Apply { X = 6, Y = 3 };
var client = new GrpcClient(http, nameof(ApplyServices));
Assert.Equal(nameof(ApplyServices), client.ToString());
var response = client.BlockingUnary<Apply, ApplyResponse>(request, nameof(ApplyServices.Add));
Assert.Equal(9, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, nameof(ApplyServices.Mul));
Assert.Equal(18, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, nameof(ApplyServices.Sub));
Assert.Equal(3, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, nameof(ApplyServices.Div));
Assert.Equal(2, response.Result);
}
[Fact]
public void CanCallAllApplyServicesTypedUnarySync()
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new Apply { X = 6, Y = 3 };
var client = new GrpcClient(http, typeof(ApplyServices));
Assert.Equal(nameof(ApplyServices), client.ToString());
var response = client.BlockingUnary<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Add)));
Assert.Equal(9, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Mul)));
Assert.Equal(18, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Sub)));
Assert.Equal(3, response.Result);
response = client.BlockingUnary<Apply, ApplyResponse>(request, GetMethod(nameof(ApplyServices.Div)));
Assert.Equal(2, response.Result);
static MethodInfo GetMethod(string name) => typeof(ApplyServices).GetMethod(name)!;
}
[Fact]
public void CanCallAdocService()
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new AdhocRequest { X = 12, Y = 7 };
var client = http.CreateGrpcService<IAdhocService>(AdhocConfig.ClientFactory);
var response = client.AdhocMethod(request);
Assert.Equal(19, response.Z);
}
[Fact]
public async Task CanCallInterceptedService()
{
GrpcClientFactory.AllowUnencryptedHttp2 = true;
using var http = GrpcChannel.ForAddress($"http://localhost:{GrpcServiceFixture.Port}");
var request = new Apply { X = 6, Y = 3 };
var client = http.CreateGrpcService<IInterceptedService>();
_fixture?.Log("> Add");
var result = await client.Add(new Apply { X = 42, Y = 8 });
_fixture?.Log("< Add");
Assert.Equal(50, result.Result);
}
}
}
#endif