-
Notifications
You must be signed in to change notification settings - Fork 504
Expand file tree
/
Copy pathTestApiGatewayHttpApiV2Calls.cs
More file actions
378 lines (304 loc) · 15.5 KB
/
Copy pathTestApiGatewayHttpApiV2Calls.cs
File metadata and controls
378 lines (304 loc) · 15.5 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
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
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
using Amazon.Lambda.TestUtilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TestWebApp;
using TestWebApp.Controllers;
using Xunit;
namespace Amazon.Lambda.AspNetCoreServer.Test
{
public class TestApiGatewayHttpApiV2Calls
{
[Fact]
public async Task TestValuesGetAllFromBetaStage()
{
var context = new TestLambdaContext();
var response = await InvokeAPIGatewayRequest(context, "values-get-all-httpapi-v2-with-stage.json");
Assert.Equal(200, response.StatusCode);
Assert.Equal("[\"value1\",\"value2\"]", response.Body);
Assert.True(response.Headers.ContainsKey("Content-Type"));
Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]);
Assert.Contains("OnStarting Called", ((TestLambdaLogger)context.Logger).Buffer.ToString());
}
[Fact]
public async Task TestGetBinaryContent()
{
var response = await InvokeAPIGatewayRequest("values-get-binary-httpapi-v2-request.json");
Assert.Equal((int)HttpStatusCode.OK, response.StatusCode);
string contentType;
Assert.True(response.Headers.TryGetValue("Content-Type", out contentType),
"Content-Type response header exists");
Assert.Equal("application/octet-stream", contentType);
Assert.NotNull(response.Body);
Assert.True(response.Body.Length > 0,
"Body content is not empty");
Assert.True(response.IsBase64Encoded, "Response IsBase64Encoded");
// Compute a 256-byte array, with values 0-255
var binExpected = new byte[byte.MaxValue].Select((val, index) => (byte)index).ToArray();
var binActual = Convert.FromBase64String(response.Body);
Assert.Equal(binExpected, binActual);
}
[Fact]
public async Task TestEncodePlusInResourcePath()
{
var response = await InvokeAPIGatewayRequest("encode-plus-in-resource-path-httpapi-v2.json");
Assert.Equal(200, response.StatusCode);
var root = JObject.Parse(response.Body);
Assert.Equal("/foo+bar", root["Path"]?.ToString());
}
[Fact]
public async Task TestGetQueryStringValueMV()
{
var response = await InvokeAPIGatewayRequest("values-get-querystring-httpapi-v2-mv-request.json");
Assert.Equal("value1,value2", response.Body);
Assert.True(response.Headers.ContainsKey("Content-Type"));
Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]);
}
[Fact]
public async Task TestGetEncodingQueryStringGateway()
{
var response = await InvokeAPIGatewayRequest("values-get-querystring-httpapi-v2-encoding-request.json");
var results = JsonConvert.DeserializeObject<TestWebApp.Controllers.RawQueryStringController.Results>(response.Body);
Assert.Equal("http://www.google.com", results.Url);
Assert.Equal(DateTimeOffset.Parse("2019-03-12T16:06:06.549817+00:00"), results.TestDateTimeOffset);
Assert.True(response.Headers.ContainsKey("Content-Type"));
Assert.Equal("application/json; charset=utf-8", response.Headers["Content-Type"]);
}
[Fact]
public async Task TestPutWithBody()
{
var response = await InvokeAPIGatewayRequest("values-put-withbody-httpapi-v2-request.json");
Assert.Equal(200, response.StatusCode);
Assert.Equal("Agent, Smith", response.Body);
Assert.True(response.Headers.ContainsKey("Content-Type"));
Assert.Equal("text/plain; charset=utf-8", response.Headers["Content-Type"]);
}
[Fact]
public async Task TestDefaultResponseErrorCode()
{
var response = await InvokeAPIGatewayRequest("values-get-error-httpapi-v2-request.json");
Assert.Equal(500, response.StatusCode);
Assert.Equal(string.Empty, response.Body);
}
[Theory]
[InlineData("values-get-aggregateerror-httpapi-v2-request.json", "AggregateException", true)]
[InlineData("values-get-typeloaderror-httpapi-v2-request.json", "ReflectionTypeLoadException", true)]
[InlineData("values-get-aggregateerror-httpapi-v2-request.json", "AggregateException", false)]
[InlineData("values-get-typeloaderror-httpapi-v2-request.json", "ReflectionTypeLoadException", false)]
public async Task TestEnhancedExceptions(string requestFileName, string expectedExceptionType, bool configureApiToReturnExceptionDetail)
{
var response = await InvokeAPIGatewayRequest(requestFileName, configureApiToReturnExceptionDetail);
Assert.Equal(500, response.StatusCode);
Assert.Equal(string.Empty, response.Body);
if (configureApiToReturnExceptionDetail)
{
Assert.True(response.Headers.ContainsKey("ErrorType"));
Assert.Equal(expectedExceptionType, response.Headers["ErrorType"]);
}
else
{
Assert.False(response.Headers.ContainsKey("ErrorType"));
}
}
[Fact]
public async Task TestGettingSwaggerDefinition()
{
var response = await InvokeAPIGatewayRequest("swagger-get-httpapi-v2-request.json");
Assert.Equal(200, response.StatusCode);
Assert.True(response.Body.Length > 0);
Assert.Equal("application/json", response.Headers["Content-Type"]);
}
[Fact]
public async Task TestEncodeSpaceInResourcePath()
{
var response = await InvokeAPIGatewayRequest("encode-space-in-resource-path-httpapi-v2.json");
Assert.Equal(200, response.StatusCode);
Assert.Equal("value=tmh/file name.xml", response.Body);
}
[Fact]
public async Task TestEncodeSlashInResourcePath()
{
var requestStr = GetRequestContent("encode-slash-in-resource-path-httpapi-v2.json");
var response = await InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr);
Assert.Equal(200, response.StatusCode);
Assert.Equal("{\"only\":\"a%2Fb\"}", response.Body);
response = await InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), requestStr.Replace("a%2Fb", "a/b"));
Assert.Equal(200, response.StatusCode);
Assert.Equal("{\"first\":\"a\",\"second\":\"b\"}", response.Body);
}
[Fact]
public async Task TestTrailingSlashInPath()
{
var response = await InvokeAPIGatewayRequest("trailing-slash-in-path-httpapi-v2.json");
Assert.Equal(200, response.StatusCode);
var root = JObject.Parse(response.Body);
Assert.Equal("/beta", root["PathBase"]?.ToString());
Assert.Equal("/foo/", root["Path"]?.ToString());
}
[Theory]
[InlineData("rawtarget-escaped-percent-in-path-httpapi-v2.json", "/foo%25bar")]
[InlineData("rawtarget-escaped-percent-slash-in-path-httpapi-v2.json", "/foo%25%2Fbar")]
[InlineData("rawtarget-escaped-reserved-in-query-httpapi-v2.json", "/foo/bar?foo=b%40r")]
[InlineData("rawtarget-escaped-slash-in-path-httpapi-v2.json", "/foo%2Fbar")]
public async Task TestRawTarget(string requestFileName, string expectedRawTarget)
{
var response = await InvokeAPIGatewayRequest(requestFileName);
Assert.Equal(200, response.StatusCode);
var root = JObject.Parse(response.Body);
Assert.Equal(expectedRawTarget, root["RawTarget"]?.ToString());
}
[Fact]
public async Task TestAuthTestAccess()
{
var response = await InvokeAPIGatewayRequest("authtest-access-request-httpapi-v2.json");
Assert.Equal(200, response.StatusCode);
Assert.Equal("You Have Access", response.Body);
}
[Fact]
public async Task TestAuthTestNoAccess()
{
var response = await InvokeAPIGatewayRequest("authtest-noaccess-request-httpapi-v2.json");
Assert.NotEqual(200, response.StatusCode);
}
[Fact]
public async Task TestAuthMTls()
{
var response = await InvokeAPIGatewayRequest("mtls-request-httpapi-v2.json");
Assert.Equal(200, response.StatusCode);
Assert.Equal("O=Internet Widgits Pty Ltd, S=Some-State, C=AU", response.Body);
}
[Fact]
public async Task TestReturningCookie()
{
var response = await InvokeAPIGatewayRequest("cookies-get-returned-httpapi-v2-request.json");
Assert.Collection(response.Cookies,
actual => Assert.StartsWith("TestCookie=TestValue", actual));
}
[Fact]
public async Task TestReturningMultipleCookies()
{
var response = await InvokeAPIGatewayRequest("cookies-get-multiple-returned-httpapi-v2-request.json");
Assert.Collection(response.Cookies.OrderBy(s => s),
actual => Assert.StartsWith("TestCookie1=TestValue1", actual),
actual => Assert.StartsWith("TestCookie2=TestValue2", actual));
}
[Fact]
public async Task TestSingleCookie()
{
var response = await InvokeAPIGatewayRequest("cookies-get-single-httpapi-v2-request.json");
Assert.Equal("TestValue", response.Body);
}
[Fact]
public async Task TestMultipleCookie()
{
var response = await InvokeAPIGatewayRequest("cookies-get-multiple-httpapi-v2-request.json");
Assert.Equal("TestValue3", response.Body);
}
[Fact]
public async Task TestTraceIdSetFromLambdaContext()
{
try
{
Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "MyTraceId-1");
var response = await InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json");
Assert.Equal("MyTraceId-1", response.Body);
Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", "MyTraceId-2");
response = await InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json");
Assert.Equal("MyTraceId-2", response.Body);
Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", null);
response = await InvokeAPIGatewayRequest("traceid-get-httpapi-v2-request.json");
Assert.True(!string.IsNullOrEmpty(response.Body) && !string.Equals(response.Body, "MyTraceId-2"));
}
finally
{
Environment.SetEnvironmentVariable("_X_AMZN_TRACE_ID", null);
}
}
/// <summary>
/// Verifies that <see cref="HttpV2LambdaFunction.GetBeforeSnapshotRequests"/> is invoked during startup.
/// </summary>
/// <returns></returns>
[Fact]
public async Task TestSnapStartInitialization()
{
using var e1 = new EnvironmentVariableHelper("AWS_LAMBDA_FUNCTION_NAME", nameof(TestSnapStartInitialization));
using var e2 = new EnvironmentVariableHelper("AWS_LAMBDA_INITIALIZATION_TYPE", "snap-start");
var cts = new CancellationTokenSource();
using var bootstrap = LambdaBootstrapBuilder.Create<APIGatewayHttpApiV2ProxyRequest>(
new TestWebApp.HttpV2LambdaFunction().FunctionHandlerAsync,
new DefaultLambdaJsonSerializer())
.ConfigureOptions(opt => opt.RuntimeApiEndpoint = "localhost:123")
.Build();
// Keep the task so we can tear the bootstrap down before the test returns. Previously this
// was fire-and-forget (_ = bootstrap.RunAsync(...)); the polling loop (against a dead
// endpoint) then kept running after the assert, and under parallel CI load the leaked loop
// hung the whole test process until the credentials expired ~2h later.
var bootstrapTask = bootstrap.RunAsync(cts.Token);
// allow some time for Bootstrap to initialize in background
await Task.Delay(100);
// Assert what the test is actually about (the SnapStart before-snapshot hook ran) before
// tearing down, so a teardown exception can't mask the real result.
Assert.True(SnapStartController.Invoked);
await cts.CancelAsync();
// Wait for the polling loop to actually stop so no background work outlives the test. The
// bootstrap runs against a dead endpoint (localhost:123), so its loop either observes the
// cancellation (OperationCanceledException) or throws the connection failure it was
// retrying (HttpRequestException); both are expected teardown noise, not test failures.
try
{
await bootstrapTask;
}
catch (OperationCanceledException)
{
}
catch (HttpRequestException)
{
}
}
private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequest(string fileName, bool configureApiToReturnExceptionDetail = false)
{
return await InvokeAPIGatewayRequestWithContent(new TestLambdaContext(), GetRequestContent(fileName), configureApiToReturnExceptionDetail);
}
private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequest(TestLambdaContext context, string fileName, bool configureApiToReturnExceptionDetail = false)
{
return await InvokeAPIGatewayRequestWithContent(context, GetRequestContent(fileName), configureApiToReturnExceptionDetail);
}
private async Task<APIGatewayHttpApiV2ProxyResponse> InvokeAPIGatewayRequestWithContent(TestLambdaContext context, string requestContent, bool configureApiToReturnExceptionDetail = false)
{
var lambdaFunction = new TestWebApp.HttpV2LambdaFunction();
if (configureApiToReturnExceptionDetail)
lambdaFunction.IncludeUnhandledExceptionDetailInResponse = true;
var requestStream = new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(requestContent));
var request = new Amazon.Lambda.Serialization.SystemTextJson.LambdaJsonSerializer().Deserialize<APIGatewayHttpApiV2ProxyRequest>(requestStream);
return await lambdaFunction.FunctionHandlerAsync(request, context);
}
private string GetRequestContent(string fileName)
{
var filePath = Path.Combine(Path.GetDirectoryName(GetType().GetTypeInfo().Assembly.Location), fileName);
var requestStr = File.ReadAllText(filePath);
return requestStr;
}
}
public class EnvironmentVariableHelper : IDisposable
{
private readonly string _name;
private readonly string _oldValue;
public EnvironmentVariableHelper(string name, string value)
{
_name = name;
_oldValue = Environment.GetEnvironmentVariable(name);
Environment.SetEnvironmentVariable(name, value);
}
public void Dispose() => Environment.SetEnvironmentVariable(_name, _oldValue);
}
}