Summary

Class:WireMock.Owin.WireMockMiddleware
Assembly:WireMock.Net
File(s):C:\Users\StefHeyenrath\Documents\GitHub\WireMock.Net\src\WireMock.Net\Owin\WireMockMiddleware.cs
Covered lines:102
Uncovered lines:6
Coverable lines:108
Total lines:188
Line coverage:94.4%
Branch coverage:86.3%

Metrics

MethodCyclomatic complexity NPath complexity Sequence coverage Branch coverage
Invoke(...)0010
LogRequest(...)0011
.ctor(...)0010
.cctor()0010
InvokeInternal()000.9080.846

File(s)

C:\Users\StefHeyenrath\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;
 10using WireMock.Owin.Mappers;
 11using WireMock.Serialization;
 12using WireMock.Validation;
 13#if !USE_ASPNETCORE
 14using Microsoft.Owin;
 15using IContext = Microsoft.Owin.IOwinContext;
 16using OwinMiddleware = Microsoft.Owin.OwinMiddleware;
 17using Next = Microsoft.Owin.OwinMiddleware;
 18#else
 19using OwinMiddleware = System.Object;
 20using IContext = Microsoft.AspNetCore.Http.HttpContext;
 21using Next = Microsoft.AspNetCore.Http.RequestDelegate;
 22#endif
 23
 24namespace WireMock.Owin
 25{
 26    internal class WireMockMiddleware : OwinMiddleware
 27    {
 128        private static readonly Task CompletedTask = Task.FromResult(false);
 29        private readonly IWireMockMiddlewareOptions _options;
 30        private readonly IOwinRequestMapper _requestMapper;
 31        private readonly IOwinResponseMapper _responseMapper;
 32        private readonly IMappingMatcher _mappingMatcher;
 33
 34#if !USE_ASPNETCORE
 35        public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwin
 36        {
 37            Check.NotNull(options, nameof(options));
 38            Check.NotNull(requestMapper, nameof(requestMapper));
 39            Check.NotNull(responseMapper, nameof(responseMapper));
 40            Check.NotNull(mappingMatcher, nameof(mappingMatcher));
 41
 42            _options = options;
 43            _requestMapper = requestMapper;
 44            _responseMapper = responseMapper;
 45            _mappingMatcher = mappingMatcher;
 46        }
 47#else
 5148        public WireMockMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinRequestMapper requestMapper, IOwin
 5149        {
 5150            Check.NotNull(options, nameof(options));
 5151            Check.NotNull(requestMapper, nameof(requestMapper));
 5152            Check.NotNull(responseMapper, nameof(responseMapper));
 5153            Check.NotNull(mappingMatcher, nameof(mappingMatcher));
 54
 5155            _options = options;
 5156            _requestMapper = requestMapper;
 5157            _responseMapper = responseMapper;
 5158            _mappingMatcher = mappingMatcher;
 5159        }
 60#endif
 61
 62#if !USE_ASPNETCORE
 63        public override Task Invoke(IContext ctx)
 64#else
 65        public Task Invoke(IContext ctx)
 66#endif
 5067        {
 4968            return InvokeInternal(ctx);
 5069        }
 70
 71        private async Task InvokeInternal(IContext ctx)
 4972        {
 4973            var request = await _requestMapper.MapAsync(ctx.Request);
 74
 4975            bool logRequest = false;
 4976            ResponseMessage response = null;
 4977            (IMapping TargetMapping, RequestMatchResult RequestMatchResult) result = (null, null);
 78            try
 4979            {
 48980                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
 3081                {
 82                    // Set start
 3083                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
 484                    {
 485                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
 486                        {
 487                            Name = mapping.Scenario
 488                        });
 489                    }
 3090                }
 91
 5092                result = _mappingMatcher.Match(request);
 5093                var targetMapping = result.TargetMapping;
 94
 5095                if (targetMapping == null)
 1396                {
 1397                    logRequest = true;
 1398                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
 1399                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
 13100                    return;
 101                }
 102
 37103                logRequest = !targetMapping.IsAdminInterface;
 104
 37105                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
 2106                {
 2107                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<stri
 2108                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfec
 2109                    {
 2110                        _options.Logger.Error("HttpStatusCode set to 401");
 2111                        response = ResponseMessageBuilder.Create(null, 401);
 2112                        return;
 113                    }
 0114                }
 115
 35116                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
 1117                {
 1118                    await Task.Delay(_options.RequestProcessingDelay.Value);
 1119                }
 120
 35121                response = await targetMapping.ResponseToAsync(request);
 122
 35123                if (targetMapping.Scenario != null)
 9124                {
 9125                    _options.Scenarios[targetMapping.Scenario].NextState = targetMapping.NextState;
 9126                    _options.Scenarios[targetMapping.Scenario].Started = true;
 9127                    _options.Scenarios[targetMapping.Scenario].Finished = targetMapping.NextState == null;
 9128                }
 35129            }
 0130            catch (Exception ex)
 0131            {
 0132                _options.Logger.Error("HttpStatusCode set to 500");
 0133                response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
 0134            }
 135            finally
 50136            {
 50137                var log = new LogEntry
 50138                {
 50139                    Guid = Guid.NewGuid(),
 50140                    RequestMessage = request,
 50141                    ResponseMessage = response,
 50142                    MappingGuid = result.TargetMapping?.Guid,
 50143                    MappingTitle = result.TargetMapping?.Title,
 50144                    RequestMatchResult = result.RequestMatchResult
 50145                };
 146
 50147                LogRequest(log, logRequest);
 148
 50149                await _responseMapper.MapAsync(response, ctx.Response);
 50150            }
 151
 35152            await CompletedTask;
 50153        }
 154
 155        private void LogRequest(LogEntry entry, bool addRequest)
 49156        {
 49157            _options.Logger.DebugRequestResponse(LogEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__adm
 158
 50159            if (addRequest)
 40160            {
 40161                _options.LogEntries.Add(entry);
 40162            }
 163
 50164            if (_options.MaxRequestLogCount != null)
 3165            {
 3166                var amount = _options.LogEntries.Count - _options.MaxRequestLogCount.Value;
 8167                for (int i = 0; i < amount; i++)
 1168                {
 1169                    _options.LogEntries.RemoveAt(0);
 1170                }
 3171            }
 172
 50173            if (_options.RequestLogExpirationDuration != null)
 1174            {
 1175                var checkTime = DateTime.Now.AddHours(-_options.RequestLogExpirationDuration.Value);
 176
 4177                for (var i = _options.LogEntries.Count - 1; i >= 0; i--)
 1178                {
 1179                    var le = _options.LogEntries[i];
 1180                    if (le.RequestMessage.DateTime <= checkTime)
 1181                    {
 1182                        _options.LogEntries.RemoveAt(i);
 1183                    }
 1184                }
 1185            }
 50186        }
 187    }
 188}