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

Fix ProtoBuf mapping.json #1236

Merged
merged 5 commits into from
Jan 26, 2025
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
6 changes: 4 additions & 2 deletions src/WireMock.Net.Abstractions/Server/IWireMockServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,16 @@ public interface IWireMockServer : IDisposable
/// This can be used if you have 1 or more <see cref="MappingModel"/> defined and want to register these in WireMock.Net directly instead of using the fluent syntax.
/// </summary>
/// <param name="mappings">The MappingModels</param>
/// <returns><see cref="IWireMockServer"/></returns>
IWireMockServer WithMapping(params MappingModel[] mappings);

/// <summary>
/// Register the mappings (via json string).
///
/// This can be used if you the mappings as json string defined and want to register these in WireMock.Net directly instead of using the fluent syntax.
/// This can be used if you've the mappings as json string defined and want to register these in WireMock.Net directly instead of using the fluent syntax.
/// </summary>
/// <param name="mappings">The mapping(s) as json string.</param>
/// <returns><see cref="IWireMockServer"/></returns>
IWireMockServer WithMapping(string mappings);

/// <summary>
Expand All @@ -238,5 +240,5 @@ public interface IWireMockServer : IDisposable
/// </summary>
/// <param name="converterType">The <see cref="MappingConverterType"/></param>
/// <returns>C# code</returns>
public string MappingsToCSharpCode(MappingConverterType converterType);
string MappingsToCSharpCode(MappingConverterType converterType);
}
11 changes: 10 additions & 1 deletion src/WireMock.Net.RestClient/IWireMockAdminApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,23 @@ public interface IWireMockAdminApi
Task<StatusModel> ReloadStaticMappingsAsync(CancellationToken cancellationToken = default);

/// <summary>
/// Get a mapping based on the guid
/// Get a mapping based on the guid.
/// </summary>
/// <param name="guid">The Guid</param>
/// <returns>MappingModel</returns>
/// <param name="cancellationToken">The optional cancellationToken.</param>
[Get("mappings/{guid}")]
Task<MappingModel> GetMappingAsync([Path] Guid guid, CancellationToken cancellationToken = default);

/// <summary>
/// Get a mapping based on the guid.
/// </summary>
/// <param name="guid">The Guid</param>
/// <returns>MappingModel</returns>
/// <param name="cancellationToken">The optional cancellationToken.</param>
[Get("mappings/{guid}")]
Task<MappingModel> GetMappingAsync([Path] string guid, CancellationToken cancellationToken = default);

/// <summary>
/// Get the C# code from a mapping based on the guid
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@
return stringMatcher.IsMatch(requestMessage.BodyAsString);
}

// In case the matcher is a IProtoBufMatcher, use the BodyAsBytes to match on.

Check warning on line 69 in src/WireMock.Net/Matchers/Helpers/BodyDataMatchScoreCalculator.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/Matchers/Helpers/BodyDataMatchScoreCalculator.cs#L69

Added line #L69 was not covered by tests
if (matcher is IProtoBufMatcher protoBufMatcher)
{
return protoBufMatcher.IsMatchAsync(requestMessage.BodyAsBytes).GetAwaiter().GetResult();
}

return default;
}
}
3 changes: 1 addition & 2 deletions src/WireMock.Net/Matchers/ProtoBufMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

#if PROTOBUF
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ProtoBufJsonConverter;
Expand All @@ -28,7 +27,7 @@ public class ProtoBufMatcher : IProtoBufMatcher
/// <summary>
/// The Func to define the proto definition as id or texts.
/// </summary>
public Func<IdOrTexts> ProtoDefinition { get; }
public Func<IdOrTexts> ProtoDefinition { get; internal set; }

/// <summary>
/// The full type of the protobuf (request/response) message object. Format is "{package-name}.{type-name}".
Expand Down
1 change: 0 additions & 1 deletion src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

using System;
using System.Collections.Generic;
using JsonConverter.Abstractions;
using WireMock.Matchers;
using WireMock.Util;

Expand Down
15 changes: 15 additions & 0 deletions src/WireMock.Net/RequestBuilders/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;

Check warning on line 8 in src/WireMock.Net/RequestBuilders/Request.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/RequestBuilders/Request.cs#L8

Added line #L8 was not covered by tests
using System.Linq;
using Stef.Validation;
using WireMock.Matchers;

Check warning on line 11 in src/WireMock.Net/RequestBuilders/Request.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/RequestBuilders/Request.cs#L11

Added line #L11 was not covered by tests
using WireMock.Matchers.Request;

namespace WireMock.RequestBuilders;
Expand Down Expand Up @@ -71,6 +73,19 @@
return _requestMatchers.OfType<T>().FirstOrDefault(func);
}

internal bool TryGetProtoBufMatcher([NotNullWhen(true)] out IProtoBufMatcher? protoBufMatcher)

Check warning on line 76 in src/WireMock.Net/RequestBuilders/Request.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/RequestBuilders/Request.cs#L76

