private ResponseMessage RequestsDelete(RequestMessage requestMessage)
        {
            ResetLogEntries();

            return(ResponseMessageBuilder.Create("Requests deleted"));
        }
        private ResponseMessage MappingsSave(RequestMessage requestMessage)
        {
            SaveStaticMappings();

            return(ResponseMessageBuilder.Create("Mappings saved to disk"));
        }
        private ResponseMessage ScenariosReset(RequestMessage requestMessage)
        {
            ResetScenarios();

            return(ResponseMessageBuilder.Create("Scenarios reset"));
        }
        private async Task InvokeInternal(IContext ctx)
        {
            var request = await _requestMapper.MapAsync(ctx.Request);

            bool            logRequest = false;
            ResponseMessage response   = null;

            (IMapping TargetMapping, RequestMatchResult RequestMatchResult)result = (null, null);
            try
            {
                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
                {
                    // Set start
                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
                    {
                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
                        {
                            Name = mapping.Scenario
                        });
                    }
                }

                result = _mappingMatcher.Match(request);
                var targetMapping = result.TargetMapping;

                if (targetMapping == null)
                {
                    logRequest = true;
                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
                    return;
                }

                logRequest = !targetMapping.IsAdminInterface;

                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
                {
                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization);
                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
                    {
                        _options.Logger.Error("HttpStatusCode set to 401");
                        response = ResponseMessageBuilder.Create(null, 401);
                        return;
                    }
                }

                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestProcessingDelay.Value);
                }

                response = await targetMapping.ProvideResponseAsync(request);

                if (targetMapping.Scenario != null)
                {
                    _options.Scenarios[targetMapping.Scenario].NextState = targetMapping.NextState;
                    _options.Scenarios[targetMapping.Scenario].Started   = true;
                    _options.Scenarios[targetMapping.Scenario].Finished  = targetMapping.NextState == null;
                }
            }
            catch (Exception ex)
            {
                _options.Logger.Error($"Providing a Response for Mapping '{result.TargetMapping.Guid}' failed. HttpStatusCode set to 500. Exception: {ex}");
                response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
            }
            finally
            {
                var log = new LogEntry
                {
                    Guid               = Guid.NewGuid(),
                    RequestMessage     = request,
                    ResponseMessage    = response,
                    MappingGuid        = result.TargetMapping?.Guid,
                    MappingTitle       = result.TargetMapping?.Title,
                    RequestMatchResult = result.RequestMatchResult
                };

                LogRequest(log, logRequest);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }
示例#5
0
        private async Task InvokeInternal(IContext ctx)
        {
            var request = await _requestMapper.MapAsync(ctx.Request, _options);

            bool            logRequest = false;
            ResponseMessage response   = null;

            (MappingMatcherResult Match, MappingMatcherResult Partial)result = (null, null);
            try
            {
                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
                {
                    // Set scenario start
                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
                    {
                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
                        {
                            Name = mapping.Scenario
                        });
                    }
                }

                result = _mappingMatcher.FindBestMatch(request);

                var targetMapping = result.Match?.Mapping;
                if (targetMapping == null)
                {
                    logRequest = true;
                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
                    return;
                }

                logRequest = targetMapping.LogMapping;

                if (targetMapping.IsAdminInterface && _options.AuthenticationMatcher != null)
                {
                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization);
                    if (!present || _options.AuthenticationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
                    {
                        _options.Logger.Error("HttpStatusCode set to 401");
                        response = ResponseMessageBuilder.Create(null, 401);
                        return;
                    }
                }

                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestProcessingDelay.Value);
                }

                var(theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request);

                response = theResponse;

                var responseBuilder = targetMapping.Provider as Response;

                if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null)
                {
                    if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMapping == true)
                    {
                        _options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping);
                    }

                    if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping?.Settings?.ProxyAndRecordSettings?.SaveMappingToFile == true)
                    {
                        var matcherMapper      = new MatcherMapper(targetMapping.Settings);
                        var mappingConverter   = new MappingConverter(matcherMapper);
                        var mappingToFileSaver = new MappingToFileSaver(targetMapping.Settings, mappingConverter);

                        mappingToFileSaver.SaveMappingToFile(theOptionalNewMapping);
                    }
                }

                if (targetMapping.Scenario != null)
                {
                    UpdateScenarioState(targetMapping);
                }

                if (!targetMapping.IsAdminInterface && targetMapping.Webhooks?.Length > 0)
                {
                    await SendToWebhooksAsync(targetMapping, request, response).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                _options.Logger.Error($"Providing a Response for Mapping '{result.Match?.Mapping?.Guid}' failed. HttpStatusCode set to 500. Exception: {ex}");
                response = ResponseMessageBuilder.Create(ex.Message, 500);
            }
            finally
            {
                var log = new LogEntry
                {
                    Guid            = Guid.NewGuid(),
                    RequestMessage  = request,
                    ResponseMessage = response,

                    MappingGuid        = result.Match?.Mapping?.Guid,
                    MappingTitle       = result.Match?.Mapping?.Title,
                    RequestMatchResult = result.Match?.RequestMatchResult,

                    PartialMappingGuid  = result.Partial?.Mapping?.Guid,
                    PartialMappingTitle = result.Partial?.Mapping?.Title,
                    PartialMatchResult  = result.Partial?.RequestMatchResult
                };

                LogRequest(log, logRequest);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }
