-
Notifications
You must be signed in to change notification settings - Fork 235
Expand file tree
/
Copy pathRecordSessionTests.cs
More file actions
718 lines (629 loc) · 32 KB
/
RecordSessionTests.cs
File metadata and controls
718 lines (629 loc) · 32 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Sdk.Tools.TestProxy.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualBasic;
using Moq;
using NuGet.ContentModel;
using Xunit;
namespace Azure.Sdk.Tools.TestProxy.Tests
{
public class RecordSessionTests
{
[Theory]
[InlineData("{\"json\":\"value\"}", "application/json")]
[InlineData("{\"json\":\"\\\"value\\\"\"}", "application/json")]
[InlineData("{\"json\":{\"json\":\"value\"}}", "application/json")]
[InlineData("[\"json\",\"value\"]", "application/json")]
[InlineData("[{\"json\":\"value\"},{\"json\":\"value\"}]", "application/json")]
[InlineData("\"\"", "application/json")]
[InlineData("invalid json", "application/json")]
[InlineData("null", "application/json")]
[InlineData("\"null\"", "application/json")]
[InlineData(null, "application/json")]
[InlineData("{}", "application/json")]
[InlineData("[]", "application/json")]
[InlineData("19", "application/json")]
[InlineData("true", "application/json")]
[InlineData("false", "application/json")]
[InlineData("{\"a-key\":\"akeywith+inthemiddle\"}", "application/json")]
[InlineData("{\"json\":\"value\"}", "unknown")]
[InlineData("multi\rline", "application/xml")]
[InlineData("multi\r\nline", "application/xml")]
[InlineData("multi\n\rline\n", "application/xml")]
[InlineData("", "")]
[InlineData("true", "")]
public void CanRoundtripSessionRecord(string body, string contentType)
{
byte[] bodyBytes = body != null ? Encoding.UTF8.GetBytes(body) : null;
var session = new RecordSession();
session.Variables["a"] = "value a";
session.Variables["b"] = "value b";
RecordEntry recordEntry = new RecordEntry();
recordEntry.Request.Headers.Add("Content-Type", new[] { contentType });
recordEntry.Request.Headers.Add("Other-Header", new[] { "multi", "value" });
recordEntry.Request.Body = bodyBytes;
recordEntry.RequestUri = "url";
recordEntry.RequestMethod = RequestMethod.Delete;
recordEntry.Response.Headers.Add("Content-Type", new[] { contentType });
recordEntry.Response.Headers.Add("Other-Response-Header", new[] { "multi", "value" });
recordEntry.Response.Body = bodyBytes;
recordEntry.StatusCode = 202;
session.Entries.Add(recordEntry);
var arrayBufferWriter = new ArrayBufferWriter<byte>();
using var jsonWriter = new Utf8JsonWriter(arrayBufferWriter, new JsonWriterOptions()
{
Indented = true, Encoder = RecordEntry.WriterOptions.Encoder
});
session.Serialize(jsonWriter);
jsonWriter.Flush();
var document = JsonDocument.Parse(arrayBufferWriter.WrittenMemory);
var deserializedSession = RecordSession.Deserialize(document.RootElement);
Assert.Equal("value a", deserializedSession.Variables["a"]);
Assert.Equal("value b", deserializedSession.Variables["b"]);
RecordEntry deserializedRecord = deserializedSession.Entries.Single();
Assert.Equal(RequestMethod.Delete, recordEntry.RequestMethod);
Assert.Equal("url", recordEntry.RequestUri);
Assert.Equal(202, recordEntry.StatusCode);
Assert.Equal(new[] { contentType }, deserializedRecord.Request.Headers["content-type"]);
Assert.Equal(new[] { "multi", "value" }, deserializedRecord.Request.Headers["other-header"]);
Assert.Equal(new[] { contentType }, deserializedRecord.Response.Headers["content-type"]);
Assert.Equal(new[] { "multi", "value" }, deserializedRecord.Response.Headers["other-response-header"]);
Assert.Equal(bodyBytes, deserializedRecord.Request.Body);
Assert.Equal(bodyBytes, deserializedRecord.Response.Body);
}
[Fact]
public async Task CanRoundTripDockerDigest()
{
// get everything organized
var sampleExpected = "{\n \"schemaVersion\": 2,\n \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n \"config\": {\n \"mediaType\": \"application/vnd.docker.container.image.v1+json\",\n \"size\"" +
": 1472,\n \"digest\": \"sha256:042a816809aac8d0f7d7cacac7965782ee2ecac3f21bcf9f24b1de1a7387b769\"\n },\n \"layers\": [\n {\n \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n \"size\"" + "" +
": 3370628,\n \"digest\": \"sha256:8921db27df2831fa6eaa85321205a2470c669b855f3ec95d5a3c2b46de0442c9\"\n }\n ]\n}";
var testName = "roundtrip.json";
DefaultHttpContext ctx = new DefaultHttpContext();
Assets assets = new Assets()
{
AssetsRepo = "Azure/azure-sdk-assets-integration",
AssetsRepoPrefixPath = "pull/scenarios",
AssetsRepoId = "",
TagPrefix = "language/tables",
Tag = "python/tables_fc54d0"
};
var folderStructure = new string[]
{
GitStoretests.AssetsJson
};
var testEntry = new RecordEntry()
{
RequestUri = "https://Sanitized.azurecr.io/v2/alpine/manifests/3.17.1",
RequestMethod = RequestMethod.Get,
Request = new RequestOrResponse()
{
Headers = new SortedDictionary<string, string[]>()
{
{ "Accept", new string[]{ "application/json", "application/vnd.docker.distribution.manifest.v2+json" } },
{ "Accept-Encoding", new string[]{ "gzip" } },
{ "Authorization", new string[]{ "Sanitized" } },
{ "User-Agent", new string[]{ "azsdk-go-azcontainerregistry/v0.2.2 (go1.21.6; linux)" } },
},
Body = null,
},
StatusCode = 200,
Response = new RequestOrResponse()
{
Headers = new SortedDictionary<string, string[]>()
{
{ "Access-Control-Expose-Headers", new string[]{ "Docker-Content-Digest", "WWW-Authenticate", "Link","X-Ms-Correlation-Request-Id" } },
{ "Connection", new string[]{ "keep-alive" } },
{ "Content-Length", new string[]{ "528" } },
{ "Content-Type", new string[]{ "application/vnd.docker.distribution.manifest.v2+json" } },
{ "Date", new string[]{ "Fri, 17 May 2024 21:42:34 GMT" } },
{ "Docker-Content-Digest", new string[]{ "sha256:93d5a28ff72d288d69b5997b8ba47396d2cbb62a72b5d87cd3351094b5d578a0" } },
{ "Docker-Distribution-Api-Version", new string[]{ "registry/2.0" } },
{ "ETag", new string[]{ "\"sha256:93d5a28ff72d288d69b5997b8ba47396d2cbb62a72b5d87cd3351094b5d578a0\"" } },
{ "Server", new string[]{ "AzureContainerRegistry" } },
{ "Strict-Transport-Security", new string[]{ "max-age=31536000; includeSubDomains", "max-age=31536000; includeSubDomains" } },
{ "X-Content-Type-Options", new string[]{ "nosniff" } },
{ "X-Ms-Client-Request-Id", new string[]{ "" } },
{ "X-Ms-Correlation-Request-Id", new string[]{ "caf56438-d3ba-469d-a30c-360a4ff536c1" } },
{ "X-Ms-Request-Id", new string[]{ "Sanitized" } },
},
Body = Encoding.UTF8.GetBytes(sampleExpected)
},
};
// create the session which will be saved to disk, then save it
var testFolder = TestHelpers.DescribeTestFolder(assets, folderStructure);
var handler = new RecordingHandler(testFolder);
await handler.StartRecordingAsync(testName, ctx.Response);
var recordingId = ctx.Response.Headers["x-recording-id"].ToString();
var session = handler.RecordingSessions[recordingId];
session.Session.Entries.Add(testEntry);
handler.StopRecording(recordingId);
// now load it, did we avoid mangling it?
var sessionFromDisk = TestHelpers.LoadRecordSession(Path.Combine(testFolder, testName));
var targetEntry = sessionFromDisk.Session.Entries[0];
var content = Encoding.UTF8.GetString(targetEntry.Response.Body);
Assert.Equal(sampleExpected, content);
}
[Fact]
public void EnsureJsonEscaping()
{
var shouldNotExist = new string[] {
"\\u0026", "\\u002B"
};
var body = "{\"tags\":{\"hidden-link:/app-insights-resource-id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/Lwm_Rg/providers/microsoft.insights/components/FunctionApp1Lwm\"}"
+ ",\"properties\":{\"WEBSITE_CONTENTAZUREFILECONNECTIONSTRING\":\"DefaultEndpointsProtocol=https;AccountName=anaccountname!;AccountKey=aBase64&String+Fake==;EndpointSuffix=core.windows.net\"}}";
var session = new RecordSession();
session.Entries.Add(new RecordEntry()
{
Response = new RequestOrResponse()
{
Headers = new SortedDictionary<string, string[]>()
{
{
"Content-Type", new string[] { "application/json" }
}
},
Body = Encoding.UTF8.GetBytes(body),
}
});
var tmpDir = Path.GetTempPath();
var recordSession = Path.Combine(tmpDir, $"{Guid.NewGuid()}.json");
using var stream = System.IO.File.Create(recordSession);
var options = new JsonWriterOptions { Indented = true, Encoder = RecordEntry.WriterOptions.Encoder };
var writer = new Utf8JsonWriter(stream, options);
session.Serialize(writer);
writer.Flush();
stream.Close();
var text = File.ReadAllText(recordSession);
foreach(var unicodeChar in shouldNotExist)
{
Assert.DoesNotContain(unicodeChar, text);
}
}
[Theory]
[InlineData("{\"json\":\"value\"}", "application/json")]
[InlineData("{\"json\":\"\\\"value\\\"\"}", "application/json")]
[InlineData("{\"json\":{\"json\":\"value\"}}", "application/json")]
[InlineData("[\"json\", \"value\"]", "application/json")]
[InlineData("{\"json\": 1.00000000000000345345445}", "application/json")]
public void BodyNormalizationWorksWhenMatching(string body, string contentType)
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
var session = new RecordSession();
session.Variables["a"] = "value a";
session.Variables["b"] = "value b";
RecordEntry recordEntry = new RecordEntry();
recordEntry.Request.Headers.Add("Content-Type", new[] { contentType });
recordEntry.Request.Headers.Add("Other-Header", new[] { "multi", "value" });
recordEntry.Request.Body = bodyBytes;
recordEntry.RequestUri = "http://localhost/";
recordEntry.RequestMethod = RequestMethod.Delete;
recordEntry.Response.Headers.Add("Content-Type", new[] { contentType });
recordEntry.Response.Headers.Add("Other-Response-Header", new[] { "multi", "value" });
recordEntry.Response.Body = bodyBytes;
recordEntry.StatusCode = 202;
session.Entries.Add(recordEntry);
var arrayBufferWriter = new ArrayBufferWriter<byte>();
using var jsonWriter = new Utf8JsonWriter(arrayBufferWriter, new JsonWriterOptions()
{
Indented = true
});
session.Serialize(jsonWriter);
jsonWriter.Flush();
var document = JsonDocument.Parse(arrayBufferWriter.WrittenMemory);
var deserializedSession = RecordSession.Deserialize(document.RootElement);
var matcher = new RecordMatcher();
Assert.NotNull(deserializedSession.Lookup(recordEntry, matcher, new[] { new RecordedTestSanitizer() }));
}
[Theory]
[InlineData("<body>data</body>", "text/xml")]
[InlineData("{\"json\":\"value\"}", "application/json")]
[InlineData("{\"json\":\"value\"}", "text/json")]
[InlineData("{\"json\":\"value\"}", "application/json+param=val")]
[InlineData("missing", null)]
public void BodyNormalizationRespectsContentType(string body, string contentType)
{
byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
var session = new RecordSession();
RecordEntry recordEntry = new RecordEntry();
if (contentType != null)
{
recordEntry.Request.Headers.Add("Content-Type", new[] { contentType });
}
recordEntry.Request.Body = bodyBytes;
recordEntry.RequestUri = "http://localhost/";
recordEntry.RequestMethod = RequestMethod.Delete;
RecordEntry.NormalizeJsonBody(recordEntry.Request);
if (contentType?.Contains("json") == true)
{
Assert.NotSame(bodyBytes, recordEntry.Request.Body);
}
else
{
Assert.Same(bodyBytes, recordEntry.Request.Body);
}
}
[Fact]
public void RecordMatcherThrowsExceptionsWithDetails()
{
var matcher = new RecordMatcher();
var requestEntry = new RecordEntry()
{
RequestUri = "http://localhost/",
RequestMethod = RequestMethod.Head,
Request =
{
Headers =
{
{"Content-Length", new[] {"41"}},
{"Some-Header", new[] {"Random value"}},
{"Some-Other-Header", new[] {"V"}}
},
Body = Encoding.UTF8.GetBytes("This is request body, it's nice and long.")
}
};
RecordEntry[] entries = new[]
{
new RecordEntry()
{
RequestUri = "http://remote-host",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "Content-Length", new[] { "41"}},
{ "Some-Header", new[] { "Non-Random value"}},
{ "Extra-Header", new[] { "Extra-Value" }}
},
Body = Encoding.UTF8.GetBytes("This is request body, it's nice and long but it also doesn't match.")
}
}
};
TestRecordingMismatchException exception = Assert.Throws<TestRecordingMismatchException>(() => matcher.FindMatch(requestEntry, entries));
Assert.Equal(
"Unable to find a record for the request HEAD http://localhost/" + Environment.NewLine +
"Method doesn't match, request <HEAD> record <PUT>" + Environment.NewLine +
"Uri doesn't match:" + Environment.NewLine +
" request <http://localhost/>" + Environment.NewLine +
" record <http://remote-host>" + Environment.NewLine +
"Header differences:" + Environment.NewLine +
" <Some-Header> values differ, request <Random value>, record <Non-Random value>" + Environment.NewLine +
" <Some-Other-Header> is absent in record, value <V>" + Environment.NewLine +
" <Extra-Header> is absent in request, value <Extra-Value>" + Environment.NewLine +
"Body differences:" + Environment.NewLine +
"Request and record bodies do not match at index 40:" + Environment.NewLine +
" request: \"e and long.\"" + Environment.NewLine +
" record: \"e and long but it also doesn't\"" + Environment.NewLine,
exception.Message);
}
[Fact]
public void RecordMatcherIgnoresValuesOfIgnoredHeaders()
{
var matcher = new RecordMatcher();
var mockRequest = new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "Request-Id", new[] { "Non-Random value"}},
{ "Date", new[] { "Fri, 05 Nov 2020 02:42:26 GMT"} },
{ "x-ms-date", new[] { "Fri, 05 Nov 2020 02:42:26 GMT"} },
{ "x-ms-client-request-id", new[] {"non random request id"} },
{ "x-ms-client-id", new[] {"non random client id"} },
{ "User-Agent", new[] {"non random sdk"} },
{ "traceparent", new[] { "non random traceparent" } }
}
}
};
RecordEntry[] entries = new[]
{
new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "Request-Id", new[] { "Some Random value"}},
{ "Date", new[] { "Fri, 06 Nov 2020 02:42:26 GMT"} },
{ "x-ms-date", new[] { "Fri, 06 Nov 2020 02:42:26 GMT"} },
{ "x-ms-client-request-id", new[] {"some random request id"} },
{ "x-ms-client-id", new[] {"some random client id"} },
{ "User-Agent", new[] {"some random sdk"} },
{ "traceparent", new[] {"some random traceparent"} }
}
}
}
};
Assert.NotNull(matcher.FindMatch(mockRequest, entries));
}
[Fact]
public void RecordMatcherIgnoresLegacyExcludedHeaders()
{
var matcher = new RecordMatcher
{
ExcludeHeaders = { "some header", "another" }
};
var mockRequest = new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "some header", new[] { "Non-Random value"}},
}
}
};
RecordEntry[] entries = new[]
{
new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "another", new[] { "Some Random value"}},
}
}
}
};
Assert.NotNull(matcher.FindMatch(mockRequest, entries));
}
[Fact(Skip = "Not yet implemented")]
public void RecordMatcheRequiresPresenceOfIgnoredHeaders()
{
var matcher = new RecordMatcher();
var mockRequest = new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
// Request-Id and TraceParent are ignored until we can
// re-record all old tests.
Headers =
{
{ "Request-Id", new[] { "Some Random value"}},
{ "Date", new[] { "Fri, 06 Nov 2020 02:42:26 GMT"} },
{ "x-ms-date", new[] { "Fri, 06 Nov 2020 02:42:26 GMT"} },
}
}
};
RecordEntry[] entries = new[]
{
new RecordEntry()
{
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
Request =
{
Headers =
{
{ "x-ms-client-request-id", new[] {"some random request id"} },
{ "User-Agent", new[] {"some random sdk"} },
{ "traceparent", new[] {"some random traceparent"} }
}
}
}
};
TestRecordingMismatchException exception = Assert.Throws<TestRecordingMismatchException>(() => matcher.FindMatch(mockRequest, entries));
Assert.Equal(
"Unable to find a record for the request PUT http://localhost" + Environment.NewLine +
"Header differences:" + Environment.NewLine +
" <Date> is absent in record, value <Fri, 06 Nov 2020 02:42:26 GMT>" + Environment.NewLine +
" <x-ms-date> is absent in record, value <Fri, 06 Nov 2020 02:42:26 GMT>" + Environment.NewLine +
" <User-Agent> is absent in request, value <some random sdk>" + Environment.NewLine +
" <x-ms-client-request-id> is absent in request, value <some random request id>" + Environment.NewLine +
"Body differences:" + Environment.NewLine,
exception.Message);
}
[Theory]
[InlineData("http://localhost?VolatileParam1=Value1¶m=paramVal", "http://localhost?VolatileParam1=Value2¶m=paramVal", true, true)]
[InlineData("http://localhost?param=paramVal&VolatileParam1=Value1", "http://localhost?param=paramVal&VolatileParam1=Value2", true, true)]
[InlineData("http://localhost?param=paramVal&VolatileParam1=Value1&VolatileParam2=Value2", "http://localhost?param=paramVal&VolatileParam1=Value3&VolatileParam2=Value3", true, true)]
// order should still be respected
[InlineData("http://localhost?param=paramVal&VolatileParam2=Value2&VolatileParam1=Value1", "http://localhost?param=paramVal&VolatileParam1=Value3&VolatileParam2=Value3", true, false)]
// presence of volatile param is still required
[InlineData("http://localhost?param=paramVal&VolatileParam1=Value1&VolatileParam2=Value2", "http://localhost?param=paramVal&VolatileParam1=Value3", true, false)]
// non-volatile param values should be respected
[InlineData("http://localhost?VolatileParam1=Value1¶m=paramVal", "http://localhost?VolatileParam1=Value2¶m=paramVal2", true, false)]
// regression test cases
[InlineData("http://localhost?VolatileParam1=Value¶m=paramVal", "http://localhost?param=paramVal2&VolatileParam1=Value", false, false)]
[InlineData("http://localhost?VolatileParam1=Value1¶m=paramVal", "http://localhost?VolatileParam1=Value2¶m=paramVal", false, false)]
[InlineData("http://localhost?param=paramVal&VolatileParam1=Value1", "http://localhost?param=paramVal&VolatileParam1=Value2", false, false)]
[InlineData("http://localhost?VolatileParam1=Value1¶m=paramVal", "http://localhost?VolatileParam1=Value2¶m=paramVal2", false, false)]
public void RecordMatcherRespectsIgnoredQueryParameters(string requestUri, string entryUri, bool includeVolatile, bool shouldMatch)
{
var matcher = new RecordMatcher();
if (includeVolatile)
{
matcher.IgnoredQueryParameters.Add("VolatileParam1");
matcher.IgnoredQueryParameters.Add("VolatileParam2");
}
var mockRequest = new RecordEntry()
{
RequestUri = requestUri,
RequestMethod = RequestMethod.Put,
};
RecordEntry[] entries = new[]
{
new RecordEntry()
{
RequestUri = entryUri,
RequestMethod = RequestMethod.Put
}
};
if (shouldMatch)
{
Assert.NotNull(matcher.FindMatch(mockRequest, entries));
}
else
{
Assert.Throws<TestRecordingMismatchException>(() => matcher.FindMatch(mockRequest, entries));
}
}
[Fact]
public void RecordMatcherThrowsExceptionsWhenNoRecordsLeft()
{
var matcher = new RecordMatcher();
var mockRequest = new RecordEntry()
{
RequestUri = "http://localhost/",
RequestMethod = RequestMethod.Head
};
RecordEntry[] entries = { };
TestRecordingMismatchException exception = Assert.Throws<TestRecordingMismatchException>(() => matcher.FindMatch(mockRequest, entries));
Assert.Equal(
"Unable to find a record for the request HEAD http://localhost/" + Environment.NewLine +
"No records to match." + Environment.NewLine,
exception.Message);
}
[Fact]
public void RecordingSessionSanitizeSanitizesVariables()
{
var sanitizer = new TestSanitizer();
var session = new RecordSession();
session.Variables["A"] = "secret";
session.Variables["B"] = "Totally not a secret";
session.Sanitize(sanitizer);
Assert.Equal("SANITIZED", session.Variables["A"]);
Assert.Equal("Totally not a SANITIZED", session.Variables["B"]);
}
[Theory]
[InlineData("*", "invalid json", "invalid json")]
[InlineData("..secret",
"[{\"secret\":\"I should be sanitized\"},{\"secret\":\"I should be sanitized\"}]",
"[{\"secret\":\"Sanitized\"},{\"secret\":\"Sanitized\"}]")]
[InlineData("$..secret",
"{\"secret\":\"I should be sanitized\",\"level\":{\"key\":\"value\",\"secret\":\"I should be sanitized\"}}",
"{\"secret\":\"Sanitized\",\"level\":{\"key\":\"value\",\"secret\":\"Sanitized\"}}")]
public void RecordingSessionSanitizeTextBody(string jsonPath, string body, string expected)
{
var sanitizer = new RecordedTestSanitizer();
sanitizer.JsonPathSanitizers.Add(jsonPath);
string response = sanitizer.SanitizeTextBody(default, body);
Assert.Equal(expected, response);
}
[Fact]
public void RecordingSessionSanitizeTextBodyMultipleValues()
{
var sanitizer = new RecordedTestSanitizer();
sanitizer.JsonPathSanitizers.Add("$..secret");
sanitizer.JsonPathSanitizers.Add("$..topSecret");
var body = "{\"secret\":\"I should be sanitized\",\"key\":\"value\",\"topSecret\":\"I should be sanitized\"}";
var expected = "{\"secret\":\"Sanitized\",\"key\":\"value\",\"topSecret\":\"Sanitized\"}";
string response = sanitizer.SanitizeTextBody(default, body);
Assert.Equal(expected, response);
}
[Theory]
[InlineData("Content-Type")]
[InlineData("Accept")]
[InlineData("Random-Header")]
public void SpecialHeadersNormalizedForMatching(string name)
{
// Use HttpClientTransport as it does header normalization
var originalRequest = new HttpClientTransport().CreateRequest();
originalRequest.Method = RequestMethod.Get;
originalRequest.Uri.Reset(new Uri("http://localhost"));
originalRequest.Headers.Add(name, "application/json;odata=nometadata");
originalRequest.Headers.Add("Date", "This should be ignored");
var playbackRequest = new MockTransport().CreateRequest();
playbackRequest.Method = RequestMethod.Get;
playbackRequest.Uri.Reset(new Uri("http://localhost"));
playbackRequest.Headers.Add(name, "application/json;odata=nometadata");
playbackRequest.Headers.Add("Date", "It doesn't match");
var matcher = new RecordMatcher();
var requestEntry = RecordTransport.CreateEntry(originalRequest, null);
var entry = RecordTransport.CreateEntry(playbackRequest, new MockResponse(200));
Assert.NotNull(matcher.FindMatch(requestEntry, new[] { entry }));
}
[Theory]
[InlineData("Content-Type")]
[InlineData("Accept")]
[InlineData("Random-Header")]
public void SpecialHeadersNormalizedForMatchingMultiValue(string name)
{
// Use HttpClientTransport as it does header normalization
var originalRequest = new HttpClientTransport().CreateRequest();
originalRequest.Method = RequestMethod.Get;
originalRequest.Uri.Reset(new Uri("http://localhost"));
originalRequest.Headers.Add(name, "application/json, text/json");
originalRequest.Headers.Add("Date", "This should be ignored");
var playbackRequest = new MockTransport().CreateRequest();
playbackRequest.Method = RequestMethod.Get;
playbackRequest.Uri.Reset(new Uri("http://localhost"));
playbackRequest.Headers.Add(name, "application/json, text/json");
playbackRequest.Headers.Add("Date", "It doesn't match");
var matcher = new RecordMatcher();
var requestEntry = RecordTransport.CreateEntry(originalRequest, null);
var entry = RecordTransport.CreateEntry(playbackRequest, new MockResponse(200));
Assert.NotNull(matcher.FindMatch(requestEntry, new[] { entry }));
}
[Fact]
public void ContentLengthNotChangedOnHeadRequestWithEmptyBody()
{
ContentLengthUpdatedCorrectlyOnEmptyBody(isHeadRequest: true);
}
[Fact]
public void ContentLengthResetToZeroOnGetRequestWithEmptyBody()
{
ContentLengthUpdatedCorrectlyOnEmptyBody(isHeadRequest: false);
}
private void ContentLengthUpdatedCorrectlyOnEmptyBody(bool isHeadRequest)
{
var sanitizer = new RecordedTestSanitizer();
var entry = new RecordEntry()
{
RequestUri = "http://localhost/",
RequestMethod = isHeadRequest ? RequestMethod.Head : RequestMethod.Get,
Response =
{
Headers =
{
{"Content-Length", new[] {"41"}},
{"Some-Header", new[] {"Random value"}},
{"Some-Other-Header", new[] {"V"}}
},
Body = new byte[0]
}
};
sanitizer.Sanitize(entry);
if (isHeadRequest)
{
Assert.Equal(new[] { "41" }, entry.Response.Headers["Content-Length"]);
}
else
{
Assert.Equal(new[] { "0" }, entry.Response.Headers["Content-Length"]);
}
}
private class TestSanitizer : RecordedTestSanitizer
{
public override string SanitizeVariable(string variableName, string environmentVariableValue)
{
return environmentVariableValue.Replace("secret", "SANITIZED");
}
}
}
}