Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class ConfigurationLiveTests : RecordedTestBase<AppConfigurationTestEnvir
public ConfigurationLiveTests(bool isAsync) : base(isAsync)
{
Sanitizer = new ConfigurationRecordedTestSanitizer();
Matcher = new ConfigurationRecordMatcher(Sanitizer);
Matcher = new ConfigurationRecordMatcher();
}

private string GenerateKeyId(string prefix = null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class ConfigurationRecordMatcher : RecordMatcher
"etag"
};

public ConfigurationRecordMatcher(RecordedTestSanitizer sanitizer) : base(sanitizer)
public ConfigurationRecordMatcher()
{
VolatileResponseHeaders.Add("Sync-Token");
}
Expand Down
1,576 changes: 809 additions & 767 deletions sdk/core/Azure.Core/Azure.Core.All.sln

Large diffs are not rendered by default.

59 changes: 36 additions & 23 deletions sdk/core/Azure.Core/tests/RecordSessionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,23 @@ public void CanRoundtripSessionRecord(string body, string contentType)
[Test]
public void RecordMatcherThrowsExceptionsWithDetails()
{
var matcher = new RecordMatcher(new RecordedTestSanitizer());
var matcher = new RecordMatcher();

MockRequest mockRequest = new MockRequest
var requestEntry = new RecordEntry()
{
Method = RequestMethod.Head
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.")
}
};
mockRequest.Uri.Reset(new Uri("http://localhost"));
mockRequest.Headers.Add("Some-Header", "Random value");
mockRequest.Headers.Add("Some-Other-Header", "V");

RecordEntry[] entries = new[]
{
Expand All @@ -99,14 +107,16 @@ public void RecordMatcherThrowsExceptionsWithDetails()
{
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.")
}
}
};

InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => matcher.FindMatch(mockRequest, entries));
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => matcher.FindMatch(requestEntry, entries));
Assert.AreEqual(
"Unable to find a record for the request HEAD http://localhost/" + Environment.NewLine +
"Method doesn't match, request <HEAD> record <PUT>" + Environment.NewLine +
Expand All @@ -116,20 +126,24 @@ public void RecordMatcherThrowsExceptionsWithDetails()
"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,
" <Extra-Header> is absent in request, value <Extra-Value>" + Environment.NewLine +
"Body differences:" + Environment.NewLine +
"Request and response 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);
}

[Test]
public void RecordMatcherIgnoresIgnoredHeaders()
{
var matcher = new RecordMatcher(new RecordedTestSanitizer());
var matcher = new RecordMatcher();

MockRequest mockRequest = new MockRequest
var mockRequest = new RecordEntry()
{
Method = RequestMethod.Put
RequestUri = "http://localhost",
RequestMethod = RequestMethod.Put,
};
mockRequest.Uri.Reset(new Uri("http://localhost"));

RecordEntry[] entries = new[]
{
Expand All @@ -153,15 +167,13 @@ public void RecordMatcherIgnoresIgnoredHeaders()
[Test]
public void RecordMatcherThrowsExceptionsWhenNoRecordsLeft()
{
var matcher = new RecordMatcher(new RecordedTestSanitizer());
var matcher = new RecordMatcher();

MockRequest mockRequest = new MockRequest
var mockRequest = new RecordEntry()
{
Method = RequestMethod.Head
RequestUri = "http://localhost/",
RequestMethod = RequestMethod.Head
};
mockRequest.Uri.Reset(new Uri("http://localhost"));
mockRequest.Headers.Add("Some-Header", "Random value");
mockRequest.Headers.Add("Some-Other-Header", "V");

RecordEntry[] entries = { };

Expand Down Expand Up @@ -191,7 +203,7 @@ public void SavingRecordingSanitizesValues()
{
var tempFile = Path.GetTempFileName();
var sanitizer = new TestSanitizer();
TestRecording recording = new TestRecording(RecordedTestMode.Record, tempFile, sanitizer, new RecordMatcher(sanitizer));
TestRecording recording = new TestRecording(RecordedTestMode.Record, tempFile, sanitizer, new RecordMatcher());

recording.SetVariable("A", "secret");
recording.Dispose(true);
Expand All @@ -218,12 +230,13 @@ public void SpecialHeadersNormalizedForMatching(string name)
playbackRequest.Method = RequestMethod.Get;
playbackRequest.Uri.Reset(new Uri("http://localhost"));
playbackRequest.Headers.Add(name, "application/json;odata=nometadata");
originalRequest.Headers.Add("Date", "It doesn't match");
playbackRequest.Headers.Add("Date", "It doesn't match");

var matcher = new RecordMatcher(new RecordedTestSanitizer());
var matcher = new RecordMatcher();
var requestEntry = RecordTransport.CreateEntry(originalRequest, null);
var entry = RecordTransport.CreateEntry(originalRequest, new MockResponse(200));

Assert.NotNull(matcher.FindMatch(playbackRequest, new[] { entry }));
Assert.NotNull(matcher.FindMatch(requestEntry, new[] { entry }));
}

private class TestSanitizer : RecordedTestSanitizer
Expand Down
10 changes: 6 additions & 4 deletions sdk/core/Azure.Core/tests/TestFramework/PlaybackTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Azure.Core.Pipeline;

namespace Azure.Core.Testing
{
Expand All @@ -15,13 +14,16 @@ public class PlaybackTransport : MockTransport

private readonly RecordMatcher _matcher;

private readonly RecordedTestSanitizer _sanitizer;

private readonly Random _random;

public PlaybackTransport(RecordSession session, RecordMatcher matcher, Random random)
public PlaybackTransport(RecordSession session, RecordMatcher matcher, RecordedTestSanitizer sanitizer, Random random)
{
_session = session;
_matcher = matcher;
_random = random;
_sanitizer = sanitizer;
}

public override void Process(HttpMessage message)
Expand All @@ -39,7 +41,7 @@ public override void Process(HttpMessage message)
}
}

message.Response = GetResponse(_session.Lookup(message.Request, _matcher));
message.Response = GetResponse(_session.Lookup(message.Request, _matcher, _sanitizer));
}

public override async ValueTask ProcessAsync(HttpMessage message)
Expand All @@ -57,7 +59,7 @@ public override async ValueTask ProcessAsync(HttpMessage message)
}
}

