-
Notifications
You must be signed in to change notification settings - Fork 495
Expand file tree
/
Copy pathBaseApiGatewayTest.cs
More file actions
230 lines (201 loc) · 8.83 KB
/
BaseApiGatewayTest.cs
File metadata and controls
230 lines (201 loc) · 8.83 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Lambda.TestTool.Commands;
using Amazon.Lambda.TestTool.Commands.Settings;
using Amazon.Lambda.TestTool.Services;
using Amazon.Lambda.TestTool.Services.IO;
using Moq;
using Spectre.Console.Cli;
using Xunit.Abstractions;
using Amazon.Lambda.TestTool.Models;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using System.Threading;
using Microsoft.Extensions.Hosting;
using Amazon.SecurityToken;
namespace Amazon.Lambda.TestTool.IntegrationTests;
public abstract class BaseApiGatewayTest
{
protected readonly ITestOutputHelper TestOutputHelper;
protected readonly Mock<IToolInteractiveService> MockInteractiveService;
protected readonly Mock<IEnvironmentManager> MockEnvironmentManager;
protected readonly Mock<IRemainingArguments> MockRemainingArgs;
protected CancellationTokenSource CancellationTokenSource;
protected static readonly object TestLock = new();
protected BaseApiGatewayTest(ITestOutputHelper testOutputHelper)
{
TestOutputHelper = testOutputHelper;
MockEnvironmentManager = new Mock<IEnvironmentManager>();
MockInteractiveService = new Mock<IToolInteractiveService>();
MockRemainingArgs = new Mock<IRemainingArguments>();
CancellationTokenSource = new CancellationTokenSource();
}
protected async Task CleanupAsync()
{
if (CancellationTokenSource != null)
{
await CancellationTokenSource.CancelAsync();
CancellationTokenSource.Dispose();
CancellationTokenSource = new CancellationTokenSource();
}
Environment.SetEnvironmentVariable("APIGATEWAY_EMULATOR_ROUTE_CONFIG", null);
}
protected async Task StartTestToolProcessAsync(ApiGatewayEmulatorMode apiGatewayMode, string routeName, int lambdaPort, int apiGatewayPort, CancellationTokenSource cancellationTokenSource, string httpMethod = "POST")
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
Environment.SetEnvironmentVariable("APIGATEWAY_EMULATOR_ROUTE_CONFIG", $@"{{
""LambdaResourceName"": ""{routeName}"",
""Endpoint"": ""http://localhost:{lambdaPort}"",
""HttpMethod"": ""{httpMethod}"",
""Path"": ""/{routeName}""
}}");
var settings = new RunCommandSettings
{
LambdaEmulatorPort = lambdaPort,
NoLaunchWindow = true,
ApiGatewayEmulatorMode = apiGatewayMode,
ApiGatewayEmulatorPort = apiGatewayPort
};
var command = new RunCommand(MockInteractiveService.Object, MockEnvironmentManager.Object);
var context = new CommandContext(new List<string>(), MockRemainingArgs.Object, "run", null);
_ = command.ExecuteAsync(context, settings, cancellationTokenSource);
await Task.Delay(2000, cancellationTokenSource.Token);
}
protected async Task WaitForGatewayHealthCheck(int apiGatewayPort)
{
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(10);
var startTime = DateTime.UtcNow;
var timeout = TimeSpan.FromSeconds(60);
var healthUrl = $"http://localhost:{apiGatewayPort}/__lambda_test_tool_apigateway_health__";
while (DateTime.UtcNow - startTime < timeout)
{
try
{
var response = await client.GetAsync(healthUrl, new CancellationTokenSource(10000).Token);
if (response.IsSuccessStatusCode)
{
TestOutputHelper.WriteLine("API Gateway health check succeeded");
await Task.Delay(2000);
return;
}
}
catch (Exception ex)
{
TestOutputHelper.WriteLine($"Health check attempt failed: {ex.Message}");
await Task.Delay(1000);
}
}
throw new TimeoutException("API Gateway failed to start within timeout period");
}
}
protected async Task<HttpResponseMessage> TestEndpoint(string routeName, int apiGatewayPort, string httpMethod = "POST", string? payload = null)
{
TestOutputHelper.WriteLine($"Testing endpoint: http://localhost:{apiGatewayPort}/{routeName}");
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(120);
var startTime = DateTime.UtcNow;
var timeout = TimeSpan.FromSeconds(180);
Exception? lastException = null;
while (DateTime.UtcNow - startTime < timeout)
{
await Task.Delay(2000);
try
{
return httpMethod.ToUpper() switch
{
"POST" => await client.PostAsync(
$"http://localhost:{apiGatewayPort}/{routeName}",
new StringContent(payload ?? "hello world", Encoding.UTF8, new MediaTypeHeaderValue("text/plain")), new CancellationTokenSource(5000).Token),
"GET" => await client.GetAsync($"http://localhost:{apiGatewayPort}/{routeName}", new CancellationTokenSource(5000).Token),
_ => throw new ArgumentException($"Unsupported HTTP method: {httpMethod}")
};
}
catch (Exception ex)
{
lastException = ex;
TestOutputHelper.WriteLine($"Request attempt failed - Message: {ex.Message}");
TestOutputHelper.WriteLine($"Request attempt failed - Stack Trace: {ex.StackTrace}");
await Task.Delay(1000);
}
}
throw new TimeoutException($"Failed to complete request within timeout period: {lastException?.Message}", lastException);
}
}
protected (int lambdaPort, int apiGatewayPort) GetFreePorts()
{
var lambdaPort = GetFreePort();
int apiGatewayPort;
do
{
apiGatewayPort = GetFreePort();
} while (apiGatewayPort == lambdaPort);
return (lambdaPort, apiGatewayPort);
}
protected int GetFreePort()
{
Console.WriteLine("Looking for free port");
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
var app = builder.Build();
app.MapGet("/", () => "test");
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(5000);
var runTask = app.RunAsync(tokenSource.Token);
var uri = new Uri(app.Urls.First());
using var client = new HttpClient();
string? content = null;
Console.WriteLine($"Testing port: {uri.Port}");
var timeout = DateTime.UtcNow.AddSeconds(30);
while(DateTime.UtcNow < timeout)
{
try
{
content = client.GetStringAsync(uri, tokenSource.Token).GetAwaiter().GetResult();
Console.WriteLine("Port was successful");
break;
}
catch
{
Thread.Sleep(100);
}
}
if (!string.Equals(content, "test"))
{
Console.WriteLine("Port test failed trying again");
var recursivePort = GetFreePort();
tokenSource.Cancel();
return recursivePort;
}
tokenSource.Cancel();
Task.Delay(2000);
return uri.Port;
}
protected async Task StartTestToolProcessWithNullEndpoint(ApiGatewayEmulatorMode apiGatewayMode, string routeName, int lambdaPort, int apiGatewayPort, CancellationTokenSource cancellationTokenSource)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
Environment.SetEnvironmentVariable("APIGATEWAY_EMULATOR_ROUTE_CONFIG", $@"{{
""LambdaResourceName"": ""{routeName}"",
""HttpMethod"": ""POST"",
""Path"": ""/{routeName}""
}}");
var settings = new RunCommandSettings
{
LambdaEmulatorPort = lambdaPort,
NoLaunchWindow = true,
ApiGatewayEmulatorMode = apiGatewayMode,
ApiGatewayEmulatorPort = apiGatewayPort
};
var command = new RunCommand(MockInteractiveService.Object, MockEnvironmentManager.Object);
var context = new CommandContext(new List<string>(), MockRemainingArgs.Object, "run", null);
_ = command.ExecuteAsync(context, settings, cancellationTokenSource);
await Task.Delay(2000, cancellationTokenSource.Token);
}
}