Пример #1
0
        private double IsMatch(RequestMessage requestMessage)
        {
            if (requestMessage.Headers == null)
            {
                return(MatchScores.Mismatch);
            }

            if (Funcs != null)
            {
                return(MatchScores.ToScore(Funcs.Any(f => f(requestMessage.Headers.ToDictionary(entry => entry.Key, entry => entry.Value.ToArray())))));
            }

            if (Matchers == null)
            {
                return(MatchScores.Mismatch);
            }

            if (!requestMessage.Headers.ContainsKey(Name))
            {
                return(MatchScores.Mismatch);
            }

            WireMockList <string> list = requestMessage.Headers[Name];

            return(Matchers.Max(m => list.Max(value => m.IsMatch(value)))); // TODO : is this correct ?
        }
Пример #2
0
        private double IsMatch(RequestMessage requestMessage)
        {
            if (requestMessage.Headers == null)
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            // Check if we want to use IgnoreCase to compare the Header-Name and Header-Value(s)
            var headers = !_ignoreCase ? requestMessage.Headers : new Dictionary <string, WireMockList <string> >(requestMessage.Headers, StringComparer.OrdinalIgnoreCase);

            if (Funcs != null)
            {
                return(MatchScores.ToScore(Funcs.Any(f => f(headers.ToDictionary(entry => entry.Key, entry => entry.Value.ToArray())))));
            }

            if (Matchers == null)
            {
                return(MatchScores.Mismatch);
            }

            if (!headers.ContainsKey(Name))
            {
                return(MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch));
            }

            WireMockList <string> list = headers[Name];

            return(Matchers.Max(m => list.Max(value => m.IsMatch(value)))); // TODO : is this correct ?
        }
        private double CalculateScore(WireMockList <string> valuesPresentInRequestMessage)
        {
            var total = new List <double>();

            // If the total patterns in all matchers > values in message, use the matcher as base
            if (Matchers.Sum(m => m.GetPatterns().Length) > valuesPresentInRequestMessage.Count)
            {
                foreach (var matcher in Matchers)
                {
                    double score = 0d;
                    foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
                    {
                        score += matcher.IsMatch(valuePresentInRequestMessage) / matcher.GetPatterns().Length;
                    }

                    total.Add(score);
                }
            }
            else
            {
                foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
                {
                    double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
                    total.Add(score);
                }
            }

            return(total.Any() ? MatchScores.ToScore(total) : MatchScores.Mismatch);
        }
        private double IsMatch(RequestMessage requestMessage)
        {
            if (Funcs != null)
            {
                return(MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query))));
            }

            WireMockList <string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key, IgnoreCase ?? false);

            if (valuesPresentInRequestMessage == null)
            {
                // Key is not present at all, just return Mismatch
                return(MatchScores.Mismatch);
            }

            if (Matchers != null && Matchers.Any())
            {
                // Return the score based on Matchers and valuesPresentInRequestMessage
                return(CalculateScore(valuesPresentInRequestMessage));
            }

            if (Matchers == null || !Matchers.Any())
            {
                // Matchers are null or not defined, and Key is present, just return Perfect.
                return(MatchScores.Perfect);
            }

            return(MatchScores.Mismatch);
        }
Пример #5
0
        /// <summary>
        /// Adds the header.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="values">The values.</param>
        public void AddHeader(string name, params string[] values)
        {
            Check.NotNullOrEmpty(values, nameof(values));

            var newHeaderValues = Headers.TryGetValue(name, out WireMockList <string> existingValues)
                ? values.Union(existingValues).ToArray()
                : values;

            Headers[name] = new WireMockList <string>(newHeaderValues);
        }