message.Response = GetResponse(_session.Lookup(message.Request, _matcher));
message.Response = GetResponse(_session.Lookup(message.Request, _matcher, _sanitizer));
}

public override Request CreateRequest()
Expand Down
101 changes: 72 additions & 29 deletions sdk/core/Azure.Core/tests/TestFramework/RecordMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,25 @@

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Azure.Core.Testing
{
public class RecordMatcher
{
private readonly RecordedTestSanitizer _sanitizer;

// Headers that are normalized by HttpClient
private HashSet<string> _normalizedHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Accept",
"Content-Type"
};

public RecordMatcher(RecordedTestSanitizer sanitizer)
private bool _compareBodies;

public RecordMatcher(bool compareBodies = true)
{
_sanitizer = sanitizer;
_compareBodies = compareBodies;
}

public HashSet<string> ExcludeHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
Expand Down Expand Up @@ -59,28 +58,16 @@ public RecordMatcher(RecordedTestSanitizer sanitizer)
"x-ms-correlation-request-id"
};

public virtual RecordEntry FindMatch(Request request, IList<RecordEntry> entries)
public virtual RecordEntry FindMatch(RecordEntry request, IList<RecordEntry> entries)
{
SortedDictionary<string, string[]> headers = new SortedDictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);

foreach (HttpHeader header in request.Headers)
{
var gotHeader = request.Headers.TryGetValues(header.Name, out IEnumerable<string> values);
Debug.Assert(gotHeader);
headers[header.Name] = values.ToArray();
}

_sanitizer.SanitizeHeaders(headers);

string uri = _sanitizer.SanitizeUri(request.Uri.ToString());

int bestScore = int.MaxValue;
RecordEntry bestScoreEntry = null;

