Summary

Class:WireMock.Owin.WireMockMiddleware
Assembly:WireMock.Net
File(s):C:\Users\azureuser\Documents\Github\WireMock.Net\src\WireMock.Net\Owin\WireMockMiddleware.cs
Covered lines:84
Uncovered lines:34
Coverable lines:118
Total lines:185
Line coverage:71.1%
Branch coverage:69.2%

Metrics

MethodCyclomatic complexity  NPath complexity  Sequence coverage  Branch coverage  
.ctor(...)10100100
LogRequest(...)76456.6761.54
.cctor()10100100
Invoke()5226214474.2472.97

File(s)

C:\Users\azureuser\Documents\Github\WireMock.Net\src\WireMock.Net\Owin\WireMockMiddleware.cs

#LineLine coverage
 1using System;
 2using System.Threading.Tasks;
 3using WireMock.Logging;
 4using WireMock.Matchers.Request;
 5using System.Linq;
 6using WireMock.Matchers;
 7using WireMock.Util;
 8using Newtonsoft.Json;
 9using WireMock.Http;
 10#if !NETSTANDARD
 11using Microsoft.Owin;
 12#else
 13using Microsoft.AspNetCore.Http;
 14#endif
 15
 16namespace WireMock.Owin
 17{
 18#if !NETSTANDARD
 19    internal class WireMockMiddleware : OwinMiddleware
 20#else
 21    internal class WireMockMiddleware
 22#endif
 23    {
 124        private static readonly Task CompletedTask = Task.FromResult(false);
 25        private readonly WireMockMiddlewareOptions _options;
 26
 4727        private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper();
 4728        private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper();
 29
 30#if !NETSTANDARD
 4731        public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
 4732        {
 4733            _options = options;
 4734        }
 35#else
 36        public WireMockMiddleware(RequestDelegate next, WireMockMiddlewareOptions options)
 37        {
 38            _options = options;
 39        }
 40#endif
 41
 42#if !NETSTANDARD
 43        public override async Task Invoke(IOwinContext ctx)
 44#else
 45        public async Task Invoke(HttpContext ctx)
 46#endif
 5847        {
 5848            var request = await _requestMapper.MapAsync(ctx.Request);
 49
 5850            bool logRequest = false;
 5851            ResponseMessage response = null;
 5852            Mapping targetMapping = null;
 5853             RequestMatchResult requestMatchResult = null;
 54            try
 5855            {
 35256                 foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
 1457                {
 58                    // Set start
 1459                     if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
 260                    {
 261                        _options.Scenarios.Add(mapping.Scenario, null);
 262                    }
 1463                }
 64
 5865                var mappings = _options.Mappings.Values
 20866                     .Select(m => new
 20867                    {
 20868                        Mapping = m,
 20869                        MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _options.Scenarios.Contains
 20870                    })
 5871                    .ToList();
 72
 5873                 if (_options.AllowPartialMapping)
 074                {
 075                    var partialMappings = mappings
 076                        .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdmin
 077                        .OrderBy(m => m.MatchResult)
 078                        .ThenBy(m => m.Mapping.Priority)
 079                        .ToList();
 80
 081                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);
 82
 083                     targetMapping = bestPartialMatch?.Mapping;
 084                     requestMatchResult = bestPartialMatch?.MatchResult;
 085                }
 86                else
 5887                {
 5888                    var perfectMatch = mappings
 20889                        .OrderBy(m => m.Mapping.Priority)
 15690                        .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);
 91
 5892                     targetMapping = perfectMatch?.Mapping;
 5893                     requestMatchResult = perfectMatch?.MatchResult;
 5894                }
 95
 5896                 if (targetMapping == null)
 1297                {
 1298                    logRequest = true;
 1299                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
 12100                    response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
 12101                    return;
 102                }
 103
 46104                logRequest = !targetMapping.IsAdminInterface;
 105
 46106                 if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
 0107                {
 0108                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<stri
 0109                     if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfec
 0110                    {
 0111                        _options.Logger.Error("HttpStatusCode set to 401");
 0112                        response = new ResponseMessage { StatusCode = 401 };
 0113                        return;
 114                    }
 0115                }
 116
 46117                 if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
 1118                {
 1119                    await Task.Delay(_options.RequestProcessingDelay.Value);
 1120                }
 121
 46122                response = await targetMapping.ResponseToAsync(request);
 123
 46124                 if (targetMapping.Scenario != null)
 5125                {
 5126                    _options.Scenarios[targetMapping.Scenario] = targetMapping.NextState;
 5127                }
 46128            }
 0129            catch (Exception ex)
 0130            {
 0131                _options.Logger.Error("HttpStatusCode set to 500");
 0132                response = new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) };
 0133            }
 134            finally
 58135            {
 58136                 var log = new LogEntry
 58137                {
 58138                    Guid = Guid.NewGuid(),
 58139                    RequestMessage = request,
 58140                    ResponseMessage = response,
 58141                    MappingGuid = targetMapping?.Guid,
 58142                    MappingTitle = targetMapping?.Title,
 58143                    RequestMatchResult = requestMatchResult
 58144                };
 145
 58146                LogRequest(log, logRequest);
 147
 58148                await _responseMapper.MapAsync(response, ctx.Response);
 58149             }
 150
 46151            await CompletedTask;
 58152        }
 153
 154        private void LogRequest(LogEntry entry, bool addRequest)
 58155        {
 58156             if (addRequest)
 53157            {
 53158                _options.LogEntries.Add(entry);
 53159            }
 160
 58161             if (_options.MaxRequestLogCount != null)
 3162            {
 3163                var amount = _options.LogEntries.Count - _options.MaxRequestLogCount.Value;
 8164                 for (int i = 0; i < amount; i++)
 1165                {
 1166                    _options.LogEntries.RemoveAt(0);
 1167                }
 3168            }
 169
 58170             if (_options.RequestLogExpirationDuration != null)
 0171            {
 0172                var checkTime = DateTime.Now.AddHours(-_options.RequestLogExpirationDuration.Value);
 173
 0174                 for (var i = _options.LogEntries.Count - 1; i >= 0; i--)
 0175                {
 0176                    var le = _options.LogEntries[i];
 0177                     if (le.RequestMessage.DateTime <= checkTime)
 0178                    {
 0179                        _options.LogEntries.RemoveAt(i);
 0180                    }
 0181                }
 0182            }
 58183        }
 184    }
 185}