コード例 #1
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result = new ConditionCheckResultModel();

        if (stub.Conditions?.Json == null)
        {
            return(result);
        }

        var convertedJsonConditions = ConvertJsonConditions(stub.Conditions.Json);

        var body = _httpContextService.GetBody();

        try
        {
            var jToken     = JToken.Parse(body);
            var logResults = new List <string>();
            result.ConditionValidation = CheckSubmittedJson(convertedJsonConditions, jToken, logResults)
                ? ConditionValidationType.Valid
                : ConditionValidationType.Invalid;
            result.Log = string.Join(Environment.NewLine, logResults);
        }
        catch (JsonReaderException ex)
        {
            result.ConditionValidation = ConditionValidationType.Invalid;
            result.Log = ex.Message;
        }

        return(result);
    }
コード例 #2
0
        public ConditionCheckResultModel Validate(string stubId, StubConditionsModel conditions)
        {
            var result             = new ConditionCheckResultModel();
            var jsonPathConditions = conditions?.JsonPath?.ToArray();

            if (jsonPathConditions == null || jsonPathConditions?.Any() != true)
            {
                return(result);
            }

            var validJsonPaths = 0;
            var body           = _httpContextService.GetBody();
            var jsonObject     = JObject.Parse(body);

            foreach (var condition in jsonPathConditions)
            {
                var elements = jsonObject.SelectToken(condition);
                if (elements == null)
                {
                    // No suitable JSON results found.
                    result.Log = $"No suitable JSON results found with JSONPath query '{condition}'.";
                    break;
                }

                validJsonPaths++;
            }

            // If the number of succeeded conditions is equal to the actual number of conditions,
            // the header condition is passed and the stub ID is passed to the result.
            result.ConditionValidation = validJsonPaths == jsonPathConditions.Length
                ? ConditionValidationType.Valid
                : ConditionValidationType.Invalid;

            return(result);
        }
コード例 #3
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result = new ConditionCheckResultModel();
        var bodyConditions = stub.Conditions?.Body?.ToArray();
        if (bodyConditions == null || bodyConditions?.Any() != true)
        {
            return result;
        }

        var body = _httpContextService.GetBody();

        var validBodyConditions = 0;
        foreach (var condition in bodyConditions)
        {
            if (!StringHelper.IsRegexMatchOrSubstring(body, condition))
            {
                // If the check failed, it means the query string is incorrect and the condition should fail.
                result.Log = $"Body condition '{condition}' failed.";
                break;
            }

            validBodyConditions++;
        }

        // If the number of succeeded conditions is equal to the actual number of conditions,
        // the body condition is passed and the stub ID is passed to the result.
        result.ConditionValidation = validBodyConditions == bodyConditions.Length
            ? ConditionValidationType.Valid
            : ConditionValidationType.Invalid;

        return result;
    }
コード例 #4
0
    /// <inheritdoc />
    public string Parse(string input, IEnumerable <Match> matches)
    {
        var matchArray = matches as Match[] ?? matches.ToArray();

        if (!matchArray.Any())
        {
            return(input);
        }

        var     body       = _httpContextService.GetBody();
        JObject jsonObject = null;

        try
        {
            jsonObject = JObject.Parse(body);
        }
        catch (JsonException je)
        {
            _logger.LogInformation($"Exception occurred while trying to parse response body as JSON: {je}");
        }

        return(matchArray
               .Where(match => match.Groups.Count >= 2)
               .Aggregate(input,
                          (current, match) => current.Replace(match.Value, GetJsonPathValue(match, jsonObject))));
    }
コード例 #5
0
    private async Task <ResponseModel> HandleRequest(string correlation)
    {
        var requestLogger = _requestLoggerFactory.GetRequestLogger();

        // Enable rewind here to be able to read the posted body multiple times.
        _httpContextService.EnableRewind();

        // Log the request here
        requestLogger.LogRequestParameters(
            _httpContextService.Method,
            _httpContextService.DisplayUrl,
            _httpContextService.GetBody(),
            _clientDataResolver.GetClientIp(),
            _httpContextService.GetHeaders());

        _httpContextService.ClearResponse();
        _httpContextService.TryAddHeader(CorrelationHeaderKey, correlation);
        var response = await _stubRequestExecutor.ExecuteRequestAsync();

        _httpContextService.SetStatusCode(response.StatusCode);
        foreach (var(key, value) in response.Headers)
        {
            _httpContextService.AddHeader(key, value);
        }

        if (response.Body != null)
        {
            await _httpContextService.WriteAsync(response.Body);
        }

        return(response);
    }
