Swagger support (#749)

* r

* fix

* sw

* x

* s

* .

* .

* .

* CreateTypeFromJObject

* .

* .

* f

* c

* .

* .

* .

* .

* .

* .

* ok

* ,

* .

* .

* .

* .

* n

* pact

* fix

* schema

* null

* fluent

* r

* -p

* .

* .

* refs

* .
This commit is contained in:
Stef Heyenrath
2022-05-13 22:01:46 +02:00
committed by GitHub
parent 0d8b3b1438
commit 5e301fd74b
45 changed files with 2371 additions and 1123 deletions

View File

@@ -12,277 +12,318 @@ using WireMock.Settings;
using Xunit;
using static System.Environment;
namespace WireMock.Net.Tests.FluentAssertions
namespace WireMock.Net.Tests.FluentAssertions;
public class WireMockAssertionsTests : IDisposable
{
public class WireMockAssertionsTests : IDisposable
private readonly WireMockServer _server;
private readonly HttpClient _httpClient;
private readonly int _portUsed;
public WireMockAssertionsTests()
{
private readonly WireMockServer _server;
private readonly HttpClient _httpClient;
private readonly int _portUsed;
_server = WireMockServer.Start();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithSuccess());
_portUsed = _server.Ports.First();
public WireMockAssertionsTests()
{
_server = WireMockServer.Start();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithSuccess());
_portUsed = _server.Ports.First();
_httpClient = new HttpClient { BaseAddress = new Uri(_server.Urls[0]) };
}
_httpClient = new HttpClient { BaseAddress = new Uri(_server.Urls[0]) };
}
[Fact]
public async Task HaveReceivedNoCalls_AtAbsoluteUrl_WhenACallWasNotMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("xxx").ConfigureAwait(false);
[Fact]
public async Task AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
_server.Should()
.HaveReceivedNoCalls()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
_server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
[Fact]
public async Task HaveReceived0Calls_AtAbsoluteUrl_WhenACallWasNotMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("xxx").ConfigureAwait(false);
[Fact]
public void AtAbsoluteUrl_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl("anyurl");
_server.Should()
.HaveReceived(0).Calls()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called at address matching the absolute url \"anyurl\", but no calls were made.");
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
[Fact]
public async Task AtAbsoluteUrl_Should_ThrowWhenNoCallsMatchingTheAbsoluteUrlWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
_server.Should()
.HaveReceived(1).Calls()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl("anyurl");
[Fact]
public async Task HaveReceived2Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called at address matching the absolute url \"anyurl\", but didn't find it among the calls to {{\"http://localhost:{_portUsed}/\"}}.");
}
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
[Fact]
public async Task WithHeader_WhenACallWasMadeWithExpectedHeader_Should_BeOK()
{
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer a");
await _httpClient.GetAsync("").ConfigureAwait(false);
_server.Should()
.HaveReceived(2).Calls()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
_server.Should()
.HaveReceivedACall()
.WithHeader("Authorization", "Bearer a");
}
[Fact]
public async Task HaveReceivedACall_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
[Fact]
public async Task WithHeader_WhenACallWasMadeWithExpectedHeaderAmongMultipleHeaderValues_Should_BeOK()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
_server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl($"http://localhost:{_portUsed}/anyurl");
}
_server.Should()
.HaveReceivedACall()
.WithHeader("Accept", new[] { "application/xml", "application/json" });
}
[Fact]
public void HaveReceivedACall_AtAbsoluteUrl_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl("anyurl");
[Fact]
public async Task WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderNameWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called at address matching the absolute url \"anyurl\", but no calls were made.");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Authorization", "value");
[Fact]
public async Task HaveReceivedACall_AtAbsoluteUrl_Should_ThrowWhenNoCallsMatchingTheAbsoluteUrlWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Contain("to contain key \"Authorization\".");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.AtAbsoluteUrl("anyurl");
[Fact]
public async Task WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderValuesWereMade()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called at address matching the absolute url \"anyurl\", but didn't find it among the calls to {{\"http://localhost:{_portUsed}/\"}}.");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Accept", "missing-value");
[Fact]
public async Task HaveReceivedACall_WithHeader_WhenACallWasMadeWithExpectedHeader_Should_BeOK()
{
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer a");
await _httpClient.GetAsync("").ConfigureAwait(false);
var sentHeaders = _server.LogEntries.SelectMany(x => x.RequestMessage.Headers)
.ToDictionary(x => x.Key, x => x.Value)["Accept"]
.Select(x => $"\"{x}\"")
.ToList();
_server.Should()
.HaveReceivedACall()
.WithHeader("Authorization", "Bearer a");
}
var sentHeaderString = "{" + string.Join(", ", sentHeaders) + "}";
[Fact]
public async Task HaveReceivedACall_WithHeader_WhenACallWasMadeWithExpectedHeaderAmongMultipleHeaderValues_Should_BeOK()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected header \"Accept\" from requests sent with value(s) {sentHeaderString} to contain \"missing-value\".{NewLine}");
}
_server.Should()
.HaveReceivedACall()
.WithHeader("Accept", new[] { "application/xml", "application/json" });
}
[Fact]
public async Task WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderWithMultipleValuesWereMade()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task HaveReceivedACall_WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderNameWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Accept", new[] { "missing-value1", "missing-value2" });
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Authorization", "value");
const string missingValue1Message =
"Expected header \"Accept\" from requests sent with value(s) {\"application/xml\", \"application/json\"} to contain \"missing-value1\".";
const string missingValue2Message =
"Expected header \"Accept\" from requests sent with value(s) {\"application/xml\", \"application/json\"} to contain \"missing-value2\".";
act.Should().Throw<Exception>()
.And.Message.Should()
.Contain("to contain key \"Authorization\".");
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be($"{string.Join(NewLine, missingValue1Message, missingValue2Message)}{NewLine}");
}
[Fact]
public async Task HaveReceivedACall_WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderValuesWereMade()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task AtUrl_WhenACallWasMadeToUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Accept", "missing-value");
_server.Should()
.HaveReceivedACall()
.AtUrl($"http://localhost:{_portUsed}/anyurl");
}
var sentHeaders = _server.LogEntries.SelectMany(x => x.RequestMessage.Headers)
.ToDictionary(x => x.Key, x => x.Value)["Accept"]
.Select(x => $"\"{x}\"")
.ToList();
[Fact]
public void AtUrl_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.AtUrl("anyurl");
var sentHeaderString = "{" + string.Join(", ", sentHeaders) + "}";
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called at address matching the url \"anyurl\", but no calls were made.");
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected header \"Accept\" from requests sent with value(s) {sentHeaderString} to contain \"missing-value\".{NewLine}");
}
[Fact]
public async Task AtUrl_Should_ThrowWhenNoCallsMatchingTheUrlWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task HaveReceivedACall_WithHeader_Should_ThrowWhenNoCallsMatchingTheHeaderWithMultipleValuesWereMade()
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await _httpClient.GetAsync("").ConfigureAwait(false);
Action act = () => _server.Should()
.HaveReceivedACall()
.AtUrl("anyurl");
Action act = () => _server.Should()
.HaveReceivedACall()
.WithHeader("Accept", new[] { "missing-value1", "missing-value2" });
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called at address matching the url \"anyurl\", but didn't find it among the calls to {{\"http://localhost:{_portUsed}/\"}}.");
}
const string missingValue1Message =
"Expected header \"Accept\" from requests sent with value(s) {\"application/xml\", \"application/json\"} to contain \"missing-value1\".";
const string missingValue2Message =
"Expected header \"Accept\" from requests sent with value(s) {\"application/xml\", \"application/json\"} to contain \"missing-value2\".";
[Fact]
public async Task WithProxyUrl_WhenACallWasMadeWithProxyUrl_Should_BeOK()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
act.Should().Throw<Exception>()
.And.Message.Should()
.Be($"{string.Join(NewLine, missingValue1Message, missingValue2Message)}{NewLine}");
}
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task HaveReceivedACall_AtUrl_WhenACallWasMadeToUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl").ConfigureAwait(false);
_server.Should()
.HaveReceivedACall()
.WithProxyUrl($"http://localhost:9999");
}
_server.Should()
.HaveReceivedACall()
.AtUrl($"http://localhost:{_portUsed}/anyurl");
}
[Fact]
public void WithProxyUrl_Should_ThrowWhenNoCallsWereMade()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
[Fact]
public void HaveReceivedACall_AtUrl_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.AtUrl("anyurl");
Action act = () => _server.Should()
.HaveReceivedACall()
.WithProxyUrl("anyurl");
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called at address matching the url \"anyurl\", but no calls were made.");
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called with proxy url \"anyurl\", but no calls were made.");
}
[Fact]
public async Task HaveReceivedACall_AtUrl_Should_ThrowWhenNoCallsMatchingTheUrlWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task WithProxyUrl_Should_ThrowWhenNoCallsWithTheProxyUrlWereMade()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
Action act = () => _server.Should()
.HaveReceivedACall()
.AtUrl("anyurl");
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called at address matching the url \"anyurl\", but didn't find it among the calls to {{\"http://localhost:{_portUsed}/\"}}.");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.WithProxyUrl("anyurl");
[Fact]
public async Task HaveReceivedACall_WithProxyUrl_WhenACallWasMadeWithProxyUrl_Should_BeOK()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called with proxy url \"anyurl\", but didn't find it among the calls with {{\"http://localhost:9999\"}}.");
}
await _httpClient.GetAsync("").ConfigureAwait(false);
[Fact]
public async Task FromClientIP_whenACallWasMadeFromClientIP_Should_BeOK()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP;
_server.Should()
.HaveReceivedACall()
.WithProxyUrl($"http://localhost:9999");
}
_server.Should()
.HaveReceivedACall()
.FromClientIP(clientIP);
}
[Fact]
public void HaveReceivedACall_WithProxyUrl_Should_ThrowWhenNoCallsWereMade()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
[Fact]
public void FromClientIP_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.FromClientIP("different-ip");
Action act = () => _server.Should()
.HaveReceivedACall()
.WithProxyUrl("anyurl");
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called from client IP \"different-ip\", but no calls were made.");
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called with proxy url \"anyurl\", but no calls were made.");
}
[Fact]
public async Task FromClientIP_Should_ThrowWhenNoCallsFromClientIPWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP;
[Fact]
public async Task HaveReceivedACall_WithProxyUrl_Should_ThrowWhenNoCallsWithTheProxyUrlWereMade()
{
_server.ResetMappings();
_server.Given(Request.Create().UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(new ProxyAndRecordSettings { Url = "http://localhost:9999" }));
Action act = () => _server.Should()
.HaveReceivedACall()
.FromClientIP("different-ip");
await _httpClient.GetAsync("").ConfigureAwait(false);
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called from client IP \"different-ip\", but didn't find it among the calls from IP(s) {{\"{clientIP}\"}}.");
}
Action act = () => _server.Should()
.HaveReceivedACall()
.WithProxyUrl("anyurl");
public void Dispose()
{
_server?.Stop();
_server?.Dispose();
_httpClient?.Dispose();
}
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called with proxy url \"anyurl\", but didn't find it among the calls with {{\"http://localhost:9999\"}}.");
}
[Fact]
public async Task HaveReceivedACall_FromClientIP_whenACallWasMadeFromClientIP_Should_BeOK()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP;
_server.Should()
.HaveReceivedACall()
.FromClientIP(clientIP);
}
[Fact]
public void HaveReceivedACall_FromClientIP_Should_ThrowWhenNoCallsWereMade()
{
Action act = () => _server.Should()
.HaveReceivedACall()
.FromClientIP("different-ip");
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
"Expected _server to have been called from client IP \"different-ip\", but no calls were made.");
}
[Fact]
public async Task HaveReceivedACall_FromClientIP_Should_ThrowWhenNoCallsFromClientIPWereMade()
{
await _httpClient.GetAsync("").ConfigureAwait(false);
var clientIP = _server.LogEntries.Last().RequestMessage.ClientIP;
Action act = () => _server.Should()
.HaveReceivedACall()
.FromClientIP("different-ip");
act.Should().Throw<Exception>()
.And.Message.Should()
.Be(
$"Expected _server to have been called from client IP \"different-ip\", but didn't find it among the calls from IP(s) {{\"{clientIP}\"}}.");
}
public void Dispose()
{
_server?.Stop();
_server?.Dispose();
_httpClient?.Dispose();
}
}

