Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more tests for Proxy with Authorization #555

Merged
merged 5 commits into from
Dec 16, 2020
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
32 changes: 7 additions & 25 deletions examples/WireMock.Net.Console.Proxy.NETCoreApp2/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Logging;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
Expand All @@ -14,9 +15,6 @@ class Program
{
static void Main(string[] args)
{
RunTestDifferentPort().Wait(20000); // prints "1"
RunTestDifferentPort().Wait(20000); // prints "1"

var server = WireMockServer.Start(new WireMockServerSettings
{
Urls = new[] { "http://localhost:9091", "https://localhost:9443" },
Expand All @@ -29,34 +27,18 @@ static void Main(string[] args)
SaveMapping = true,
SaveMappingToFile = false,
ExcludedHeaders = new[] { "dnt", "Content-Length" }
}
},
Logger= new WireMockConsoleLogger()
});

server.LogEntriesChanged += (sender, eventRecordArgs) =>
{
System.Console.WriteLine(JsonConvert.SerializeObject(eventRecordArgs.NewItems, Formatting.Indented));
};
//server.LogEntriesChanged += (sender, eventRecordArgs) =>
//{
// System.Console.WriteLine(JsonConvert.SerializeObject(eventRecordArgs.NewItems, Formatting.Indented));
//};

System.Console.WriteLine("Press any key to stop the server");
System.Console.ReadKey();
server.Stop();
}

private static async Task RunTestDifferentPort()
{
var server = WireMockServer.Start();

server.Given(Request.Create().WithPath("/").UsingGet())
.RespondWith(Response.Create().WithStatusCode(200).WithBody("Hello"));

Thread.Sleep(1000);

var response = await new HttpClient().GetAsync(server.Urls[0]);
response.EnsureSuccessStatusCode();

System.Console.WriteLine("RunTestDifferentPort - server.LogEntries.Count() = " + server.LogEntries.Count());

server.Stop();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFrameworks>netcoreapp2.1;netcoreapp3.1;net5.0</TargetFrameworks>
<ApplicationIcon>../../WireMock.Net-Logo.ico</ApplicationIcon>
</PropertyGroup>

Expand Down
10 changes: 10 additions & 0 deletions src/WireMock.Net/RequestBuilders/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ private Request(IList<IRequestMatcher> requestMatchers) : base(requestMatchers)
return _requestMatchers.OfType<T>().FirstOrDefault();
}

/// <summary>
/// Gets the request message matcher.
/// </summary>
/// <typeparam name="T">Type of IRequestMatcher</typeparam>
/// <returns>A RequestMatcher</returns>
public T GetRequestMessageMatcher<T>(Func<T, bool> func) where T : IRequestMatcher
{
return _requestMatchers.OfType<T>().FirstOrDefault(func);
}

/// <inheritdoc cref="IClientIPRequestBuilder.WithClientIP(IStringMatcher[])"/>
public IRequestBuilder WithClientIP(params IStringMatcher[] matchers)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using FluentAssertions;
using Moq;
using System.Threading.Tasks;
using System.Threading.Tasks;
using FluentAssertions;
using WireMock.Models;
using WireMock.ResponseBuilders;
using WireMock.Settings;
Expand Down
57 changes: 52 additions & 5 deletions test/WireMock.Net.Tests/WireMockServer.Proxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Util;
using Xunit;

namespace WireMock.Net.Tests
Expand Down Expand Up @@ -75,8 +76,8 @@ public async Task WireMockServer_Proxy_Should_log_proxied_requests()
await new HttpClient(httpClientHandler).SendAsync(requestMessage);

// Assert
Check.That(server.Mappings).HasSize(2);
Check.That(server.LogEntries).HasSize(1);
server.Mappings.Should().HaveCount(2);
server.LogEntries.Should().HaveCount(1);
}

[Fact]
Expand Down Expand Up @@ -148,10 +149,56 @@ public async Task WireMockServer_Proxy_Should_preserve_content_header_in_proxied

// check that new proxied mapping is added
Check.That(server.Mappings).HasSize(2);
}

[Fact]
public async Task WireMockServer_Proxy_Should_preserve_Authorization_header_in_proxied_request()
{
// Assign
string path = $"/prx_{Guid.NewGuid()}";
var serverForProxyForwarding = WireMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithCallback(x => new ResponseMessage
{
BodyData = new BodyData
{
BodyAsString = x.Headers["Authorization"].ToString(),
DetectedBodyType = Types.BodyType.String
}
}));

var settings = new WireMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false
}
};
var server = WireMockServer.Start(settings);

// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent", Encoding.ASCII)
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("BASIC", "test-A");
var result = await new HttpClient().SendAsync(requestMessage);

// Assert
(await result.Content.ReadAsStringAsync()).Should().Be("BASIC test-A");

var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
var authorizationHeader = receivedRequest.Headers["Authorization"].ToString().Should().Be("BASIC test-A");

//var newMapping = _server.Mappings.First(m => m.Guid != guid);
//var matcher = ((Request)newMapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().FirstOrDefault(m => m.Name == "bbb");
//Check.That(matcher).IsNotNull();
server.Mappings.Should().HaveCount(2);
var authorizationRequestMessageHeaderMatcher = ((Request)server.Mappings.Single(m => !m.IsAdminInterface).RequestMatcher)
.GetRequestMessageMatcher<RequestMessageHeaderMatcher>(x => x.Matchers.Any(m => m.GetPatterns().Contains("BASIC test-A")));
authorizationRequestMessageHeaderMatcher.Should().NotBeNull();
}

[Fact]
Expand Down