Added line #L76 was not covered by tests
{
protoBufMatcher = GetRequestMessageMatcher<RequestMessageProtoBufMatcher>()?.Matcher;
if (protoBufMatcher != null)
{
return true;
}

Check warning on line 83 in src/WireMock.Net/RequestBuilders/Request.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/RequestBuilders/Request.cs#L82-L83

Added lines #L82 - L83 were not covered by tests
var bodyMatcher = GetRequestMessageMatcher<RequestMessageBodyMatcher>();
protoBufMatcher = bodyMatcher?.Matchers?.OfType<IProtoBufMatcher>().FirstOrDefault();
return protoBufMatcher != null;
}

Check warning on line 88 in src/WireMock.Net/RequestBuilders/Request.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/RequestBuilders/Request.cs#L88

Added line #L88 was not covered by tests
private IRequestBuilder Add<T>(T requestMatcher) where T : IRequestMatcher
{
foreach (var existing in _requestMatchers.OfType<T>().ToArray())
Expand Down
6 changes: 3 additions & 3 deletions src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
public IResponseBuilder WithTrailingHeader(string name, params string[] values)
{
#if !TRAILINGHEADERS
throw new System.NotSupportedException("The WithBodyAsProtoBuf method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");
throw new System.NotSupportedException("The WithTrailingHeader method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");

Check warning on line 52 in src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs#L52

Added line #L52 was not covered by tests
#else

Guard.NotNull(name);
Expand All @@ -63,7 +63,7 @@
public IResponseBuilder WithTrailingHeaders(IDictionary<string, string> headers)
{
#if !TRAILINGHEADERS
throw new System.NotSupportedException("The WithBodyAsProtoBuf method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");
throw new System.NotSupportedException("The WithTrailingHeaders method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");

Check warning on line 66 in src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs#L66

Added line #L66 was not covered by tests
#else

Guard.NotNull(headers);
Expand All @@ -77,7 +77,7 @@
public IResponseBuilder WithTrailingHeaders(IDictionary<string, string[]> headers)
{
#if !TRAILINGHEADERS
throw new System.NotSupportedException("The WithBodyAsProtoBuf method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");
throw new System.NotSupportedException("The WithTrailingHeaders method can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");

Check warning on line 80 in src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/ResponseBuilders/Response.WithHeaders.cs#L80

Added line #L80 was not covered by tests
#else

Guard.NotNull(headers);
Expand Down
12 changes: 5 additions & 7 deletions src/WireMock.Net/ResponseBuilders/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using System.Threading.Tasks;
using JetBrains.Annotations;
using Stef.Validation;
using WireMock.Matchers.Request;
using WireMock.Proxy;
using WireMock.RequestBuilders;
using WireMock.Settings;
Expand Down Expand Up @@ -264,16 +263,15 @@

if (UseTransformer)
{
// Check if the body matcher is a RequestMessageProtoBufMatcher and try to decode the byte-array to a BodyAsJson.
if (mapping.RequestMatcher is Request requestMatcher && requestMessage is RequestMessage request)
// If the body matcher is a RequestMessageProtoBufMatcher or BodyMatcher with a ProtoBufMatcher then try to decode the byte-array to a BodyAsJson.

Check warning on line 266 in src/WireMock.Net/ResponseBuilders/Response.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/ResponseBuilders/Response.cs#L266

Added line #L266 was not covered by tests
if (mapping.RequestMatcher is Request request && requestMessage is RequestMessage requestMessageImplementation)
{
var protoBufMatcher = requestMatcher.GetRequestMessageMatcher<RequestMessageProtoBufMatcher>()?.Matcher;
if (protoBufMatcher != null)
if (request.TryGetProtoBufMatcher(out var protoBufMatcher))
{
var decoded = await protoBufMatcher.DecodeAsync(request.BodyData?.BodyAsBytes).ConfigureAwait(false);
var decoded = await protoBufMatcher.DecodeAsync(requestMessage.BodyData?.BodyAsBytes).ConfigureAwait(false);
if (decoded != null)
{
request.BodyAsJson = JsonUtils.ConvertValueToJToken(decoded);
requestMessageImplementation.BodyAsJson = JsonUtils.ConvertValueToJToken(decoded);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net/Serialization/MappingConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ public MappingModel ToMappingModel(IMapping mapping)
}

var bodyMatchers =
protoBufMatcher?.Matcher != null ? new[] { protoBufMatcher.Matcher } : null ??
protoBufMatcher?.Matcher != null ? [protoBufMatcher.Matcher] : null ??
multiPartMatcher?.Matchers ??
graphQLMatcher?.Matchers ??
bodyMatcher?.Matchers;
Expand Down
24 changes: 3 additions & 21 deletions src/WireMock.Net/Serialization/MatcherMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@
{
model.Pattern = texts[0];
}
else
else if (texts.Count > 1)

Check warning on line 220 in src/WireMock.Net/Serialization/MatcherMapper.cs

View check run for this annotation

Codecov / codecov/patch

src/WireMock.Net/Serialization/MatcherMapper.cs#L220

Added line #L220 was not covered by tests
{
model.Patterns = texts.Cast<object>().ToArray();
}
Expand Down Expand Up @@ -293,27 +293,9 @@
{
var objectMatcher = Map(matcher.ContentMatcher) as IObjectMatcher;

IdOrTexts protoDefinitionAsIdOrTexts;
if (protoDefinitions.Count == 1)
{
var idOrText = protoDefinitions[0];
if (_settings.ProtoDefinitions?.TryGetValue(idOrText, out var protoDefinitionFromSettings) == true)
{
protoDefinitionAsIdOrTexts = new(idOrText, protoDefinitionFromSettings);
}
else
{
protoDefinitionAsIdOrTexts = new(null, protoDefinitions);
}
}
else
{
protoDefinitionAsIdOrTexts = new(null, protoDefinitions);
}

return new ProtoBufMatcher(
() => protoDefinitionAsIdOrTexts,
matcher!.ProtoBufMessageType!,
() => ProtoDefinitionHelper.GetIdOrTexts(_settings, protoDefinitions.ToArray()),
matcher.ProtoBufMessageType!,
matchBehaviour ?? MatchBehaviour.AcceptOnMatch,
objectMatcher
);
Expand Down
6 changes: 3 additions & 3 deletions src/WireMock.Net/Server/IRespondWithAProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,14 @@ public interface IRespondWithAProvider
void ThenRespondWithStatusCode(HttpStatusCode code);

/// <summary>
/// Sets the the scenario.
/// Sets the scenario.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(string scenario);

/// <summary>
/// Sets the the scenario with an integer value.
/// Sets the scenario with an integer value.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
Expand Down Expand Up @@ -220,7 +220,7 @@ IRespondWithAProvider WithWebhook(

/// <summary>
/// Data Object which can be used when WithTransformer is used.
/// e.g. lookup an path in this object using
/// e.g. lookup a path in this object using
/// <param name="data">The data dictionary object.</param>
/// <example>
/// lookup data "1"
Expand Down
31 changes: 8 additions & 23 deletions src/WireMock.Net/Server/RespondWithAProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
namespace WireMock.Server;

/// <summary>
/// The respond with a provider.
/// The RespondWithAProvider.
/// </summary>
internal class RespondWithAProvider : IRespondWithAProvider
{
Expand All @@ -37,7 +37,6 @@ internal class RespondWithAProvider : IRespondWithAProvider
private int _timesInSameState = 1;
private bool? _useWebhookFireAndForget;
private double? _probability;
private IdOrTexts? _protoDefinition;
private GraphQLSchemaDetails? _graphQLSchemaDetails;

public Guid Guid { get; private set; }
Expand All @@ -48,6 +47,8 @@ internal class RespondWithAProvider : IRespondWithAProvider

public object? Data { get; private set; }

public IdOrTexts? ProtoDefinition { get; private set; }

/// <summary>
/// Initializes a new instance of the <see cref="RespondWithAProvider"/> class.
/// </summary>
Expand Down Expand Up @@ -104,9 +105,9 @@ public void RespondWith(IResponseProvider provider)
mapping.WithProbability(_probability.Value);
}

if (_protoDefinition != null)
if (ProtoDefinition != null)
{
mapping.WithProtoDefinition(_protoDefinition.Value);
mapping.WithProtoDefinition(ProtoDefinition.Value);
}

_registrationCallback(mapping, _saveToFile);
Expand Down Expand Up @@ -296,7 +297,7 @@ public IRespondWithAProvider WithWebhook(
Guard.NotNull(url);
Guard.NotNull(method);

Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
Webhooks = [InitWebhook(url, method, headers, useTransformer, transformerType)];

if (body != null)
{
Expand All @@ -323,7 +324,7 @@ public IRespondWithAProvider WithWebhook(
Guard.NotNull(url);
Guard.NotNull(method);

Webhooks = new[] { InitWebhook(url, method, headers, useTransformer, transformerType) };
Webhooks = [InitWebhook(url, method, headers, useTransformer, transformerType)];

if (body != null)
{
Expand Down Expand Up @@ -355,23 +356,7 @@ public IRespondWithAProvider WithProtoDefinition(params string[] protoDefinition
{
Guard.NotNull(protoDefinitionOrId);

if (protoDefinitionOrId.Length == 1)
{
var idOrText = protoDefinitionOrId[0];
if (_settings.ProtoDefinitions?.TryGetValue(idOrText, out var protoDefinitions) == true)
{
_protoDefinition = new(idOrText, protoDefinitions);
}
else
{
_protoDefinition = new(null, protoDefinitionOrId);
}
}
else
{
_protoDefinition = new(null, protoDefinitionOrId);
}

ProtoDefinition = ProtoDefinitionHelper.GetIdOrTexts(_settings, protoDefinitionOrId);

return this;
}
Expand Down
Loading
Loading