-
Notifications
You must be signed in to change notification settings - Fork 501
Expand file tree
/
Copy pathLambdaResponseStreamingCoreTests.cs
More file actions
556 lines (453 loc) · 21.4 KB
/
Copy pathLambdaResponseStreamingCoreTests.cs
File metadata and controls
556 lines (453 loc) · 21.4 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#pragma warning disable CA2252
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Lambda.Core.ResponseStreaming;
using Amazon.Lambda.RuntimeSupport.Client.ResponseStreaming;
using Xunit;
namespace Amazon.Lambda.RuntimeSupport.UnitTests
{
// ─────────────────────────────────────────────────────────────────────────────
// HttpResponseStreamPrelude.ToByteArray() tests
// ─────────────────────────────────────────────────────────────────────────────
public class HttpResponseStreamPreludeTests
{
private static JsonDocument ParsePrelude(HttpResponseStreamPrelude prelude)
=> JsonDocument.Parse(prelude.ToByteArray());
[Fact]
public void ToByteArray_EmptyPrelude_ProducesEmptyJsonObject()
{
var prelude = new HttpResponseStreamPrelude();
var doc = ParsePrelude(prelude);
Assert.Equal(JsonValueKind.Object, doc.RootElement.ValueKind);
// No properties should be present
Assert.False(doc.RootElement.TryGetProperty("statusCode", out _));
Assert.False(doc.RootElement.TryGetProperty("headers", out _));
Assert.False(doc.RootElement.TryGetProperty("multiValueHeaders", out _));
Assert.False(doc.RootElement.TryGetProperty("cookies", out _));
}
[Fact]
public void ToByteArray_WithStatusCode_IncludesStatusCode()
{
var prelude = new HttpResponseStreamPrelude { StatusCode = HttpStatusCode.OK };
var doc = ParsePrelude(prelude);
Assert.True(doc.RootElement.TryGetProperty("statusCode", out var sc));
Assert.Equal(200, sc.GetInt32());
}
[Fact]
public void ToByteArray_WithHeaders_IncludesHeaders()
{
var prelude = new HttpResponseStreamPrelude
{
Headers = new Dictionary<string, string>
{
["Content-Type"] = "application/json",
["X-Custom"] = "value"
}
};
var doc = ParsePrelude(prelude);
Assert.True(doc.RootElement.TryGetProperty("headers", out var headers));
Assert.Equal("application/json", headers.GetProperty("Content-Type").GetString());
Assert.Equal("value", headers.GetProperty("X-Custom").GetString());
}
[Fact]
public void ToByteArray_WithMultiValueHeaders_IncludesMultiValueHeaders()
{
var prelude = new HttpResponseStreamPrelude
{
MultiValueHeaders = new Dictionary<string, IList<string>>
{
["Set-Cookie"] = new List<string> { "a=1", "b=2" }
}
};
var doc = ParsePrelude(prelude);
Assert.True(doc.RootElement.TryGetProperty("multiValueHeaders", out var mvh));
var cookies = mvh.GetProperty("Set-Cookie");
Assert.Equal(JsonValueKind.Array, cookies.ValueKind);
Assert.Equal(2, cookies.GetArrayLength());
}
[Fact]
public void ToByteArray_WithCookies_IncludesCookies()
{
var prelude = new HttpResponseStreamPrelude
{
Cookies = new List<string> { "session=abc", "pref=dark" }
};
var doc = ParsePrelude(prelude);
Assert.True(doc.RootElement.TryGetProperty("cookies", out var cookies));
Assert.Equal(JsonValueKind.Array, cookies.ValueKind);
Assert.Equal(2, cookies.GetArrayLength());
Assert.Equal("session=abc", cookies[0].GetString());
}
[Fact]
public void ToByteArray_AllFieldsPopulated_ProducesCorrectJson()
{
var prelude = new HttpResponseStreamPrelude
{
StatusCode = HttpStatusCode.Created,
Headers = new Dictionary<string, string> { ["X-Req"] = "1" },
MultiValueHeaders = new Dictionary<string, IList<string>> { ["X-Multi"] = new List<string> { "a", "b" } },
Cookies = new List<string> { "c=1" }
};
var doc = ParsePrelude(prelude);
Assert.Equal(201, doc.RootElement.GetProperty("statusCode").GetInt32());
Assert.Equal("1", doc.RootElement.GetProperty("headers").GetProperty("X-Req").GetString());
Assert.Equal(2, doc.RootElement.GetProperty("multiValueHeaders").GetProperty("X-Multi").GetArrayLength());
Assert.Equal("c=1", doc.RootElement.GetProperty("cookies")[0].GetString());
}
[Fact]
public void ToByteArray_EmptyCollections_OmitsThoseFields()
{
var prelude = new HttpResponseStreamPrelude
{
StatusCode = HttpStatusCode.OK,
Headers = new Dictionary<string, string>(), // empty — should be omitted
MultiValueHeaders = new Dictionary<string, IList<string>>(), // empty
Cookies = new List<string>() // empty
};
var doc = ParsePrelude(prelude);
Assert.True(doc.RootElement.TryGetProperty("statusCode", out _));
Assert.False(doc.RootElement.TryGetProperty("headers", out _));
Assert.False(doc.RootElement.TryGetProperty("multiValueHeaders", out _));
Assert.False(doc.RootElement.TryGetProperty("cookies", out _));
}
[Fact]
public void ToByteArray_ProducesValidUtf8()
{
var prelude = new HttpResponseStreamPrelude
{
StatusCode = HttpStatusCode.OK,
Headers = new Dictionary<string, string> { ["Content-Type"] = "text/plain; charset=utf-8" }
};
var bytes = prelude.ToByteArray();
// Should not throw
var text = Encoding.UTF8.GetString(bytes);
Assert.NotEmpty(text);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// LambdaResponseStream (Stream subclass) tests
// ─────────────────────────────────────────────────────────────────────────────
public class LambdaResponseStreamTests
{
/// <summary>
/// Creates a LambdaResponseStream backed by a real ResponseStream wired to a MemoryStream.
/// </summary>
private static async Task<(LambdaResponseStream lambdaStream, MemoryStream httpOutput)> CreateWiredLambdaStream()
{
var inner = new ResponseStream(Array.Empty<byte>());
var output = new MemoryStream();
await inner.SetHttpOutputStreamAsync(output);
var implStream = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var lambdaStream = new LambdaResponseStream(implStream);
return (lambdaStream, output);
}
[Fact]
public void LambdaResponseStream_IsStreamSubclass()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.IsAssignableFrom<Stream>(stream);
}
[Fact]
public void CanWrite_IsTrue()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.True(stream.CanWrite);
}
[Fact]
public void CanRead_IsFalse()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.False(stream.CanRead);
}
[Fact]
public void CanSeek_IsFalse()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.False(stream.CanSeek);
}
[Fact]
public void Read_ThrowsNotImplementedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.Throws<NotImplementedException>(() => stream.Read(new byte[1], 0, 1));
}
[Fact]
public void ReadAsync_ThrowsNotImplementedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
// ReadAsync throws synchronously (not async) — capture the thrown task
var ex = Assert.Throws<NotImplementedException>(
() => { var _ = stream.ReadAsync(new byte[1], 0, 1, CancellationToken.None); });
Assert.NotNull(ex);
}
[Fact]
public void Seek_ThrowsNotImplementedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.Throws<NotImplementedException>(() => stream.Seek(0, SeekOrigin.Begin));
}
[Fact]
public void Position_Get_ThrowsNotSupportedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.Throws<NotSupportedException>(() => _ = stream.Position);
}
[Fact]
public void Position_Set_ThrowsNotSupportedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.Throws<NotSupportedException>(() => stream.Position = 0);
}
[Fact]
public void SetLength_ThrowsNotSupportedException()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var stream = new LambdaResponseStream(impl);
Assert.Throws<NotSupportedException>(() => stream.SetLength(100));
}
[Fact]
public async Task WriteAsync_WritesRawBytesToHttpStream()
{
var (stream, output) = await CreateWiredLambdaStream();
var data = Encoding.UTF8.GetBytes("hello streaming");
await stream.WriteAsync(data, 0, data.Length);
Assert.Equal(data, output.ToArray());
}
[Fact]
public async Task Write_SyncOverload_WritesRawBytes()
{
var (stream, output) = await CreateWiredLambdaStream();
var data = new byte[] { 1, 2, 3 };
stream.Write(data, 0, data.Length);
Assert.Equal(data, output.ToArray());
}
[Fact]
public async Task Length_ReflectsBytesWritten()
{
var (stream, _) = await CreateWiredLambdaStream();
var data = new byte[42];
await stream.WriteAsync(data, 0, data.Length);
Assert.Equal(42, stream.Length);
Assert.Equal(42, stream.BytesWritten);
}
[Fact]
public async Task Flush_IsNoOp()
{
var (stream, _) = await CreateWiredLambdaStream();
// Should not throw
stream.Flush();
}
[Fact]
public async Task WriteAsync_ByteArrayOverload_WritesFullArray()
{
var (stream, output) = await CreateWiredLambdaStream();
var data = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
await stream.WriteAsync(data);
Assert.Equal(data, output.ToArray());
}
}
// ─────────────────────────────────────────────────────────────────────────────
// ImplLambdaResponseStream (bridge class) tests
// ─────────────────────────────────────────────────────────────────────────────
public class ImplLambdaResponseStreamTests
{
[Fact]
public async Task WriteAsync_DelegatesToInnerResponseStream()
{
var inner = new ResponseStream(Array.Empty<byte>());
var output = new MemoryStream();
await inner.SetHttpOutputStreamAsync(output);
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
var data = new byte[] { 1, 2, 3 };
await impl.WriteAsync(data, 0, data.Length);
Assert.Equal(data, output.ToArray());
}
[Fact]
public async Task BytesWritten_ReflectsInnerStreamBytesWritten()
{
var inner = new ResponseStream(Array.Empty<byte>());
var output = new MemoryStream();
await inner.SetHttpOutputStreamAsync(output);
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
await impl.WriteAsync(new byte[7], 0, 7);
Assert.Equal(7, impl.BytesWritten);
}
[Fact]
public void HasError_InitiallyFalse()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
Assert.False(impl.HasError);
}
[Fact]
public void HasError_TrueAfterReportError()
{
var inner = new ResponseStream(Array.Empty<byte>());
inner.ReportError(new Exception("test"));
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
Assert.True(impl.HasError);
}
[Fact]
public void Dispose_DisposesInnerStream()
{
var inner = new ResponseStream(Array.Empty<byte>());
var impl = new ResponseStreamLambdaCoreInitializerIsolated.ImplLambdaResponseStream(inner);
// Should not throw
impl.Dispose();
}
}
// ─────────────────────────────────────────────────────────────────────────────
// LambdaResponseStreamFactory tests
// ─────────────────────────────────────────────────────────────────────────────
[Collection("RuntimeSupportStateCheck")]
public class LambdaResponseStreamFactoryTests : IDisposable
{
public LambdaResponseStreamFactoryTests()
{
// Wire up the factory via the initializer (same as production bootstrap does)
ResponseStreamLambdaCoreInitializerIsolated.InitializeCore();
}
public void Dispose()
{
ResponseStreamFactory.CleanupInvocation(isMultiConcurrency: false);
}
private void InitializeInvocation(string requestId = "test-req")
{
var envVars = new TestEnvironmentVariables();
var client = new NoOpStreamingRuntimeApiClient(envVars);
ResponseStreamFactory.InitializeInvocation(requestId, false, client, CancellationToken.None);
}
/// <summary>
/// Minimal RuntimeApiClient that accepts StartStreamingResponseAsync without real HTTP.
/// </summary>
private class NoOpStreamingRuntimeApiClient : RuntimeApiClient
{
public NoOpStreamingRuntimeApiClient(IEnvironmentVariables envVars)
: base(envVars, new TestHelpers.NoOpInternalRuntimeApiClient()) { }
internal override async Task<IDisposable> StartStreamingResponseAsync(
string awsRequestId, ResponseStream responseStream, CancellationToken cancellationToken = default)
{
// Provide the HTTP output stream so writes don't block
await responseStream.SetHttpOutputStreamAsync(new MemoryStream(), cancellationToken);
await responseStream.WaitForCompletionAsync(cancellationToken);
return new NoOpDisposable();
}
}
[Fact]
public void CreateStream_ReturnsLambdaResponseStream()
{
InitializeInvocation();
var stream = LambdaResponseStreamFactory.CreateStream();
Assert.NotNull(stream);
Assert.IsType<LambdaResponseStream>(stream);
}
[Fact]
public void CreateStream_ReturnsStreamSubclass()
{
InitializeInvocation();
var stream = LambdaResponseStreamFactory.CreateStream();
Assert.IsAssignableFrom<Stream>(stream);
}
[Fact]
public void CreateStream_ReturnedStream_IsWritable()
{
InitializeInvocation();
var stream = LambdaResponseStreamFactory.CreateStream();
Assert.True(stream.CanWrite);
}
[Fact]
public void CreateStream_ReturnedStream_IsNotSeekable()
{
InitializeInvocation();
var stream = LambdaResponseStreamFactory.CreateStream();
Assert.False(stream.CanSeek);
}
[Fact]
public void CreateStream_ReturnedStream_IsNotReadable()
{
InitializeInvocation();
var stream = LambdaResponseStreamFactory.CreateStream();
Assert.False(stream.CanRead);
}
[Fact]
public void CreateHttpStream_WithPrelude_ReturnsLambdaResponseStream()
{
InitializeInvocation();
var prelude = new HttpResponseStreamPrelude { StatusCode = HttpStatusCode.OK };
var stream = LambdaResponseStreamFactory.CreateHttpStream(prelude);
Assert.NotNull(stream);
Assert.IsType<LambdaResponseStream>(stream);
}
[Fact]
public void CreateHttpStream_PassesSerializedPreludeToFactory()
{
// Capture the prelude bytes passed to the inner factory
byte[] capturedPrelude = null;
LambdaResponseStreamFactory.SetLambdaResponseStream(prelude =>
{
capturedPrelude = prelude;
// Return a minimal stub that satisfies the interface
return new StubLambdaResponseStream();
});
var httpPrelude = new HttpResponseStreamPrelude
{
StatusCode = HttpStatusCode.Created,
Headers = new Dictionary<string, string> { ["X-Test"] = "1" }
};
LambdaResponseStreamFactory.CreateHttpStream(httpPrelude);
Assert.NotNull(capturedPrelude);
Assert.True(capturedPrelude.Length > 0);
// Verify the bytes are valid JSON containing the status code
var doc = JsonDocument.Parse(capturedPrelude);
Assert.Equal(201, doc.RootElement.GetProperty("statusCode").GetInt32());
}
[Fact]
public void CreateStream_PassesEmptyPreludeToFactory()
{
byte[] capturedPrelude = null;
LambdaResponseStreamFactory.SetLambdaResponseStream(prelude =>
{
capturedPrelude = prelude;
return new StubLambdaResponseStream();
});
LambdaResponseStreamFactory.CreateStream();
Assert.NotNull(capturedPrelude);
Assert.Empty(capturedPrelude);
}
private class StubLambdaResponseStream : ILambdaResponseStream
{
public long BytesWritten => 0;
public bool HasError => false;
public void Dispose() { }
public Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
=> Task.CompletedTask;
}
}
}