示例#6
0
        public async Task Invoke(HttpContext ctx)
#endif
        {
            var request = await _requestMapper.MapAsync(ctx.Request);

            bool               logRequest         = false;
            ResponseMessage    response           = null;
            Mapping            targetMapping      = null;
            RequestMatchResult requestMatchResult = null;

            try
            {
                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
                {
                    // Set start
                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
                    {
                        _options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
                        {
                            Name = mapping.Scenario
                        });
                    }
                }

                var mappings = _options.Mappings.Values
                               .Select(m => new
                {
                    Mapping     = m,
                    MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _options.Scenarios.ContainsKey(m.Scenario) ? _options.Scenarios[m.Scenario].NextState : null)
                })
                               .ToList();

                if (_options.AllowPartialMapping)
                {
                    var partialMappings = mappings
                                          .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdminInterface)
                                          .OrderBy(m => m.MatchResult)
                                          .ThenBy(m => m.Mapping.Priority)
                                          .ToList();

                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);

                    targetMapping      = bestPartialMatch?.Mapping;
                    requestMatchResult = bestPartialMatch?.MatchResult;
                }
                else
                {
                    var perfectMatch = mappings
                                       .OrderBy(m => m.Mapping.Priority)
                                       .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);

                    targetMapping      = perfectMatch?.Mapping;
                    requestMatchResult = perfectMatch?.MatchResult;
                }

                if (targetMapping == null)
                {
                    logRequest = true;
                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
                    response = ResponseMessageBuilder.Create("No matching mapping found", 404);
                    return;
                }

                logRequest = !targetMapping.IsAdminInterface;

                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
                {
                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization);
                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
                    {
                        _options.Logger.Error("HttpStatusCode set to 401");
                        response = ResponseMessageBuilder.Create(null, 401);
                        return;
                    }
                }

                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestProcessingDelay.Value);
                }

                response = await targetMapping.ResponseToAsync(request);

                if (targetMapping.Scenario != null)
                {
                    _options.Scenarios[targetMapping.Scenario].NextState = targetMapping.NextState;
                    _options.Scenarios[targetMapping.Scenario].Started   = true;
                    _options.Scenarios[targetMapping.Scenario].Finished  = targetMapping.NextState == null;
                }
            }
            catch (Exception ex)
            {
                _options.Logger.Error("HttpStatusCode set to 500");
                response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
            }
            finally
            {
                var log = new LogEntry
                {
                    Guid               = Guid.NewGuid(),
                    RequestMessage     = request,
                    ResponseMessage    = response,
                    MappingGuid        = targetMapping?.Guid,
                    MappingTitle       = targetMapping?.Title,
                    RequestMatchResult = requestMatchResult
                };

                LogRequest(log, logRequest);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }