-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathRecordingHandlerTests.cs
More file actions
1146 lines (947 loc) · 53 KB
/
RecordingHandlerTests.cs
File metadata and controls
1146 lines (947 loc) · 53 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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Azure.Sdk.Tools.TestProxy.Common;
using Azure.Sdk.Tools.TestProxy.Matchers;
using Azure.Sdk.Tools.TestProxy.Sanitizers;
using Azure.Sdk.Tools.TestProxy.Transforms;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Primitives;
using Xunit;
using Azure.Core;
using System.Runtime.InteropServices;
using Azure.Sdk.Tools.TestProxy.Common.Exceptions;
using Azure.Sdk.Tools.TestProxy.Store;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
namespace Azure.Sdk.Tools.TestProxy.Tests
{
public class RecordingHandlerTests
{
#region helpers and private test fields
private HttpContext GenerateHttpRequestContext(string[] headerValueStrings)
{
HttpContext context = new DefaultHttpContext();
foreach (var hTuple in GenerateHeaderValuesTuples(headerValueStrings))
{
context.Request.Headers.TryAdd(hTuple.Item1, hTuple.Item2);
}
context.Request.Headers.TryAdd("x-recording-upstream-base-uri", new string[] { "https://hello-world" });
context.Request.Method = "POST";
return context;
}
private IEnumerable<Tuple<string, StringValues>> GenerateHeaderValuesTuples(string[] headerValueStrings)
{
var returnedTuples = new List<Tuple<string, StringValues>>();
foreach (var headString in headerValueStrings)
{
var splitLocation = headString.IndexOf(':');
var headerKey = headString.Substring(0, splitLocation);
var headerValue = headString.Substring(splitLocation).Split(";").ToArray();
returnedTuples.Add(new Tuple<string, StringValues>(headerKey, headerValue));
}
return returnedTuples;
}
private NullLoggerFactory _nullLogger = new NullLoggerFactory();
public static JsonSerializerOptions SerializerOptions = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
[Flags]
enum CheckSkips
{
None = 0,
IncludeTransforms = 1,
IncludeSanitizers = 2,
IncludeMatcher = 4,
Default = IncludeTransforms | IncludeSanitizers | IncludeMatcher
}
private void _checkDefaultExtensions(RecordingHandler handlerForTest, CheckSkips skipsToCheck = CheckSkips.Default)
{
if (skipsToCheck.HasFlag(CheckSkips.IncludeTransforms))
{
Assert.Equal(3, handlerForTest.Transforms.Count);
Assert.IsType<StorageRequestIdTransform>(handlerForTest.Transforms[0]);
Assert.IsType<ClientIdTransform>(handlerForTest.Transforms[1]);
Assert.IsType<HeaderTransform>(handlerForTest.Transforms[2]);
}
if (skipsToCheck.HasFlag(CheckSkips.IncludeMatcher))
{
Assert.NotNull(handlerForTest.Matcher);
Assert.IsType<RecordMatcher>(handlerForTest.Matcher);
}
if (skipsToCheck.HasFlag(CheckSkips.IncludeSanitizers))
{
var sessionSanitizers = handlerForTest.SanitizerRegistry.GetSanitizers();
Assert.Equal(3, sessionSanitizers.Count);
Assert.IsType<RecordedTestSanitizer>(sessionSanitizers[0]);
Assert.IsType<BodyKeySanitizer>(sessionSanitizers[1]);
Assert.IsType<BodyKeySanitizer>(sessionSanitizers[2]);
}
}
#endregion
[Fact]
public void TestGetHeader()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
httpContext.Request.Headers["x-test-presence"] = "This header has a value";
var controller = new Admin(testRecordingHandler, _nullLogger)
{
ControllerContext = new ControllerContext()
{
HttpContext = httpContext
}
};
RecordingHandler.GetHeader(httpContext.Request, "x-test-presence");
}
[Fact]
public void TestGetHeaderThrowsOnMissingHeader()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
var controller = new Admin(testRecordingHandler, _nullLogger)
{
ControllerContext = new ControllerContext()
{
HttpContext = httpContext
}
};
var assertion = Assert.Throws<HttpException>(
() => RecordingHandler.GetHeader(httpContext.Request, "x-test-presence")
);
}
[Fact]
public void TestGetHeaderSilentOnAcceptableHeaderMiss()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
var controller = new Admin(testRecordingHandler, _nullLogger)
{
ControllerContext = new ControllerContext()
{
HttpContext = httpContext
}
};
var value = RecordingHandler.GetHeader(httpContext.Request, "x-test-presence", allowNulls: true);
Assert.Null(value);
}
[Fact]
public void TestResetAfterAddition()
{
// arrange
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
// act
testRecordingHandler.SanitizerRegistry.Register(new BodyRegexSanitizer("sanitized", ".*"));
testRecordingHandler.Matcher = new BodilessMatcher();
testRecordingHandler.Transforms.Add(new ApiVersionTransform());
testRecordingHandler.SetDefaultExtensions();
//assert
_checkDefaultExtensions(testRecordingHandler);
}
[Fact]
public void TestResetAfterRemoval()
{
// arrange
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
// act
testRecordingHandler.SanitizerRegistry.Clear();
testRecordingHandler.Matcher = null;
testRecordingHandler.Transforms.Clear();
testRecordingHandler.SetDefaultExtensions();
//assert
_checkDefaultExtensions(testRecordingHandler);
}
[Fact]
public async Task TestResetTargetsRecordingOnly()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
await testRecordingHandler.StartRecordingAsync("recordingings/cool.json", httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
testRecordingHandler.SanitizerRegistry.Clear();
testRecordingHandler.SanitizerRegistry.Register(new BodyRegexSanitizer("sanitized", ".*"));
testRecordingHandler.RegisterSanitizer(new GeneralRegexSanitizer("sanitized", ".*"), recordingId);
testRecordingHandler.SetDefaultExtensions(recordingId);
var session = testRecordingHandler.RecordingSessions.First().Value;
var recordingSanitizers = testRecordingHandler.SanitizerRegistry.GetSanitizers(session);
var sessionSanitizers = testRecordingHandler.SanitizerRegistry.GetSanitizers();
// session sanitizer is still set to a single one
Assert.Single(sessionSanitizers);
Assert.IsType<BodyRegexSanitizer>(sessionSanitizers[0]);
_checkDefaultExtensions(testRecordingHandler, CheckSkips.IncludeMatcher | CheckSkips.IncludeTransforms);
Assert.Equal(session.AppliedSanitizers, testRecordingHandler.SanitizerRegistry.SessionSanitizers);
Assert.Empty(session.AdditionalTransforms);
Assert.Null(session.CustomMatcher);
}
[Fact]
public async Task TestResetTargetsSessionOnly()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
await testRecordingHandler.StartRecordingAsync("recordingings/cool.json", httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
testRecordingHandler.SanitizerRegistry.Clear();
testRecordingHandler.SanitizerRegistry.Register(new BodyRegexSanitizer("sanitized", ".*"));
testRecordingHandler.Transforms.Clear();
testRecordingHandler.RegisterSanitizer(new GeneralRegexSanitizer("sanitized", ".*"), recordingId);
testRecordingHandler.SetDefaultExtensions(recordingId);
var session = testRecordingHandler.RecordingSessions.First().Value;
// check that the individual session had reset sanitizers
Assert.Equal(testRecordingHandler.SanitizerRegistry.GetSanitizers(), testRecordingHandler.SanitizerRegistry.GetSanitizers(session));
// stop the recording to clear out the session cache
testRecordingHandler.StopRecording(recordingId);
// then verify that the session level is NOT reset.
Assert.Single(testRecordingHandler.SanitizerRegistry.GetSanitizers());
Assert.IsType<BodyRegexSanitizer>(testRecordingHandler.SanitizerRegistry.GetSanitizers().First());
}
[Fact]
public async Task TestResetExtensionsFailsWithActiveSessions()
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
await testRecordingHandler.StartRecordingAsync("recordingings/cool.json", httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
var assertion = Assert.Throws<HttpException>(
() => testRecordingHandler.SetDefaultExtensions()
);
Assert.StartsWith("There are a total of 1 active sessions. Remove these sessions before hitting Admin/Reset.", assertion.Message);
}
[Fact]
public async Task TestInMemoryPurgesSucessfully()
{
var recordingHandler = TestHelpers.LoadRecordSessionIntoInMemoryStore("Test.RecordEntries/post_delete_get_content.json");
var httpContext = new DefaultHttpContext();
var key = recordingHandler.InMemorySessions.Keys.First();
await recordingHandler.StartPlaybackAsync(key, httpContext.Response, Common.RecordingType.InMemory);
var playbackSession = httpContext.Response.Headers["x-recording-id"];
recordingHandler.StopPlayback(playbackSession, true);
Assert.True(0 == recordingHandler.InMemorySessions.Count);
}
[Fact]
public async Task TestInMemoryDoesntPurgeErroneously()
{
var recordingHandler = TestHelpers.LoadRecordSessionIntoInMemoryStore("Test.RecordEntries/post_delete_get_content.json");
var httpContext = new DefaultHttpContext();
var key = recordingHandler.InMemorySessions.Keys.First();
await recordingHandler.StartPlaybackAsync(key, httpContext.Response, Common.RecordingType.InMemory);
var playbackSession = httpContext.Response.Headers["x-recording-id"];
recordingHandler.StopPlayback(playbackSession, false);
Assert.True(1 == recordingHandler.InMemorySessions.Count);
}
[Fact]
public async Task TestLoadOfAbsoluteRecording()
{
var tmpPath = Path.GetTempPath();
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = Path.Combine(currentPath, "Test.RecordEntries/oauth_request.json");
var recordingHandler = new RecordingHandler(tmpPath);
await recordingHandler.StartPlaybackAsync(pathToRecording, httpContext.Response);
var playbackSession = recordingHandler.PlaybackSessions.First();
var entry = playbackSession.Value.Session.Entries.First();
Assert.Equal("https://login.microsoftonline.com/12345678-1234-1234-1234-123456789012/oauth2/v2.0/token", entry.RequestUri);
}
[Fact]
public async Task TestLoadOfRelativeRecording()
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "Test.RecordEntries/oauth_request.json";
var recordingHandler = new RecordingHandler(currentPath);
await recordingHandler.StartPlaybackAsync(pathToRecording, httpContext.Response);
var playbackSession = recordingHandler.PlaybackSessions.First();
var entry = playbackSession.Value.Session.Entries.First();
Assert.Equal("https://login.microsoftonline.com/12345678-1234-1234-1234-123456789012/oauth2/v2.0/token", entry.RequestUri);
}
[Fact]
public async Task TestWriteAbsoluteRecording()
{
var tmpPath = Path.GetTempPath();
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = Path.Combine(currentPath, "recordings/oauth_request_new.json");
var recordingHandler = new RecordingHandler(tmpPath);
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
recordingHandler.StopRecording(sessionId);
try
{
Assert.True(File.Exists(pathToRecording));
}
finally
{
File.Delete(pathToRecording);
}
}
[Fact]
public async Task TestWriteRelativeRecording()
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/oauth_request_new";
var recordingHandler = new RecordingHandler(currentPath);
var fullPathToRecording = Path.Combine(currentPath, pathToRecording) + ".json";
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
recordingHandler.StopRecording(sessionId);
try
{
Assert.True(File.Exists(fullPathToRecording));
}
finally
{
File.Delete(fullPathToRecording);
}
}
[Fact]
public async Task TestCanSkipRecordingRequestBody()
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/skip_body";
var mockClient = new HttpClient(new MockHttpHandler());
var recordingHandler = new RecordingHandler(currentPath)
{
RedirectableClient = mockClient,
RedirectlessClient = mockClient
};
var fullPathToRecording = Path.Combine(currentPath, pathToRecording) + ".json";
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
CreateRecordModeRequest(httpContext, "request-body");
await recordingHandler.HandleRecordRequestAsync(sessionId, httpContext.Request, httpContext.Response);
recordingHandler.StopRecording(sessionId);
try
{
using var fileStream = File.Open(fullPathToRecording, FileMode.Open);
using var doc = JsonDocument.Parse(fileStream);
var record = RecordSession.Deserialize(doc.RootElement);
var entry = record.Entries.First();
Assert.Null(entry.Request.Body);
Assert.Equal(MockHttpHandler.DefaultResponse, Encoding.UTF8.GetString(entry.Response.Body));
}
finally
{
File.Delete(fullPathToRecording);
}
}
[Fact]
public async Task TestCanSkipRecordingEntireRequestResponse()
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/skip_entry";
var mockClient = new HttpClient(new MockHttpHandler());
var recordingHandler = new RecordingHandler(currentPath)
{
RedirectableClient = mockClient,
RedirectlessClient = mockClient
};
var fullPathToRecording = Path.Combine(currentPath, pathToRecording) + ".json";
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
CreateRecordModeRequest(httpContext, "request-response");
await recordingHandler.HandleRecordRequestAsync(sessionId, httpContext.Request, httpContext.Response);
httpContext = new DefaultHttpContext();
// send a second request that SHOULD be recorded
CreateRecordModeRequest(httpContext);
httpContext.Request.Headers.Remove("x-recording-skip");
httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody("{ \"key\": \"value\" }");
await recordingHandler.HandleRecordRequestAsync(sessionId, httpContext.Request, httpContext.Response);
recordingHandler.StopRecording(sessionId);
try
{
using var fileStream = File.Open(fullPathToRecording, FileMode.Open);
using var doc = JsonDocument.Parse(fileStream);
var record = RecordSession.Deserialize(doc.RootElement);
Assert.Single(record.Entries);
var entry = record.Entries.First();
Assert.Equal("value", JsonDocument.Parse(entry.Request.Body).RootElement.GetProperty("key").GetString());
Assert.Equal(MockHttpHandler.DefaultResponse, Encoding.UTF8.GetString(entry.Response.Body));
}
finally
{
File.Delete(fullPathToRecording);
}
}
[Theory]
[InlineData("invalid value")]
[InlineData("")]
[InlineData("request-body", "request-response")]
public async Task TestInvalidRecordModeThrows(params string[] values)
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/invalid_record_mode";
var mockClient = new HttpClient(new MockHttpHandler());
var recordingHandler = new RecordingHandler(currentPath)
{
RedirectableClient = mockClient,
RedirectlessClient = mockClient
};
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
CreateRecordModeRequest(httpContext, new StringValues(values));
HttpException resultingException = await Assert.ThrowsAsync<HttpException>(
async () => await recordingHandler.HandleRecordRequestAsync(sessionId, httpContext.Request, httpContext.Response)
);
Assert.Equal(HttpStatusCode.BadRequest, resultingException.StatusCode);
}
private static void CreateRecordModeRequest(DefaultHttpContext context, StringValues mode = default)
{
context.Request.Headers["x-recording-skip"] = mode;
context.Request.Headers["x-recording-upstream-base-uri"] = "https://contoso.net";
context.Request.ContentType = "application/json";
context.Request.Method = "PUT";
context.Request.Body = TestHelpers.GenerateStreamRequestBody("{ \"key\": \"value\" }");
// content length must be set for the body to be parsed in SetMatcher
context.Request.ContentLength = context.Request.Body.Length;
}
[Fact]
public async Task TestLoadNonexistentAbsoluteRecording()
{
var tmpPath = Path.GetTempPath();
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var recordingPath = "Test.RecordEntries/oauth_request_wrong.json";
var pathToRecording = Path.Combine(currentPath, recordingPath);
var recordingHandler = new RecordingHandler(tmpPath);
var resultingException = await Assert.ThrowsAsync<TestRecordingMismatchException>(
async () => await recordingHandler.StartPlaybackAsync(pathToRecording, httpContext.Response)
);
Assert.Contains($"{recordingPath} does not exist", resultingException.Message);
}
[Fact]
public async Task TestLoadNonexistentRelativeRecording()
{
var currentPath = Directory.GetCurrentDirectory();
var httpContext = new DefaultHttpContext();
var pathToRecording = "Test.RecordEntries/oauth_request_wrong.json";
var recordingHandler = new RecordingHandler(currentPath);
var resultingException = await Assert.ThrowsAsync<TestRecordingMismatchException>(
async () => await recordingHandler.StartPlaybackAsync(pathToRecording, httpContext.Response)
);
Assert.Contains($"{pathToRecording} does not exist", resultingException.Message);
}
[Fact]
public async Task TestStopRecordingWithVariables()
{
var tmpPath = Path.GetTempPath();
var startHttpContext = new DefaultHttpContext();
var pathToRecording = "recordings/oauth_request_new.json";
var recordingHandler = new RecordingHandler(tmpPath);
var dict = new Dictionary<string, string>{
{ "key1","valueabc123" },
{ "key2", "value123abc" }
};
var endHttpContext = new DefaultHttpContext();
await recordingHandler.StartRecordingAsync(pathToRecording, startHttpContext.Response);
var sessionId = startHttpContext.Response.Headers["x-recording-id"].ToString();
recordingHandler.StopRecording(sessionId, variables: new SortedDictionary<string, string>(dict));
var storedVariables = TestHelpers.LoadRecordSession(Path.Combine(tmpPath, pathToRecording)).Session.Variables;
Assert.Equal(dict.Count, storedVariables.Count);
foreach (var kvp in dict)
{
Assert.Equal(kvp.Value, storedVariables[kvp.Key]);
}
}
[Fact]
public async Task TestStopRecordingWithoutVariables()
{
var tmpPath = Path.GetTempPath();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/oauth_request_new.json";
var recordingHandler = new RecordingHandler(tmpPath);
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
recordingHandler.StopRecording(sessionId, variables: new SortedDictionary<string, string>());
var storedVariables = TestHelpers.LoadRecordSession(Path.Combine(tmpPath, pathToRecording)).Session.Variables;
Assert.Empty(storedVariables);
}
[Fact]
public async Task TestStopRecordingNullVariables()
{
var tmpPath = Path.GetTempPath();
var httpContext = new DefaultHttpContext();
var pathToRecording = "recordings/oauth_request_new.json";
var recordingHandler = new RecordingHandler(tmpPath);
await recordingHandler.StartRecordingAsync(pathToRecording, httpContext.Response);
var sessionId = httpContext.Response.Headers["x-recording-id"].ToString();
recordingHandler.StopRecording(sessionId, variables: null);
var storedVariables = TestHelpers.LoadRecordSession(Path.Combine(tmpPath, pathToRecording)).Session.Variables;
Assert.Empty(storedVariables);
}
[Fact]
public async Task TestStartPlaybackWithVariables()
{
var httpContext = new DefaultHttpContext();
var recordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
httpContext.Response.Body = new MemoryStream();
await recordingHandler.StartPlaybackAsync("Test.RecordEntries/oauth_request_with_variables.json", httpContext.Response);
Dictionary<string, string> results = JsonConvert.DeserializeObject<Dictionary<string, string>>(
TestHelpers.GenerateStringFromStream(httpContext.Response.Body)
);
Assert.Equal(2, results.Count);
Assert.Equal("value1", results["key1"]);
Assert.Equal("value2", results["key2"]);
}
[Fact]
public async Task TestStartPlaybackWithoutVariables()
{
var startHttpContext = new DefaultHttpContext();
var recordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
await recordingHandler.StartPlaybackAsync("Test.RecordEntries/oauth_request.json", startHttpContext.Response);
}
[Fact]
public async Task CreateEntryUsesAbsoluteUri()
{
var request = new DefaultHttpContext().Request;
var uri = new Uri("http://contoso.net/my cool directory");
request.Host = new HostString(uri.Host);
request.Path = uri.PathAndQuery;
request.Headers["x-recording-upstream-base-uri"] = uri.AbsoluteUri;
var entry = (await RecordingHandler.CreateEntryAsync(request)).Item1;
Assert.Equal(uri.AbsoluteUri, entry.RequestUri);
}
[Theory]
[InlineData("Content-Type:application/json; odata=minimalmetadata; streaming=true", "Accept:application/json;odata=minimalmetadata")]
[InlineData("Content-MD5:<ContentHash>", "x-ms-version:2019-02-02", "RequestMethod:POST", "Connection:keep-alive")]
[InlineData("Content-Encoding:utf-8", "x-ms-version:2019-02-02", "RequestMethod:POST", "Content-Length:50")]
public void TestCreateUpstreamRequestIncludesExpectedHeaders(params string[] incomingHeaders)
{
var requestContext = GenerateHttpRequestContext(incomingHeaders);
var recordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var upstreamRequestContext = GenerateHttpRequestContext(incomingHeaders);
var output = recordingHandler.CreateUpstreamRequest(upstreamRequestContext.Request, new byte[] { });
// iterate across the set we know about and confirm that GenerateUpstreamRequest worked properly!
var setOfHeaders = GenerateHeaderValuesTuples(incomingHeaders);
{
foreach (var headerTuple in setOfHeaders)
{
var inContent = false;
var inStandard = false;
try
{
inContent = output.Headers.Contains(headerTuple.Item1);
}
catch (Exception) { }
try
{
inStandard = output.Content.Headers.Contains(headerTuple.Item1);
}
catch (Exception) { }
Assert.True(inContent || inStandard);
}
}
}
[Theory]
[InlineData("awesomehost.com")]
[InlineData("")]
public async Task TestRecordMaintainsUpstreamOverrideHostHeader(string upstreamHostHeaderValue)
{
var httpContext = new DefaultHttpContext();
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
await testRecordingHandler.StartRecordingAsync("hello.json", httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
httpContext.Request.Body = TestHelpers.GenerateStreamRequestBody(String.Empty);
httpContext.Request.ContentLength = 0;
httpContext.Request.Headers["x-recording-id"] = recordingId;
httpContext.Request.Headers["x-recording-upstream-base-uri"] = "http://example.org";
if (!String.IsNullOrWhiteSpace(upstreamHostHeaderValue))
{
httpContext.Request.Headers["x-recording-upstream-host-header"] = upstreamHostHeaderValue;
}
httpContext.Request.Method = "GET";
var upstreamRequest = testRecordingHandler.CreateUpstreamRequest(httpContext.Request, new byte[] { });
if (!String.IsNullOrWhiteSpace(upstreamHostHeaderValue))
{
Assert.Equal(upstreamHostHeaderValue, upstreamRequest.Headers.Host);
}
else
{
Assert.Null(upstreamRequest.Headers.Host);
}
}
[Fact]
public async Task TestRecordWithGZippedContent()
{
var httpContext = new DefaultHttpContext();
var bodyBytes = Encoding.UTF8.GetBytes("{\"hello\":\"world\"}");
var mockClient = new HttpClient(new MockHttpHandler(bodyBytes, "application/json", "gzip"));
var path = Directory.GetCurrentDirectory();
var recordingHandler = new RecordingHandler(path)
{
RedirectableClient = mockClient,
RedirectlessClient = mockClient
};
var relativePath = "recordings/gzip";
var fullPathToRecording = Path.Combine(path, relativePath) + ".json";
await recordingHandler.StartRecordingAsync(relativePath, httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
httpContext.Request.ContentType = "application/json";
httpContext.Request.Headers["Content-Encoding"] = "gzip";
httpContext.Request.ContentLength = 0;
httpContext.Request.Headers["x-recording-id"] = recordingId;
httpContext.Request.Headers["x-recording-upstream-base-uri"] = "http://example.org";
httpContext.Request.Method = "GET";
httpContext.Request.Body = new MemoryStream(CompressionUtilities.CompressBody(bodyBytes, httpContext.Request.Headers));
await recordingHandler.HandleRecordRequestAsync(recordingId, httpContext.Request, httpContext.Response);
recordingHandler.StopRecording(recordingId);
try
{
using var fileStream = File.Open(fullPathToRecording, FileMode.Open);
using var doc = JsonDocument.Parse(fileStream);
var record = RecordSession.Deserialize(doc.RootElement);
var entry = record.Entries.First();
Assert.Equal("{\"hello\":\"world\"}", Encoding.UTF8.GetString(entry.Request.Body));
Assert.Equal("{\"hello\":\"world\"}", Encoding.UTF8.GetString(entry.Response.Body));
}
finally
{
File.Delete(fullPathToRecording);
}
}
[Fact]
public async Task RecordingHandlerIsThreadSafe()
{
var bodyBytes = Encoding.UTF8.GetBytes("{\"hello\":\"world\"}");
var mockClient = new HttpClient(new MockHttpHandler(bodyBytes));
var path = Directory.GetCurrentDirectory();
var recordingHandler = new RecordingHandler(path)
{
RedirectableClient = mockClient,
RedirectlessClient = mockClient
};
var httpContext = new DefaultHttpContext();
await recordingHandler.StartRecordingAsync("threadSafe", httpContext.Response);
var recordingId = httpContext.Response.Headers["x-recording-id"].ToString();
var requests = new List<Task>();
var requestCount = 100;
for (int i = 0; i < requestCount; i++)
{
httpContext = new DefaultHttpContext();
httpContext.Request.ContentType = "application/json";
httpContext.Request.ContentLength = 0;
httpContext.Request.Headers["x-recording-id"] = recordingId;
httpContext.Request.Headers["x-recording-upstream-base-uri"] = "http://example.org";
httpContext.Request.Method = "GET";
httpContext.Request.Body = new MemoryStream(bodyBytes);
requests.Add(recordingHandler.HandleRecordRequestAsync(recordingId, httpContext.Request, httpContext.Response));
}
await Task.WhenAll(requests);
var session = recordingHandler.RecordingSessions.First().Value;
Assert.Equal(requestCount, session.Session.Entries.Count);
}
#region ByteManipulation
private const string longBody = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.";
[Theory]
[InlineData("", 1)]
[InlineData("small body", 5)]
[InlineData("this is a body", 3)]
[InlineData("This is a little bit longer of a body that we are dividing in 2", 2)]
[InlineData(longBody, 5)]
[InlineData(longBody, 1)]
[InlineData(longBody, 10)]
public void TestGetBatches(string input, int batchCount)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var bodyData = Encoding.UTF8.GetBytes(input);
var chunks = testRecordingHandler.GetBatches(bodyData, batchCount);
int bodyPosition = 0;
// ensure that all bytes are accounted for across the batches
foreach(var chunk in chunks)
{
for (int j = 0; j < chunk.Length; j++)
{
Assert.Equal(chunk[j], bodyData[bodyPosition]);
bodyPosition++;
}
}
Assert.Equal(bodyPosition, bodyData.Length);
}
#endregion
#region SetRecordingOptions
[Theory]
[InlineData("{ \"HandleRedirects\": \"true\"}", true)]
[InlineData("{ \"HandleRedirects\": \"false\"}", false)]
[InlineData("{ \"HandleRedirects\": \"1\"}", true)]
[InlineData("{ \"HandleRedirects\": \"0\"}", false)]
[InlineData("{ \"HandleRedirects\": \"True\"}", true)]
[InlineData("{ \"HandleRedirects\": \"False\"}", false)]
[InlineData("{ \"HandleRedirects\": \"TRUE\"}", true)]
[InlineData("{ \"HandleRedirects\": \"FALSE\"}", false)]
[InlineData("{ \"HandleRedirects\": true }", true)]
[InlineData("{ \"HandleRedirects\": false }", false)]
[InlineData("{ \"HandleRedirects\": 1 }", true)]
[InlineData("{ \"HandleRedirects\": 0 }", false)]
public void TestSetRecordingOptionsHandlesValidRedirectSetting(string body, bool expectedSetting)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
Dictionary<string, object> inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
testRecordingHandler.SetRecordingOptions(inputBody);
Assert.Equal(expectedSetting, testRecordingHandler.HandleRedirects);
}
[Theory]
[InlineData("{ \"HandleRedirects\": \"anotherkey\"}", "The value of key \"HandleRedirects\" MUST be castable to a valid boolean value.")]
[InlineData("{ \"HandleRedirects\": \"true2\"}", "The value of key \"HandleRedirects\" MUST be castable to a valid boolean value.")]
[InlineData("{}", "At least one key is expected in the body being passed to SetRecordingOptions.")]
[InlineData(null, "When setting recording options, the request body is expected to be non-null and of type Dictionary<string, string>.")]
public void TestSetRecordingOptionsThrowsOnInvalidRedirectSetting(string body, string errorText)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
Dictionary<string, object> inputBody = null;
if (!string.IsNullOrWhiteSpace(body))
{
inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
}
var assertion = Assert.Throws<HttpException>(
() => testRecordingHandler.SetRecordingOptions(inputBody)
);
Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
Assert.Contains(errorText, assertion.Message);
}
[Theory]
[InlineData("hellothere", "generalkenobi")]
[InlineData("", "")]
public void TestSetRecordingOptionsHandlesValidContextDirectory(params string[] relativePaths)
{
var relativePath = Path.Combine(relativePaths);
var testDirectory = Path.GetTempPath();
RecordingHandler testRecordingHandler = new RecordingHandler(testDirectory);
testDirectory = Path.Combine(testDirectory, relativePath);
var body = $"{{ \"ContextDirectory\": \"{testDirectory.Replace("\\", "/")}\"}}";
var httpContext = new DefaultHttpContext();
Dictionary<string, object> inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
testRecordingHandler.SetRecordingOptions(inputBody);
Assert.Equal(new Uri(testDirectory), new Uri(testRecordingHandler.ContextDirectory));
}
[Theory]
[InlineData("{ \"ContextDirectory\": \":/repo/\0\"}", "Unable set proxy context to target directory")]
public void TestSetRecordingOptionsThrowsOnInvalidContextDirectory(string body, string errorText)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
var httpContext = new DefaultHttpContext();
Dictionary<string, object> inputBody = null;
if (!string.IsNullOrWhiteSpace(body))
{
inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
}
var assertion = Assert.Throws<HttpException>(
() => testRecordingHandler.SetRecordingOptions(inputBody)
);
Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
Assert.StartsWith(errorText, assertion.Message);
}
[Theory]
[InlineData("{ \"AssetsStore\": \"NullStore\"}")]
[InlineData("{ \"AssetsStore\": \"GitStore\"}")]
[InlineData("{ \"AssetsStore\": \"Azure.Sdk.Tools.TestProxy.Store.GitStore\"}")]
[InlineData("{ \"AssetsStore\": \"Azure.Sdk.Tools.TestProxy.Store.NullStore\"}")]
public void TestSetRecordingOptionsHandlesValidStoreTypes(string body)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
testRecordingHandler.Store = null;
Dictionary<string, object> inputBody = null;
if (!string.IsNullOrWhiteSpace(body))
{
inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
}
testRecordingHandler.SetRecordingOptions(inputBody);
Assert.NotNull(testRecordingHandler.Store);
}
[Theory]
[InlineData("{ \"AssetsStore\": \"NonExistent\"}", "Unable to load the specified IAssetStore class NonExistent.")]
[InlineData("{ \"AssetsStore\": \"\"}", "Users must provide a valid value when providing the key \"AssetsStore\"")]
[InlineData("{ \"AssetsStore\": \"GitAssetsConfiguration\"}", "Unable to create an instance of type GitAssetsConfiguration")]
public void TestSetRecordingOptionsThrowsOnInvalidStoreTypes(string body, string errorText)
{
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
Dictionary<string, object> inputBody = null;
if (!string.IsNullOrWhiteSpace(body))
{
inputBody = JsonConvert.DeserializeObject<Dictionary<string, object>>(body);
}
var assertion = Assert.Throws<HttpException>(
() => testRecordingHandler.SetRecordingOptions(inputBody)
);
Assert.True(assertion.StatusCode.Equals(HttpStatusCode.BadRequest));
Assert.StartsWith(errorText, assertion.Message);
}
[Fact]
public void TestSetRecordingOptionsValidTlsCert()
{
var certValue = TestHelpers.GetValueFromCertificateFile("test_public-key-only_pem").Replace(Environment.NewLine, "");
var inputObj = string.Format("{{\"Transport\": {{\"TLSValidationCert\": \"{0}\"}}}}", certValue);
var testRecordingHandler = new RecordingHandler(Path.Join(Path.GetTempPath(), Guid.NewGuid().ToString()));
var inputBody = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(inputObj, SerializerOptions);
testRecordingHandler.SetRecordingOptions(inputBody, null);
}
[Fact]
public void TestSetRecordingOptionsMultipleCertOptions()
{
var certValue = TestHelpers.GetValueFromCertificateFile("test_public-key-only_pem").Replace(Environment.NewLine, "");
var pemKey = TestHelpers.GetValueFromCertificateFile("test_pem_key").Replace(Environment.NewLine, "");
var pemValue = TestHelpers.GetValueFromCertificateFile("test_pem_value").Replace(Environment.NewLine, "");
var inputObj = string.Format("{{\"Transport\": {{\"TLSValidationCert\": \"{0}\", \"Certificates\": [ {{ \"PemValue\": \"{1}\", \"PemKey\": \"{2}\" }}]}}}}", certValue, pemValue, pemKey);
var testRecordingHandler = new RecordingHandler(Path.Join(Path.GetTempPath(), Guid.NewGuid().ToString()));
var inputBody = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(inputObj, SerializerOptions);
testRecordingHandler.SetRecordingOptions(inputBody, null);
}
[Theory]
[InlineData("{{\"Transport\": {{\"Certificates\": [ {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}, {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}]}}}}")]
[InlineData("{{\"Transport\": {{\"Certificates\": [ {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}]}}}}")]
[InlineData("{{\"Transport\": {{\"Certificates\": []}}}}")]
public void TestSetRecordingOptionsValidTransportSessionLevel(string body)
{
var pemKey = TestHelpers.GetValueFromCertificateFile("test_pem_key").Replace(Environment.NewLine, "");
var pemValue = TestHelpers.GetValueFromCertificateFile("test_pem_value").Replace(Environment.NewLine, "");
var inputObj = string.Format(body, pemValue, pemKey);
var inputBody = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(inputObj, SerializerOptions);
RecordingHandler testRecordingHandler = new RecordingHandler(Directory.GetCurrentDirectory());
testRecordingHandler.SetRecordingOptions(inputBody, null);
}
[Theory]
[InlineData("{{\"Transport\": {{\"Certificates\": [ {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}, {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}]}}}}")]
[InlineData("{{\"Transport\": {{\"Certificates\": [ {{ \"PemValue\": \"{0}\", \"PemKey\": \"{1}\" }}]}}}}")]
[InlineData("{{\"Transport\": {{\"Certificates\": []}}}}")]
public async Task TestSetRecordingOptionsValidTransportRecordingLevel(string body)
{
var pemKey = TestHelpers.GetValueFromCertificateFile("test_pem_key").Replace(Environment.NewLine, "");