コード例 #6
0
        public ConditionCheckResultModel Validate(string stubId, StubConditionsModel conditions)
        {
            var result          = new ConditionCheckResultModel();
            var xpathConditions = conditions?.Xpath?.ToArray() ?? new StubXpathModel[0];

            if (!xpathConditions.Any())
            {
                return(result);
            }

            var validXpaths = 0;
            var body        = _httpContextService.GetBody();
            var doc         = new XmlDocument();

            doc.LoadXml(body);
            foreach (var condition in xpathConditions)
            {
                var nsManager  = new XmlNamespaceManager(doc.NameTable);
                var namespaces = condition.Namespaces;
                if (namespaces != null)
                {
                    foreach (var ns in namespaces)
                    {
                        nsManager.AddNamespace(ns.Key, ns.Value);
                    }
                }
                else
                {
                    // If no namespaces are defined, check the XML namespaces with a regex.
                    nsManager.ParseBodyAndAssignNamespaces(body);
                }

                var elements = doc.SelectNodes(condition.QueryString, nsManager);
                if (elements != null && elements.Count == 0)
                {
                    // No suitable XML results found.
                    result.Log = $"No suitable XML results found with XPath query {condition}.";
                    break;
                }

                validXpaths++;
            }

            // If the number of succeeded conditions is equal to the actual number of conditions,
            // the header condition is passed and the stub ID is passed to the result.
            result.ConditionValidation = validXpaths == xpathConditions.Length ? ConditionValidationType.Valid : ConditionValidationType.Invalid;

            return(result);
        }
コード例 #7
0
        public string Parse(string input, IEnumerable <Match> matches)
        {
            var enumerable = matches as Match[] ?? matches.ToArray();

            if (!enumerable.Any())
            {
                return(input);
            }

            var body = _httpContextService.GetBody();

            return(enumerable
                   .Where(match => match.Groups.Count >= 2)
                   .Aggregate(input, (current, match) => current.Replace(match.Value, body)));
        }
