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:90
Uncovered lines:34
Coverable lines:124
Total lines:194
Line coverage:72.5%
Branch coverage:64.5%

Metrics

MethodCyclomatic complexity NPath complexity Sequence coverage Branch coverage
LogRequest(...)000.5930.583
.ctor(...)0010
.cctor()0010
Invoke()000.7560.676

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Threading.Tasks;
 4using WireMock.Logging;
 5using WireMock.Matchers.Request;
 6using System.Linq;
 7using WireMock.Matchers;
 8using WireMock.Util;
 9using Newtonsoft.Json;
 10using WireMock.Http;
 11using WireMock.Serialization;
 12#if !USE_ASPNETCORE
 13using Microsoft.Owin;
 14#else
 15using Microsoft.AspNetCore.Http;
 16#endif
 17
 18namespace WireMock.Owin
 19{
 20#if !USE_ASPNETCORE
 21    internal class WireMockMiddleware : OwinMiddleware
 22#else
 23    internal class WireMockMiddleware
 24#endif
 25    {
 126        private static readonly Task CompletedTask = Task.FromResult(false);
 27        private readonly WireMockMiddlewareOptions _options;
 28
 4929        private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper();
 4930        private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper();
 31
 32#if !USE_ASPNETCORE
 33        public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
 34        {
 35            _options = options;
 36        }
 37#else
 4938        public WireMockMiddleware(RequestDelegate next, WireMockMiddlewareOptions options)
 4939        {
 4940            _options = options;
 4941        }
 42#endif
 43
 44#if !USE_ASPNETCORE
 45        public override async Task Invoke(IOwinContext ctx)
 46#else
 47        public async Task Invoke(HttpContext ctx)
 48#endif
 6549        {
 6550            var request = await _requestMapper.MapAsync(ctx.Request);
 51
 6552            bool logRequest = false;
 6553            ResponseMessage response = null;
 6554            Mapping targetMapping = null;
 6555            RequestMatchResult requestMatchResult = null;
 56            try
 6557            {
 55058                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
 3059                {
 60                    // Set start
 3061                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
 462                    {
 463                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
 464                        {
 465                            Name = mapping.Scenario
 466                        });
 467                    }
 3068                }
 69
 6570                var mappings = _options.Mappings.Values
 36071                    .Select(m => new
 36072                    {
 36073                        Mapping = m,
 36074                        MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _options.Scenarios.Contains
 36075                    })
 6576                    .ToList();
 77
 6578                if (_options.AllowPartialMapping)
 079                {
 080                    var partialMappings = mappings
 081                        .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdmin
 082                        .OrderBy(m => m.MatchResult)
 083                        .ThenBy(m => m.Mapping.Priority)
 084                        .ToList();
 85
 086                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);
 87
 088                    targetMapping = bestPartialMatch?.Mapping;
 089                    requestMatchResult = bestPartialMatch?.MatchResult;
 090                }
 91                else
 6592                {
 6593                    var perfectMatch = mappings
 11794                        .OrderBy(m => m.Mapping.Priority)
 36095                        .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);
 96
 6597                    targetMapping = perfectMatch?.Mapping;
 6598                    requestMatchResult = perfectMatch?.MatchResult;
 6599                }
 100
 65101                if (targetMapping == null)
 14102                {
 14103                    logRequest = true;
 14104                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
 14105                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
 14106                    return;
 107                }
 108
 51109                logRequest = !targetMapping.IsAdminInterface;
 110
 51111                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
 0112                {
 0113                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList<stri
 0114                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfec
 0115                    {
 0116                        _options.Logger.Error("HttpStatusCode set to 401");
 0117                        response = ResponseMessageBuilder.Create(null, 401);
 0118                        return;
 119                    }
 0120                }
 121
 51122                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
 1123                {
 1124                    await Task.Delay(_options.RequestProcessingDelay.Value);
 1125                }
 126
 51127                response = await targetMapping.ResponseToAsync(request);
 128
 51129                if (targetMapping.Scenario != null)
 9130                {
 9131                    _options.Scenarios[targetMapping.Scenario].NextState = targetMapping.NextState;
 9132                    _options.Scenarios[targetMapping.Scenario].Started = true;
 9133                    _options.Scenarios[targetMapping.Scenario].Finished = targetMapping.NextState == null;
 9134                }
 51135            }
 0136            catch (Exception ex)
 0137            {
 0138                _options.Logger.Error("HttpStatusCode set to 500");
 0139                response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
 0140            }
 141            finally
 65142            {
 65143                var log = new LogEntry
 65144                {
 65145                    Guid = Guid.NewGuid(),
 65146                    RequestMessage = request,
 65147                    ResponseMessage = response,
 65148                    MappingGuid = targetMapping?.Guid,
 65149                    MappingTitle = targetMapping?.Title,
 65150                    RequestMatchResult = requestMatchResult
 65151                };
 152
 65153                LogRequest(log, logRequest);
 154
 65155                await _responseMapper.MapAsync(response, ctx.Response);
 65156            }
 157
 51158            await CompletedTask;
 65159        }
 160
 161        private void LogRequest(LogEntry entry, bool addRequest)
 65162        {
 65163            _options.Logger.DebugRequestResponse(LogEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__adm
 164
 65165            if (addRequest)
 57166            {
 57167                _options.LogEntries.Add(entry);
 57168            }
 169
 65170            if (_options.MaxRequestLogCount != null)
 3171            {
 3172                var amount = _options.LogEntries.Count - _options.MaxRequestLogCount.Value;
 8173                for (int i = 0; i < amount; i++)
 1174                {
 1175                    _options.LogEntries.RemoveAt(0);
 1176                }
 3177            }
 178
 65179            if (_options.RequestLogExpirationDuration != null)
 0180            {
 0181                var checkTime = DateTime.Now.AddHours(-_options.RequestLogExpirationDuration.Value);
 182
 0183                for (var i = _options.LogEntries.Count - 1; i >= 0; i--)
 0184                {
 0185                    var le = _options.LogEntries[i];
 0186                    if (le.RequestMessage.DateTime <= checkTime)
 0187                    {
 0188                        _options.LogEntries.RemoveAt(i);
 0189                    }
 0190                }
 0191            }
 65192        }
 193    }
 194}