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:101
Uncovered lines:6
Coverable lines:107
Total lines:187
Line coverage:94.3%
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\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;
 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));
 53
 5154            _options = options;
 5155            _requestMapper = requestMapper;
 5156            _responseMapper = responseMapper;
 5157            _mappingMatcher = mappingMatcher;
 5158        }
 59#endif
 60
 61#if !USE_ASPNETCORE
 62        public override Task Invoke(IContext ctx)
 63#else
 64        public Task Invoke(IContext ctx)
 65#endif
 5066        {
 5067            return InvokeInternal(ctx);
 5068        }
 69
 70        private async Task InvokeInternal(IContext ctx)
 5071        {
 5072            var request = await _requestMapper.MapAsync(ctx.Request);
 73
 5074            bool logRequest = false;
 5075            ResponseMessage response = null;
 5076            (IMapping TargetMapping, RequestMatchResult RequestMatchResult) result = (null, null);
 77            try
 5078            {
 48979                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
 3080                {
 81                    // Set start
 3082                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
 483                    {
 484                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
 485                        {
 486                            Name = mapping.Scenario
 487                        });
 488                    }
 3089                }
 90
 5091                result = _mappingMatcher.Match(request);
 5092                var targetMapping = result.TargetMapping;
 93
 5094                if (targetMapping == null)
 1395                {
 1396                    logRequest = true;
 1397                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
 1398                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
 1399                    return;
 100                }
 101
 37102                logRequest = !targetMapping.IsAdminInterface;
 103
 37104                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
 2105                {
 2106                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<stri
 2107                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfec
 2108                    {
 2109                        _options.Logger.Error("HttpStatusCode set to 401");
 2110                        response = ResponseMessageBuilder.Create(null, 401);
 2111                        return;
 112                    }
 0113                }
 114
 35115                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
 1116                {
 1117                    await Task.Delay(_options.RequestProcessingDelay.Value);
 1118                }
 119
 35120                response = await targetMapping.ResponseToAsync(request);
 121
 35122                if (targetMapping.Scenario != null)
 9123                {
 9124                    _options.Scenarios[targetMapping.Scenario].NextState = targetMapping.NextState;
 9125                    _options.Scenarios[targetMapping.Scenario].Started = true;
 9126                    _options.Scenarios[targetMapping.Scenario].Finished = targetMapping.NextState == null;
 9127                }
 35128            }
 0129            catch (Exception ex)
 0130            {
 0131                _options.Logger.Error("HttpStatusCode set to 500");
 0132                response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
 0133            }
 134            finally
 50135            {
 50136                var log = new LogEntry
 50137                {
 50138                    Guid = Guid.NewGuid(),
 50139                    RequestMessage = request,
 50140                    ResponseMessage = response,
 50141                    MappingGuid = result.TargetMapping?.Guid,
 50142                    MappingTitle = result.TargetMapping?.Title,
 50143                    RequestMatchResult = result.RequestMatchResult
 50144                };
 145
 50146                LogRequest(log, logRequest);
 147
 50148                await _responseMapper.MapAsync(response, ctx.Response);
 50149            }
 150
 35151            await CompletedTask;
 50152        }
 153
 154        private void LogRequest(LogEntry entry, bool addRequest)
 50155        {
 50156            _options.Logger.DebugRequestResponse(LogEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__adm
 157
 50158            if (addRequest)
 40159            {
 40160                _options.LogEntries.Add(entry);
 40161            }
 162
 50163            if (_options.MaxRequestLogCount != null)
 3164            {
 3165                var amount = _options.LogEntries.Count - _options.MaxRequestLogCount.Value;
 8166                for (int i = 0; i < amount; i++)
 1167                {
 1168                    _options.LogEntries.RemoveAt(0);
 1169                }
 3170            }
 171
 50172            if (_options.RequestLogExpirationDuration != null)
 1173            {
 1174                var checkTime = DateTime.Now.AddHours(-_options.RequestLogExpirationDuration.Value);
 175
 4176                for (var i = _options.LogEntries.Count - 1; i >= 0; i--)
 1177                {
 1178                    var le = _options.LogEntries[i];
 1179                    if (le.RequestMessage.DateTime <= checkTime)
 1180                    {
 1181                        _options.LogEntries.RemoveAt(i);
 1182                    }
 1183                }
 1184            }
 50185        }
 186    }
 187}