using System; using JetBrains.Annotations; using WireMock.Validation; namespace WireMock.Matchers.Request { /// /// The request body matcher. /// public class RequestMessageBodyMatcher : IRequestMatcher { /// /// The body function /// public Func Func { get; } /// /// The body data function for byte[] /// public Func DataFunc { get; } /// /// The body data function for json /// public Func JsonFunc { get; } /// /// The matcher. /// public IMatcher Matcher { get; } /// /// Initializes a new instance of the class. /// /// The body. public RequestMessageBodyMatcher([NotNull] string body) : this(new SimMetricsMatcher(body)) { } /// /// Initializes a new instance of the class. /// /// The body. public RequestMessageBodyMatcher([NotNull] byte[] body) : this(new ExactObjectMatcher(body)) { } /// /// Initializes a new instance of the class. /// /// The body. public RequestMessageBodyMatcher([NotNull] object body) : this(new ExactObjectMatcher(body)) { } /// /// Initializes a new instance of the class. /// /// The function. public RequestMessageBodyMatcher([NotNull] Func func) { Check.NotNull(func, nameof(func)); Func = func; } /// /// Initializes a new instance of the class. /// /// The function. public RequestMessageBodyMatcher([NotNull] Func func) { Check.NotNull(func, nameof(func)); DataFunc = func; } /// /// Initializes a new instance of the class. /// /// The function. public RequestMessageBodyMatcher([NotNull] Func func) { Check.NotNull(func, nameof(func)); JsonFunc = func; } /// /// Initializes a new instance of the class. /// /// The matcher. public RequestMessageBodyMatcher([NotNull] IMatcher matcher) { Check.NotNull(matcher, nameof(matcher)); Matcher = matcher; } /// public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult) { double score = IsMatch(requestMessage); return requestMatchResult.AddScore(GetType(), score); } private double IsMatch(RequestMessage requestMessage) { if (requestMessage.Body != null) { var stringMatcher = Matcher as IStringMatcher; if (stringMatcher != null) { return stringMatcher.IsMatch(requestMessage.Body); } } var objectMatcher = Matcher as IObjectMatcher; if (objectMatcher != null) { if (requestMessage.BodyAsJson != null) { return objectMatcher.IsMatch(requestMessage.BodyAsJson); } if (requestMessage.BodyAsBytes != null) { return objectMatcher.IsMatch(requestMessage.BodyAsBytes); } } if (Func != null) { return MatchScores.ToScore(requestMessage.Body != null && Func(requestMessage.Body)); } if (DataFunc != null) { return MatchScores.ToScore(requestMessage.BodyAsBytes != null && DataFunc(requestMessage.BodyAsBytes)); } if (JsonFunc != null) { return MatchScores.ToScore(requestMessage.BodyAsJson != null && JsonFunc(requestMessage.BodyAsJson)); } return MatchScores.Mismatch; } } }