foreach (RecordEntry entry in entries)
{
int score = 0;

var uri = request.RequestUri;
var recordRequestUri = entry.RequestUri;
if (entry.IsTrack1Recording)
{
Expand All @@ -98,17 +85,19 @@ public virtual RecordEntry FindMatch(Request request, IList<RecordEntry> entries
score++;
}

if (entry.RequestMethod != request.Method)
if (entry.RequestMethod != request.RequestMethod)
{
score++;
}

//we only check Uri + RequestMethod for track1 record
if (entry.IsTrack1Recording)
{
score += CompareHeaderDictionaries(headers, entry.Request.Headers, ExcludeHeaders);
score += CompareHeaderDictionaries(request.Request.Headers, entry.Request.Headers, ExcludeHeaders);
}

score += CompareBodies(request.Request.Body, entry.Request.Body);

if (score == 0)
{
return entry;
Expand All @@ -121,7 +110,57 @@ public virtual RecordEntry FindMatch(Request request, IList<RecordEntry> entries
}
}

throw new InvalidOperationException(GenerateException(request.Method, uri, headers, bestScoreEntry));
throw new InvalidOperationException(GenerateException(request, bestScoreEntry));
}

private int CompareBodies(byte[] requestBody, byte[] responseBody, StringBuilder descriptionBuilder = null)
{
if (!_compareBodies)
{
return 0;
}

if (requestBody == null && responseBody == null)
{
return 0;
}

if (requestBody == null)
{
descriptionBuilder?.AppendLine("Request has body but response doesn't");
return 1;
}

if (responseBody == null)
{
descriptionBuilder?.AppendLine("Response has body but request doesn't");
return 1;
}

if (!requestBody.SequenceEqual(responseBody))
{
if (descriptionBuilder != null)
{
var minLength = Math.Min(requestBody.Length, responseBody.Length);
int i;
for (i = 0; i < minLength - 1; i++)
{
if (requestBody[i] != responseBody[i])
{
break;
}
}
descriptionBuilder.AppendLine($"Request and response bodies do not match at index {i}:");
var before = Math.Max(0, i - 10);
var afterRequest = Math.Min(i + 20, requestBody.Length);
var afterResponse = Math.Min(i + 20, responseBody.Length);
descriptionBuilder.AppendLine($" request: \"{Encoding.UTF8.GetString(requestBody, before, afterRequest - before)}\"");
descriptionBuilder.AppendLine($" record: \"{Encoding.UTF8.GetString(responseBody, before, afterResponse - before)}\"");
}
return 1;
}

return 0;
}

public virtual bool IsEquivalentRecord(RecordEntry entry, RecordEntry otherEntry) =>
Expand Down Expand Up @@ -159,32 +198,36 @@ protected virtual bool IsBodyEquivalent(RecordEntry record, RecordEntry otherRec
.SequenceEqual((otherRecord.Response.Body ?? Array.Empty<byte>()));
}

private string GenerateException(RequestMethod requestMethod, string uri, SortedDictionary<string, string[]> headers, RecordEntry bestScoreEntry)
private string GenerateException(RecordEntry request, RecordEntry bestScoreEntry)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine($"Unable to find a record for the request {requestMethod} {uri}");
builder.AppendLine($"Unable to find a record for the request {request.RequestMethod} {request.RequestUri}");

if (bestScoreEntry == null)
{
builder.AppendLine("No records to match.");
return builder.ToString();
}

if (requestMethod != bestScoreEntry.RequestMethod)
if (request.RequestMethod != bestScoreEntry.RequestMethod)
{
builder.AppendLine($"Method doesn't match, request <{requestMethod}> record <{bestScoreEntry.RequestMethod}>");
builder.AppendLine($"Method doesn't match, request <{request.RequestMethod}> record <{bestScoreEntry.RequestMethod}>");
}

if (!AreUrisSame(uri, bestScoreEntry.RequestUri))
if (!AreUrisSame(request.RequestUri, bestScoreEntry.RequestUri))
{
builder.AppendLine("Uri doesn't match:");
builder.AppendLine($" request <{uri}>");
builder.AppendLine($" request <{request.RequestUri}>");
builder.AppendLine($" record <{bestScoreEntry.RequestUri}>");
}

builder.AppendLine("Header differences:");

CompareHeaderDictionaries(headers, bestScoreEntry.Request.Headers, ExcludeHeaders, builder);
CompareHeaderDictionaries(request.Request.Headers, bestScoreEntry.Request.Headers, ExcludeHeaders, builder);

builder.AppendLine("Body differences:");

CompareBodies(request.Request.Body, bestScoreEntry.Request.Body, builder);

return builder.ToString();
}
Expand Down
7 changes: 5 additions & 2 deletions sdk/core/Azure.Core/tests/TestFramework/RecordSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,14 @@ public void Record(RecordEntry entry)
}
}

public RecordEntry Lookup(Request request, RecordMatcher matcher)
public RecordEntry Lookup(Request request, RecordMatcher matcher, RecordedTestSanitizer sanitizer)
{
var requestEntry = RecordTransport.CreateEntry(request, null);
sanitizer.Sanitize(requestEntry);

lock (Entries)
{
RecordEntry entry = matcher.FindMatch(request, Entries);
RecordEntry entry = matcher.FindMatch(requestEntry, Entries);
Entries.Remove(entry);
return entry;
}
Expand Down
Loading