コード例 #1
0
        private ResponseMessage MappingsReset(RequestMessage requestMessage)
        {
            ResetMappings();

            ResetScenarios();

            string message = "Mappings reset";

            if (requestMessage.Query.ContainsKey(QueryParamReloadStaticMappings) &&
                bool.TryParse(requestMessage.Query[QueryParamReloadStaticMappings].ToString(), out bool reloadStaticMappings) &&
                reloadStaticMappings)
            {
                ReadStaticMappings();
                message = $"{message} and static mappings reloaded";
            }

            return(ResponseMessageBuilder.Create(message));
        }
コード例 #2
0
        private ResponseMessage SettingsUpdate(RequestMessage requestMessage)
        {
            var settings = DeserializeObject <SettingsModel>(requestMessage);

            _options.MaxRequestLogCount           = settings.MaxRequestLogCount;
            _options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration;

            if (settings.AllowPartialMapping != null)
            {
                _options.AllowPartialMapping = settings.AllowPartialMapping.Value;
            }

            if (settings.GlobalProcessingDelay != null)
            {
                _options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
            }

            return(ResponseMessageBuilder.Create("Settings updated"));
        }
コード例 #3
0
        /// <summary>
        /// Recieve a tag type dto from the body and create a new tag from the
        /// dto.
        ///
        /// Return the newly created tag including its id to the client
        /// </summary>
        /// <param name="newTag"></param>
        /// <returns></returns>
        public TagTypeDto Post([FromBody] TagTypeDto newTag)
        {
            return(ActionVerbConfigService.WrapAction(() =>
            {
                // map from the new tag to a TagType domain obhject using auto mapper
                var tagTypeDomainObject = AutoMapper.Mapper.Map <TagTypeDto, TagType>(newTag);

                var tagCreateActionResult = _tagTypesLogic.CreateTagForCategory(tagTypeDomainObject, newTag.CategoryId);

                if (tagCreateActionResult.Success)
                {
                    // map the dto of the newly created tag returned form the service to an apropriate tag dto
                    // which we will return back to the client
                    var storedTagDto = AutoMapper.Mapper.Map <TagType, TagTypeDto>(tagCreateActionResult.Data);
                    return storedTagDto;
                }

                throw new HttpResponseException(
                    ResponseMessageBuilder.BuildMessageFromActionResult(tagCreateActionResult));
            }));
        }
コード例 #4
0
        private ResponseMessage MappingsPost(RequestMessage requestMessage)
        {
            Guid?guid;

            try
            {
                var mappingModel = DeserializeObject <MappingModel>(requestMessage);
                guid = DeserializeAndAddOrUpdateMapping(mappingModel);
            }
            catch (ArgumentException a)
            {
                _logger.Error("HttpStatusCode set to 400 {0}", a);
                return(ResponseMessageBuilder.Create(a.Message, 400));
            }
            catch (Exception e)
            {
                _logger.Error("HttpStatusCode set to 500 {0}", e);
                return(ResponseMessageBuilder.Create(e.ToString(), 500));
            }

            return(ResponseMessageBuilder.Create("Mapping added", 201, guid));
        }
コード例 #5
0
        private ResponseMessage MappingsDelete(RequestMessage requestMessage)
        {
            if (!string.IsNullOrEmpty(requestMessage.Body))
            {
                var deletedGuids = MappingsDeleteMappingFromBody(requestMessage);
                if (deletedGuids != null)
                {
                    return(ResponseMessageBuilder.Create($"Mappings deleted. Affected GUIDs: [{string.Join(", ", deletedGuids.ToArray())}]"));
                }
                else
                {
                    // return bad request
                    return(ResponseMessageBuilder.Create("Poorly formed mapping JSON.", 400));
                }
            }
            else
            {
                ResetMappings();

                ResetScenarios();

                return(ResponseMessageBuilder.Create("Mappings deleted"));
            }
        }
コード例 #6
0
        private ResponseMessage ScenariosReset(RequestMessage requestMessage)
        {
            ResetScenarios();

            return(ResponseMessageBuilder.Create("Scenarios reset"));
        }
コード例 #7
0
        private ResponseMessage RequestsDelete(RequestMessage requestMessage)
        {
            ResetLogEntries();

            return(ResponseMessageBuilder.Create("Requests deleted"));
        }
コード例 #8
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.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);

                var responseBuilder = targetMapping.Provider as Response;

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

                    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(targetMapping);
                    }
                }

                if (targetMapping.Scenario != null)
                {
                    UpdateScenarioState(targetMapping);
                }
            }
            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;
        }
コード例 #9
0
        private ResponseMessage MappingsSave(RequestMessage requestMessage)
        {
            SaveStaticMappings();

            return(ResponseMessageBuilder.Create("Mappings saved to disk"));
        }
コード例 #10
0
        private async Task InvokeInternal(IContext ctx)
        {
#if !USE_ASPNETCORE
            if (ctx.Get <bool>("gotoNext"))
            {
                await Next?.Invoke(ctx);

                return;
            }
#else
#endif

            var request = await _requestMapper.MapAsync(ctx.Request, _options);

            bool                 logRequest = false;
            ResponseMessage      response   = null;
            MappingMatcherResult result     = 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.FindBestMatch(request);

                var targetMapping = result?.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.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?.Mapping?.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?.Mapping?.Guid,
                    MappingTitle       = result?.Mapping?.Title,
                    RequestMatchResult = result?.RequestMatchResult
                };

                LogRequest(log, logRequest);

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

            await CompletedTask;
        }
コード例 #11
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;
        }