View File

@@ -57,6 +57,7 @@ public class PactTests
.WithHeader("Accept", "application/json")
)
.WithTitle("A GET request to retrieve the something")
.WithGuid("23e2aedb-166c-467b-b9f6-9b0817cb1636")
.RespondWith(
Response.Create()
.WithStatusCode(HttpStatusCode.OK)
@@ -77,6 +78,7 @@ public class PactTests
.WithBody(new JsonMatcher("{ \"Id\" : \"1\", \"FirstName\" : \"Totally\" }"))
)
.WithTitle("A Post request to add the something")
.WithGuid("f3f8abe7-7d1e-4518-afa1-d295ce7dadfd")
.RespondWith(
Response.Create()
.WithStatusCode(HttpStatusCode.RedirectMethod)

View File

@@ -1,32 +1,32 @@
{
"Consumer": {
"Name": "Something API Consumer Get"
"consumer": {
"name": "Something API Consumer Get"
},
"Interactions": [
"interactions": [
{
"ProviderState": "A GET request to retrieve the something",
"Request": {
"Headers": {
"providerState": "A GET request to retrieve the something",
"request": {
"headers": {
"Accept": "application/json"
},
"Method": "GET",
"Path": "/tester",
"Query": "q1=test&q2=ok"
"method": "GET",
"path": "/tester",
"query": "q1=test&q2=ok"
},
"Response": {
"Body": {
"Id": "tester",
"FirstName": "Totally",
"LastName": "Awesome"
"response": {
"body": {
"id": "tester",
"firstName": "Totally",
"lastName": "Awesome"
},
"Headers": {
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"Status": 200
"status": 200
}
}
],
"Provider": {
"Name": "Something API"
"provider": {
"name": "Something API"
}
}

View File

@@ -1,50 +1,49 @@
{
"Consumer": {
"Name": "Something API Consumer Multiple"
"consumer": {
"name": "Something API Consumer Multiple"
},
"Interactions": [
"interactions": [
{
"ProviderState": "A Post request to add the something",
"Request": {
"Headers": {
"providerState": "A GET request to retrieve the something",
"request": {
"headers": {
"Accept": "application/json"
},
"Method": "POST",
"Path": "/add",
"Body": "{ \"Id\" : \"1\", \"FirstName\" : \"Totally\" }"
"method": "POST",
"path": "/tester",
"query": "q1=test&q2=ok"
},
"Response": {
"Body": {
"Id": "1",
"FirstName": "Totally"
"response": {
"body": {
"id": "tester",
"firstName": "Totally",
"lastName": "Awesome"
},
"Status": 303
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"status": 200
}
},
{
"ProviderState": "A GET request to retrieve the something",
"Request": {
"Headers": {
"providerState": "A Post request to add the something",
"request": {
"headers": {
"Accept": "application/json"
},
"Method": "POST",
"Path": "/tester",
"Query": "q1=test&q2=ok"
"method": "POST",
"path": "/add"
},
"Response": {
"Body": {
"Id": "tester",
"FirstName": "Totally",
"LastName": "Awesome"
"response": {
"body": {
"id": "1",
"firstName": "Totally"
},
"Headers": {
"Content-Type": "application/json; charset=utf-8"
},
"Status": 200
"status": 303
}
}
],
"Provider": {
"Name": "Something API"
"provider": {
"name": "Something API"
}
}

View File

@@ -1,115 +1,167 @@
using System;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Util
namespace WireMock.Net.Tests.Util;
public class JsonUtilsTests
{
public class JsonUtilsTests
[Fact]
public void JsonUtils_ParseJTokenToObject()
{
[Fact]
public void JsonUtils_ParseJTokenToObject()
// Assign
object value = "test";
// Act
string result = JsonUtils.ParseJTokenToObject<string>(value);
// Assert
Check.That(result).IsEqualTo(default(string));
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JToken()
{
// Assign
JToken instance = "Test";
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(instance);
// Assert
var queryable = new[] { instance }.AsQueryable().Select(line);
bool result = queryable.Any("it == \"Test\"");
Check.That(result).IsTrue();
Check.That(line).IsEqualTo("string(it)");
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JArray_Indexer()
{
// Assign
var instance = new JObject
{
// Assign
object value = "test";
{ "Items", new JArray(new JValue(4), new JValue(8)) }
};
// Act
string result = JsonUtils.ParseJTokenToObject<string>(value);
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(instance);
// Assert
Check.That(result).IsEqualTo(default(string));
}
// Assert 1
line.Should().Be("new ((new [] { long(Items[0]), long(Items[1])}) as Items)");
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JToken()
// Assert 2
var queryable = new[] { instance }.AsQueryable().Select(line);
bool result = queryable.Any("Items != null");
result.Should().BeTrue();
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JObject2()
{
// Assign
var instance = new JObject
{
// Assign
JToken j = "Test";
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(j);
// Assert
var queryable = new[] { j }.AsQueryable().Select(line);
bool result = queryable.Any("it == \"Test\"");
Check.That(result).IsTrue();
Check.That(line).IsEqualTo("string(it)");
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JArray_Indexer()
{
// Assign
var j = new JObject
{"U", new JValue(new Uri("http://localhost:80/abc?a=5"))},
{"N", new JValue((object?) null)},
{"G", new JValue(Guid.NewGuid())},
{"Flt", new JValue(10.0f)},
{"Dbl", new JValue(Math.PI)},
{"Check", new JValue(true)},
{
{ "Items", new JArray(new[] { new JValue(4), new JValue(8) }) }
};
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(j);
// Assert 1
line.Should().Be("new ((new [] { long(Items[0]), long(Items[1])}) as Items)");
// Assert 2
var queryable = new[] { j }.AsQueryable().Select(line);
bool result = queryable.Any("Items != null");
result.Should().BeTrue();
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_JObject2()
{
// Assign
var j = new JObject
{
{"U", new JValue(new Uri("http://localhost:80/abc?a=5"))},
{"N", new JValue((object) null)},
{"G", new JValue(Guid.NewGuid())},
{"Flt", new JValue(10.0f)},
{"Dbl", new JValue(Math.PI)},
{"Check", new JValue(true)},
"Child", new JObject
{
"Child", new JObject
{
{"ChildId", new JValue(4)},
{"ChildDateTime", new JValue(new DateTime(2018, 2, 17))},
{"TS", new JValue(TimeSpan.FromMilliseconds(999))}
}
},
{"I", new JValue(9)},
{"L", new JValue(long.MaxValue)},
{"Name", new JValue("Test")}
};
{"ChildId", new JValue(4)},
{"ChildDateTime", new JValue(new DateTime(2018, 2, 17))},
{"TS", new JValue(TimeSpan.FromMilliseconds(999))}
}
},
{"I", new JValue(9)},
{"L", new JValue(long.MaxValue)},
{"Name", new JValue("Test")}
};
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(j);
// Act
string line = JsonUtils.GenerateDynamicLinqStatement(instance);
// Assert 1
line.Should().Be("new (Uri(U) as U, null as N, Guid(G) as G, double(Flt) as Flt, double(Dbl) as Dbl, bool(Check) as Check, new (long(Child.ChildId) as ChildId, DateTime(Child.ChildDateTime) as ChildDateTime, TimeSpan(Child.TS) as TS) as Child, long(I) as I, long(L) as L, string(Name) as Name)");
// Assert 1
line.Should().Be("new (Uri(U) as U, null as N, Guid(G) as G, double(Flt) as Flt, double(Dbl) as Dbl, bool(Check) as Check, new (long(Child.ChildId) as ChildId, DateTime(Child.ChildDateTime) as ChildDateTime, TimeSpan(Child.TS) as TS) as Child, long(I) as I, long(L) as L, string(Name) as Name)");
// Assert 2
var queryable = new[] { j }.AsQueryable().Select(line);
bool result = queryable.Any("I > 1 && L > 1");
result.Should().BeTrue();
}
// Assert 2
var queryable = new[] { instance }.AsQueryable().Select(line);
bool result = queryable.Any("I > 1 && L > 1");
result.Should().BeTrue();
}
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_Throws()
[Fact]
public void JsonUtils_GenerateDynamicLinqStatement_Throws()
{
// Assign
var instance = new JObject
{
// Assign
var j = new JObject
{
{ "B", new JValue(new byte[] {48, 49}) }
};
{ "B", new JValue(new byte[] {48, 49}) }
};
// Act and Assert
Check.ThatCode(() => JsonUtils.GenerateDynamicLinqStatement(j)).Throws<NotSupportedException>();
}
// Act and Assert
Check.ThatCode(() => JsonUtils.GenerateDynamicLinqStatement(instance)).Throws<NotSupportedException>();
}
[Fact]
public void JsonUtils_CreateTypeFromJObject()
{
// Assign
var instance = new JObject
{
{"U", new JValue(new Uri("http://localhost:80/abc?a=5"))},
{"N", new JValue((object?) null)},
{"G", new JValue(Guid.NewGuid())},
{"Flt", new JValue(10.0f)},
{"Dbl", new JValue(Math.PI)},
{"Check", new JValue(true)},
{
"Child", new JObject
{
{"ChildId", new JValue(4)},
{"ChildDateTime", new JValue(new DateTime(2018, 2, 17))},
{"ChildTimeSpan", new JValue(TimeSpan.FromMilliseconds(999))}
}
},
{"I", new JValue(9)},
{"L", new JValue(long.MaxValue)},
{"S", new JValue("Test")},
{"C", new JValue('c')}
};
// Act
var type = JsonUtils.CreateTypeFromJObject(instance);
// Assert
var setProperties = type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(pi => pi.GetMethod != null).Select(pi => $"{pi.GetMethod}")
.ToArray();
setProperties.Should().HaveCount(11);
setProperties.Should().BeEquivalentTo(new[]
{
"System.String get_U()",
"System.Object get_N()",
"System.Guid get_G()",
"Single get_Flt()",
"Single get_Dbl()",
"Boolean get_Check()",
"Child get_Child()",
"Int64 get_I()",
"Int64 get_L()",
"System.String get_S()",
"System.String get_C()"
});
}
}

View File

@@ -0,0 +1,14 @@
using FluentAssertions;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Util;
public class SystemUtilsTests
{
[Fact]
public void Version()
{
SystemUtils.Version.Should().NotBeEmpty();
}
}

View File

@@ -83,28 +83,16 @@
<None Update="responsebody.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings.org\mapping1.json">
<None Update="__admin\mappings.org\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\00000002-ee28-4f29-ae63-1ac9b0802d86.json">
<None Update="__admin\mappings\*.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\00000002-ee28-4f29-ae63-1ac9b0802d87.json">
<None Update="__admin\mappings\*.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\351f0240-bba0-4bcb-93c6-1feba0fe8799.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\array.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\documentdb_root.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\MyXmlResponse.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\subdirectory\MyXmlResponse.xml">
<None Update="__admin\mappings\subdirectory\*.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

View File

@@ -81,7 +81,7 @@ namespace WireMock.Net.Tests
// Assert
server.Mappings.Should().NotBeNull();
server.Mappings.Should().HaveCount(25);
server.Mappings.Should().HaveCount(26);
server.Mappings.All(m => m.Priority == WireMockConstants.AdminPriority).Should().BeTrue();
}
@@ -100,9 +100,9 @@ namespace WireMock.Net.Tests
// Assert
server.Mappings.Should().NotBeNull();
server.Mappings.Should().HaveCount(26);
server.Mappings.Should().HaveCount(27);
server.Mappings.Count(m => m.Priority == WireMockConstants.AdminPriority).Should().Be(25);
server.Mappings.Count(m => m.Priority == WireMockConstants.AdminPriority).Should().Be(26);
server.Mappings.Count(m => m.Priority == WireMockConstants.ProxyPriority).Should().Be(1);
}