/// <summary>
        /// Examines input json string to ensure that it compiles with the JsonSchema definition. Any errors in the
        /// validation of the schema are returned via the errors out parameter.
        /// </summary>
        /// <param name="schema">Schemas definition used as a reference.</param>
        /// <param name="inputJson">Input json example to be validated</param>
        /// <param name="issues"></param>
        /// <param name="expectedJson"></param>
        /// <returns></returns>
        public bool ValidateJsonCompilesWithSchema(JsonSchema schema, JsonExample inputJson, IssueLogger issues, JsonExample expectedJson = null, ValidationOptions options = null)
        {
            if (null == schema)
            {
                throw new ArgumentNullException("schema");
            }

            if (null == inputJson)
            {
                throw new ArgumentNullException("inputJson");
            }

            string collectionPropertyName = "value";

            if (null != inputJson.Annotation && null != inputJson.Annotation.CollectionPropertyName)
            {
                collectionPropertyName = inputJson.Annotation.CollectionPropertyName;
            }

            // If we didn't get an options, create a new one with some defaults provided by the annotation
            options = options ?? new ValidationOptions();

            var annotationTruncated = (inputJson.Annotation ?? new CodeBlockAnnotation()).TruncatedResult;

            options.AllowTruncatedResponses = annotationTruncated || options.AllowTruncatedResponses;
            options.CollectionPropertyName  = collectionPropertyName;

            return(schema.ValidateJson(inputJson, issues, this.registeredSchema, options, expectedJson));
        }
Exemple #2
0
        /// <summary>
        /// Checks that the expected response of a method definition is valid with this resource.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="issues"></param>
        /// <returns></returns>
        public bool ValidateExpectedResponse(MethodDefinition method, IssueLogger issues)
        {
            HttpParser parser   = new HttpParser();
            var        response = parser.ParseHttpResponse(method.ExpectedResponse);

            JsonExample example      = new JsonExample(response.Body, method.ExpectedResponseMetadata);
            var         otherSchemas = new Dictionary <string, JsonSchema>();

            return(this.ValidateJson(example, issues, otherSchemas, null));
        }
        /// <summary>
        /// Checks that the expected response of a method definition is valid with this resource.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="issues"></param>
        /// <returns></returns>
        public bool ValidateExpectedResponse(MethodDefinition method, IssueLogger issues)
        {
            HttpResponse response;

            HttpParser.TryParseHttpResponse(method.ExpectedResponse, out response, issues);
            if (response != null)
            {
                JsonExample example      = new JsonExample(response.Body, method.ExpectedResponseMetadata);
                var         otherSchemas = new Dictionary <string, JsonSchema>();
                return(this.ValidateJson(example, issues, otherSchemas, null));
            }
            return(false);
        }
Exemple #4
0
        /// <summary>
        /// Validate the input json against the defined scehma when the instance was created.
        /// </summary>
        /// <param name="jsonInput">Input json to validate against schema</param>
        /// <param name="issues"></param>
        /// <param name="otherSchemas"></param>
        /// <param name="options"></param>
        /// <param name="expectedJson"></param>
        /// <returns>True if validation was successful, otherwise false.</returns>
        public bool ValidateJson(JsonExample jsonInput, IssueLogger issues, Dictionary <string, JsonSchema> otherSchemas, ValidationOptions options, JsonExample expectedJson = null)
        {
            JContainer obj;

            try
            {
                var settings = new JsonSerializerSettings {
                    DateParseHandling = DateParseHandling.None, NullValueHandling = NullValueHandling.Include, DefaultValueHandling = DefaultValueHandling.Include
                };
                obj = (JContainer)JsonConvert.DeserializeObject(jsonInput.JsonData, settings);
            }
            catch (Exception ex)
            {
                issues.Error(ValidationErrorCode.JsonParserException, $"Failed to parse json string: {jsonInput.JsonData}.", ex);
                return(false);
            }

            var annotation = jsonInput.Annotation ?? new CodeBlockAnnotation();

            bool expectErrorObject = (jsonInput.Annotation != null) && jsonInput.Annotation.ExpectError;

            // Check for an error response
            try
            {
                dynamic errorObject = obj["error"];
                if (null != errorObject && !expectErrorObject)
                {
                    string code    = errorObject.code;
                    string message = errorObject.message;

                    issues.Error(ValidationErrorCode.JsonErrorObject, $"Error response received. Code: {code}, Message: {message}");
                    return(false);
                }
                else if (expectErrorObject && null == errorObject)
                {
                    issues.Error(ValidationErrorCode.JsonErrorObjectExpected, "Expected an error object response, but didn't receive one.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                if (annotation.ExpectError)
                {
                    issues.Error(ValidationErrorCode.JsonErrorObjectExpected, "Expected an error object, but it doesn't look like we got one.", ex);
                }
            }

            // Check to see if this is a "collection" instance
            if (null != annotation && annotation.IsCollection)
            {
                this.ValidateCollectionObject(obj, annotation, otherSchemas, options.CollectionPropertyName, issues, options);
            }
            // otherwise verify the object matches this schema
            else
            {
                options = options ?? new ValidationOptions(annotation);
                if (null != expectedJson)
                {
                    var expectedJsonSchema = new JsonSchema(expectedJson.JsonData, expectedJson.Annotation);
                    options.ExpectedJsonSchema    = expectedJsonSchema;
                    options.RequiredPropertyNames = expectedJsonSchema.ExpectedProperties.Keys.ToArray();
                }
                this.ValidateContainerObject(obj, options, otherSchemas, issues);
            }

            return(issues.Issues.Count() == 0);
        }