Пример #6
0
        private double IsMatch(RequestMessage requestMessage)
        {
            if (Funcs != null)
            {
                return(MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query))));
            }

            WireMockList <string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key);

            if (valuesPresentInRequestMessage == null)
            {
                // Key is not present at all, just return Mismatch
                return(MatchScores.Mismatch);
            }

            if (Matchers != null && Matchers.Any())
            {
                // Matchers are defined, just use the matchers to calculate the match score.
                var scores = new List <double>();
                foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
                {
                    double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
                    scores.Add(score);
                }

                return(scores.Any() ? scores.Average() : MatchScores.Mismatch);
            }

            if (Matchers == null || !Matchers.Any())
            {
                // Matchers are null or not defined, and Key is present, just return Perfect.
                return(MatchScores.Perfect);
            }

            return(MatchScores.Mismatch);
        }
Пример #7
0
        public static async Task <ResponseMessage> SendAsync([NotNull] HttpClient client, [NotNull] RequestMessage requestMessage, string url)
        {
            Check.NotNull(client, nameof(client));
            Check.NotNull(requestMessage, nameof(requestMessage));

            var originalUri = new Uri(requestMessage.Url);
            var requiredUri = new Uri(url);

            var httpRequestMessage = new HttpRequestMessage(new HttpMethod(requestMessage.Method), url);

            WireMockList <string> contentTypeHeader = null;
            bool contentTypeHeaderPresent           = requestMessage.Headers.Any(header => string.Equals(header.Key, HttpKnownHeaderNames.ContentType, StringComparison.OrdinalIgnoreCase));

            if (contentTypeHeaderPresent)
            {
                contentTypeHeader = requestMessage.Headers[HttpKnownHeaderNames.ContentType];
            }

            // Set Body if present
            if (requestMessage.BodyAsBytes != null)
            {
                httpRequestMessage.Content = new ByteArrayContent(requestMessage.BodyAsBytes);
            }
            else if (requestMessage.BodyAsJson != null)
            {
                httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(requestMessage.BodyAsJson), requestMessage.BodyEncoding);
            }
            else if (requestMessage.Body != null)
            {
                httpRequestMessage.Content = new StringContent(requestMessage.Body, requestMessage.BodyEncoding);
            }

            // Overwrite the host header
            httpRequestMessage.Headers.Host = requiredUri.Authority;

            // Set headers if present
            if (requestMessage.Headers != null)
            {
                foreach (var header in requestMessage.Headers.Where(header => !string.Equals(header.Key, "HOST", StringComparison.OrdinalIgnoreCase)))
                {
                    // Try to add to request headers. If failed - try to add to content headers
                    if (!httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value))
                    {
                        httpRequestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value);
                    }
                }
            }

            // Call the URL
            var httpResponseMessage = await client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead);

            // Create transform response
            var responseMessage = new ResponseMessage {
                StatusCode = (int)httpResponseMessage.StatusCode
            };

            // Set both content and response headers, replacing URLs in values
            var headers = (httpResponseMessage.Content?.Headers.Union(httpResponseMessage.Headers) ?? Enumerable.Empty <KeyValuePair <string, IEnumerable <string> > >()).ToArray();

            if (httpResponseMessage.Content != null)
            {
                var stream = await httpResponseMessage.Content.ReadAsStreamAsync();

                var body = await BodyParser.Parse(stream, contentTypeHeader?.FirstOrDefault());

                responseMessage.Body        = body.BodyAsString;
                responseMessage.BodyAsJson  = body.BodyAsJson;
                responseMessage.BodyAsBytes = body.BodyAsBytes;
            }

            foreach (var header in headers)
            {
                // If Location header contains absolute redirect URL, and base URL is one that we proxy to,
                // we need to replace it to original one.
                if (string.Equals(header.Key, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase) &&
                    Uri.TryCreate(header.Value.First(), UriKind.Absolute, out Uri absoluteLocationUri) &&
                    string.Equals(absoluteLocationUri.Host, requiredUri.Host, StringComparison.OrdinalIgnoreCase))
                {
                    var replacedLocationUri = new Uri(originalUri, absoluteLocationUri.PathAndQuery);
                    responseMessage.AddHeader(header.Key, replacedLocationUri.ToString());
                }
                else
                {
                    responseMessage.AddHeader(header.Key, header.Value.ToArray());
                }
            }

            return(responseMessage);
        }