コード例 #8
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result          = new ConditionCheckResultModel();
        var xpathConditions = stub.Conditions?.Xpath?.ToArray() ?? Array.Empty <StubXpathModel>();

        if (!xpathConditions.Any())
        {
            return(result);
        }

        var validXpaths = 0;
        var body        = _httpContextService.GetBody();

        try
        {
            var doc = new XmlDocument();
            doc.LoadXml(body);
            foreach (var condition in xpathConditions)
            {
                var nsManager  = new XmlNamespaceManager(doc.NameTable);
                var namespaces = condition.Namespaces;
                if (namespaces != null)
                {
                    foreach (var ns in namespaces)
                    {
                        nsManager.AddNamespace(ns.Key, ns.Value);
                    }
                }
                else
                {
                    // If no namespaces are defined, check the XML namespaces with a regex.
                    nsManager.ParseBodyAndAssignNamespaces(body);
                }

                var elements = doc.SelectNodes(condition.QueryString, nsManager);
                if (elements is { Count: 0 })
                {
                    // No suitable XML results found.
                    result.Log = $"No suitable XML results found with XPath query {condition.QueryString}.";
                    break;
                }

                validXpaths++;
            }
コード例 #9
0
    /// <inheritdoc />
    public ConditionCheckResultModel Validate(StubModel stub)
    {
        var result             = new ConditionCheckResultModel();
        var jsonPathConditions = stub.Conditions?.JsonPath?.ToArray();

        if (jsonPathConditions == null || jsonPathConditions?.Any() != true)
        {
            return(result);
        }

        var validJsonPaths = 0;
        var body           = _httpContextService.GetBody();
        var jsonObject     = JObject.Parse(body);

        foreach (var condition in jsonPathConditions)
        {
            if (condition is string conditionString)
            {
                // Condition is a string, so perform plain text JSONPath condition check.
                var elements = jsonObject.SelectToken(conditionString);
                if (elements == null)
                {
                    // No suitable JSON results found.
                    result.Log = $"No suitable JSON results found with JSONPath query '{conditionString}'.";
                    break;
                }

                validJsonPaths++;
            }
            else
            {
                // Condition is an object, so first convert the condition to a StubJsonPathModel before executing the condition checker.
                var jsonPathCondition = ConvertJsonPathCondition(stub.Id, condition);

                var passed = false;
                if (jsonPathCondition != null)
                {
                    var elements = jsonObject.SelectToken(jsonPathCondition.Query);
                    if (elements != null)
                    {
                        // Retrieve the value from the JSONPath result.
                        var foundValue = JsonUtilities.ConvertFoundValue(elements);

                        // If a value is set for the condition, check if the found JSONPath value matches the value in the condition.
                        passed = string.IsNullOrWhiteSpace(jsonPathCondition.ExpectedValue) ||
                                 StringHelper.IsRegexMatchOrSubstring(
                            foundValue,
                            jsonPathCondition.ExpectedValue);
                    }
                }

                if (!passed)
                {
                    result.Log = "No suitable JSON results found.";
                }

                validJsonPaths += passed ? 1 : 0;
            }
        }

        // If the number of succeeded conditions is equal to the actual number of conditions,
        // the header condition is passed and the stub ID is passed to the result.
        result.ConditionValidation = validJsonPaths == jsonPathConditions.Length
            ? ConditionValidationType.Valid
            : ConditionValidationType.Invalid;

        return(result);
    }
コード例 #10
0
        // ReSharper disable once UnusedMember.Global
        public async Task Invoke(HttpContext context)
        {
            var path = _httpContextService.Path;

            if (_segmentsToIgnore.Any(s => path.Contains(s, StringComparison.OrdinalIgnoreCase)))
            {
                await _next(context);

                return;
            }

            const string correlationHeaderKey = "X-HttPlaceholder-Correlation";
            var          correlation          = Guid.NewGuid().ToString();
            var          requestLogger        = _requestLoggerFactory.GetRequestLogger();

            requestLogger.SetCorrelationId(correlation);
            try
            {
                // Enable rewind here to be able to read the posted body multiple times.
                _httpContextService.EnableRewind();

                // Log the request here
                requestLogger.LogRequestParameters(
                    _httpContextService.Method,
                    _httpContextService.DisplayUrl,
                    _httpContextService.GetBody(),
                    _clientDataResolver.GetClientIp(),
                    _httpContextService.GetHeaders());

                _httpContextService.ClearResponse();
                _httpContextService.TryAddHeader(correlationHeaderKey, correlation);
                var response = await _stubRequestExecutor.ExecuteRequestAsync();

                _httpContextService.SetStatusCode(response.StatusCode);
                foreach (var(key, value) in response.Headers)
                {
                    _httpContextService.AddHeader(key, value);
                }

                if (response.Body != null)
                {
                    await _httpContextService.WriteAsync(response.Body);
                }
            }
            catch (RequestValidationException e)
            {
                _httpContextService.SetStatusCode((int)HttpStatusCode.InternalServerError);
                _httpContextService.TryAddHeader(correlationHeaderKey, correlation);
                _logger.LogInformation($"Request validation exception thrown: {e.Message}");
            }
            catch (Exception e)
            {
                _httpContextService.SetStatusCode((int)HttpStatusCode.InternalServerError);
                _httpContextService.TryAddHeader(correlationHeaderKey, correlation);
                _logger.LogWarning($"Unexpected exception thrown: {e}");
            }

            var loggingResult        = requestLogger.GetResult();
            var jsonLoggingResult    = JObject.FromObject(loggingResult);
            var enableRequestLogging = _settings.Storage?.EnableRequestLogging ?? false;

            if (enableRequestLogging)
            {
                _logger.LogInformation(jsonLoggingResult.ToString());
            }

            await _stubContext.AddRequestResultAsync(loggingResult);

            // We need to map the model to a DTO here, because the frontend expected that.
            await _requestNotify.NewRequestReceivedAsync(_mapper.Map <RequestResultDto>(loggingResult));
        }