-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathLambdaClientTest.php
365 lines (312 loc) · 13.2 KB
/
LambdaClientTest.php
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
<?php
namespace Runtime\Bref\Tests;
use Bref\Context\Context;
use Bref\Event\Handler;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Server\Server;
use PHPUnit\Framework\TestCase;
use Runtime\Bref\Lambda\LambdaClient;
use Runtime\Bref\Timeout\LambdaTimeoutException;
use Runtime\Bref\Timeout\Timeout;
/**
* Tests the communication between `LambdaClient` and the Lambda Runtime HTTP API.
*
* The API is mocked using a fake HTTP server.
*/
class LambdaClientTest extends TestCase
{
/** @var LambdaClient */
private $lambda;
protected function setUp(): void
{
ob_start();
Server::start();
$this->lambda = new LambdaClient('localhost:8126', 'phpunit');
}
protected function tearDown(): void
{
Server::stop();
ob_end_clean();
}
public function test basic behavior()
{
$this->givenAnEvent(['Hello' => 'world!']);
$output = $this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
return ['hello' => 'world'];
}
});
$this->assertTrue($output);
$this->assertInvocationResult(['hello' => 'world']);
}
public function test handler receives context()
{
$this->givenAnEvent(['Hello' => 'world!']);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
return ['hello' => 'world', 'received-function-arn' => $context->getInvokedFunctionArn()];
}
});
$this->assertInvocationResult([
'hello' => 'world',
'received-function-arn' => 'test-function-name',
]);
}
public function test exceptions in the handler result in an invocation error()
{
$this->givenAnEvent(['Hello' => 'world!']);
$output = $this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
throw new \RuntimeException('This is an exception');
}
});
$this->assertFalse($output);
$this->assertInvocationErrorResult('RuntimeException', 'This is an exception');
$this->assertErrorInLogs('RuntimeException', 'This is an exception');
}
public function test nested exceptions in the handler result in an invocation error()
{
$this->givenAnEvent(['Hello' => 'world!']);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
throw new \RuntimeException('This is an exception', 0, new \RuntimeException('The previous exception.', 0, new \Exception('The original exception.')));
}
});
$this->assertInvocationErrorResult('RuntimeException', 'This is an exception');
$this->assertErrorInLogs('RuntimeException', 'This is an exception');
$this->assertPreviousErrorsInLogs([
['errorClass' => 'RuntimeException', 'errorMessage' => 'The previous exception.'],
['errorClass' => 'Exception', 'errorMessage' => 'The original exception.'],
]);
}
public function test an error is thrown if the runtime API returns a wrong response()
{
$this->expectExceptionMessage('Failed to fetch next Lambda invocation: The requested URL returned error: 404');
Server::enqueue([
new Response( // lambda event
404, // 404 instead of 200
[
'lambda-runtime-aws-request-id' => 1,
],
'{ "Hello": "world!"}'
),
]);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
}
});
}
public function test an error is thrown if the invocation id is missing()
{
$this->expectExceptionMessage('Failed to determine the Lambda invocation ID');
Server::enqueue([
new Response( // lambda event
200,
[], // Missing `lambda-runtime-aws-request-id`
'{ "Hello": "world!"}'
),
]);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
}
});
}
public function test an error is thrown if the invocation body is empty()
{
$this->expectExceptionMessage('Empty Lambda runtime API response');
Server::enqueue([
new Response( // lambda event
200,
[
'lambda-runtime-aws-request-id' => 1,
]
),
]);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
}
});
}
public function test a wrong response from the runtime API turns the invocation into an error()
{
Server::enqueue([
new Response( // lambda event
200,
[
'lambda-runtime-aws-request-id' => 1,
],
'{ "Hello": "world!"}'
),
new Response(400), // The Lambda API returns a 400 instead of a 200
new Response(200),
]);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
return $event;
}
});
$requests = Server::received();
$this->assertCount(3, $requests);
[$eventRequest, $eventFailureResponse, $eventFailureLog] = $requests;
$this->assertSame('GET', $eventRequest->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/next', $eventRequest->getUri()->__toString());
$this->assertSame('POST', $eventFailureResponse->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/1/response', $eventFailureResponse->getUri()->__toString());
$this->assertSame('POST', $eventFailureLog->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/1/error', $eventFailureLog->getUri()->__toString());
// Check the lambda result contains the error message
$error = json_decode((string) $eventFailureLog->getBody(), true);
$this->assertStringContainsString('Error while calling the Lambda runtime API: The requested URL returned error: 400', $error['errorMessage']);
$this->assertErrorInLogs('Exception', 'Error while calling the Lambda runtime API: The requested URL returned error: 400');
}
public function test function results that cannot be encoded are reported as invocation errors()
{
$this->givenAnEvent(['hello' => 'world!']);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
return "\xB1\x31";
}
});
$message = <<<ERROR
The Lambda response cannot be encoded to JSON.
This error usually happens when you try to return binary content. If you are writing an HTTP application and you want to return a binary HTTP response (like an image, a PDF, etc.), please read this guide: https://bref.sh/docs/runtimes/http.html#binary-responses
Here is the original JSON error: 'Malformed UTF-8 characters, possibly incorrectly encoded'
ERROR;
$this->assertInvocationErrorResult('Exception', $message);
$this->assertErrorInLogs('Exception', $message);
}
public function test generic event handler()
{
$handler = new class() implements Handler {
/**
* @param mixed $event
*
* @return mixed
*/
public function handle($event, Context $context)
{
return $event;
}
};
$this->givenAnEvent(['foo' => 'bar']);
$this->lambda->processNextEvent($handler);
$this->assertInvocationResult(['foo' => 'bar']);
}
public function testLambdaTimeoutsCanBeAnticipated()
{
$this->givenAnEvent([]);
$start = microtime(true);
$this->lambda->processNextEvent(new class() implements Handler {
public function handle($event, Context $context)
{
// This 10s sleep should be interrupted
sleep(10);
}
});
$elapsedTime = microtime(true) - $start;
// The Lambda timeout was 2 seconds, we expect the Bref timeout to trigger 1 second before that: 1 second
$this->assertEqualsWithDelta(1, $elapsedTime, 0.2);
Timeout::reset();
$this->assertInvocationErrorResult(LambdaTimeoutException::class, 'Maximum AWS Lambda execution time reached');
$this->assertErrorInLogs(LambdaTimeoutException::class, 'Maximum AWS Lambda execution time reached');
}
/**
* @param mixed $event
*/
private function givenAnEvent($event): void
{
Server::enqueue([
new Response( // lambda event
200,
[
'lambda-runtime-aws-request-id' => '1',
'lambda-runtime-invoked-function-arn' => 'test-function-name',
// now + 2 seconds
'lambda-runtime-deadline-ms' => intval((microtime(true) + 2) * 1000),
],
json_encode($event)
),
new Response(200), // lambda response accepted
]);
}
/**
* @param mixed $result
*/
private function assertInvocationResult($result)
{
$requests = Server::received();
$this->assertCount(2, $requests);
[$eventRequest, $eventResponse] = $requests;
$this->assertSame('GET', $eventRequest->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/next', $eventRequest->getUri()->__toString());
$this->assertSame('POST', $eventResponse->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/1/response', $eventResponse->getUri()->__toString());
$this->assertEquals($result, json_decode($eventResponse->getBody()->__toString(), true));
}
private function assertInvocationErrorResult(string $errorClass, string $errorMessage)
{
$requests = Server::received();
$this->assertCount(2, $requests);
[$eventRequest, $eventResponse] = $requests;
$this->assertSame('GET', $eventRequest->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/next', $eventRequest->getUri()->__toString());
$this->assertSame('POST', $eventResponse->getMethod());
$this->assertSame('http://localhost:8126/2018-06-01/runtime/invocation/1/error', $eventResponse->getUri()->__toString());
// Check the content of the result of the lambda
$invocationResult = json_decode($eventResponse->getBody()->__toString(), true);
$this->assertSame([
'errorType',
'errorMessage',
'stackTrace',
], array_keys($invocationResult));
$this->assertEquals($errorClass, $invocationResult['errorType']);
$this->assertEquals($errorMessage, $invocationResult['errorMessage']);
$this->assertIsArray($invocationResult['stackTrace']);
}
private function assertErrorInLogs(string $errorClass, string $errorMessage): void
{
// Decode the logs from stdout
$stdout = $this->getActualOutput();
[$requestId, $message, $json] = explode("\t", $stdout);
$this->assertSame('Invoke Error', $message);
// Check the request ID matches a UUID
$this->assertNotEmpty($requestId);
$invocationResult = json_decode($json, true);
unset($invocationResult['previous']);
$this->assertSame([
'errorType',
'errorMessage',
'stack',
], array_keys($invocationResult));
$this->assertEquals($errorClass, $invocationResult['errorType']);
$this->assertStringContainsString($errorMessage, $invocationResult['errorMessage']);
$this->assertIsArray($invocationResult['stack']);
}
private function assertPreviousErrorsInLogs(array $previousErrors)
{
// Decode the logs from stdout
$stdout = $this->getActualOutput();
[, , $json] = explode("\t", $stdout);
['previous' => $previous] = json_decode($json, true);
$this->assertCount(count($previousErrors), $previous);
foreach ($previous as $index => $error) {
$this->assertSame([
'errorType',
'errorMessage',
'stack',
], array_keys($error));
$this->assertEquals($previousErrors[$index]['errorClass'], $error['errorType']);
$this->assertEquals($previousErrors[$index]['errorMessage'], $error['errorMessage']);
$this->assertIsArray($error['stack']);
}
}
}