Esempio n. 1
0
        /// <summary>Deserializes a JSON string to a <see cref="JsonSchema4" />.</summary>
        /// <param name="data">The JSON string.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <returns>The JSON Schema.</returns>
        public static async Task <JsonSchema4> FromJsonAsync(string data, string documentPath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
        {
            var schemaType       = SchemaType.JsonSchema;
            var contractResolver = CreateJsonSerializerContractResolver(schemaType);

            return(await JsonSchemaSerialization.FromJsonAsync(data, schemaType, documentPath, referenceResolverFactory, contractResolver));
        }
Esempio n. 2
0
        public void When_schema_is_serialized_for_Swagger_then_discriminator_is_string()
        {
            //// Arrange
            var childSchema = new JsonSchema4
            {
                Type = JsonObjectType.Object,
            };

            var schema = new JsonSchema4();

            schema.Definitions["Foo"]  = childSchema;
            schema.DiscriminatorObject = new OpenApiDiscriminator
            {
                PropertyName = "discr",
                Mapping      =
                {
                    {
                        "Bar",
                        new JsonSchema4
                        {
                            Reference = childSchema
                        }
                    }
                }
            };

            //// Act
            var json = JsonSchemaSerialization.ToJson(schema, SchemaType.Swagger2, new DefaultContractResolver(), Formatting.Indented);

            //// Assert
            Assert.Contains(@"""discriminator"": ""discr""", json);
            Assert.DoesNotContain(@"""Bar"": ""#/definitions/Foo""", json);
        }
Esempio n. 3
0
        /// <summary>Converts the description object to JSON.</summary>
        /// <param name="schemaType">The schema type.</param>
        /// <returns>The JSON string.</returns>
        public string ToJson(SchemaType schemaType)
        {
            GenerateOperationIds();

            var contractResolver = CreateJsonSerializerContractResolver(schemaType);

            return(JsonSchemaSerialization.ToJson(this, schemaType, contractResolver));
        }
Esempio n. 4
0
        /// <summary>Converts the description object to JSON.</summary>
        /// <param name="schemaType">The schema type.</param>
        /// <param name="formatting">The formatting.</param>
        /// <returns>The JSON string.</returns>
        public string ToJson(SchemaType schemaType, Formatting formatting)
        {
            GenerateOperationIds();

            var contractResolver = GetJsonSerializerContractResolver(schemaType);

            return(JsonSchemaSerialization.ToJson(this, schemaType, contractResolver, formatting));
        }
Esempio n. 5
0
        public async Task When_inheritance_with_object_without_props_is_generated_then_all_classes_exist_and_additional_properties_property_is_not_generated()
        {
            // Arrange
            var json = @"{
  ""type"": ""object"",
  ""properties"": {
    ""Exception"": {
      ""$ref"": ""#/definitions/BusinessException""
    }
  },
  ""additionalProperties"": false,
  ""definitions"": {
    ""BusinessException"": {
      ""type"": ""object"",
      ""additionalProperties"": false,
      ""properties"": {
        ""customerId"": {
          ""type"": ""string"",
          ""nullable"": true
        },
        ""customerAlias"": {
          ""type"": ""string"",
          ""nullable"": true
        },
        ""userId"": {
          ""type"": ""string"",
          ""nullable"": true
        }
      }
    },
    ""ValidationException"": {
      ""allOf"": [
        {
          ""$ref"": ""#/definitions/BusinessException""
        },
        {
          ""type"": ""object"",
          ""additionalProperties"": false
        }
      ]
    }
  }
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, SchemaType.OpenApi3, null, factory, new DefaultContractResolver());

            // Act
            var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
                SchemaType = SchemaType.OpenApi3
            });
            var code = generator.GenerateFile("MyClass");

            //// Act
            Assert.Contains("class BusinessException", code);
            Assert.Contains("class ValidationException", code);
            Assert.DoesNotContain("AdditionalProperties", code);
        }
        public async Task When_schema_JSON_is_deserialized_then_AllowAdditionalProperties_is_correct(SchemaType schemaType, string json, bool expectedAllowAdditionalProperties)
        {
            //// Act
            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            //// Assert
            Assert.Equal(expectedAllowAdditionalProperties, schema.AllowAdditionalProperties);
        }
Esempio n. 7
0
        /// <summary>Serializes the <see cref="JsonSchema4" /> to a JSON string.</summary>
        /// <param name="formatting">The formatting.</param>
        /// <returns>The JSON string.</returns>
        public string ToJson(Formatting formatting)
        {
            var oldSchema = SchemaVersion;
            SchemaVersion = "http://json-schema.org/draft-04/schema#";

            var json = JsonSchemaSerialization.ToJson(this, SerializationSchemaType, ContractResolver.Value, formatting);

            SchemaVersion = oldSchema;
            return json;
        }
        public void When_AllowAdditionalProperties_is_true_then_JSON_is_correct(SchemaType schemaType, bool allowAdditionalProperties, string expectedJson)
        {
            //// Act
            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var json    = JsonSchemaSerialization.ToJson(new JsonSchema {
                AllowAdditionalProperties = allowAdditionalProperties
            }, schemaType, new DefaultContractResolver(), Formatting.None);

            //// Assert
            Assert.Equal(expectedJson, json);
        }
        public void When_default_schema_is_serialized_then_AllowAdditionalProperties_is_correct(SchemaType schemaType, string expectedJson)
        {
            // default schema (new JsonSchema) has always AllowAdditionalProperties = true

            //// Act
            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var json    = JsonSchemaSerialization.ToJson(new JsonSchema(), schemaType, new DefaultContractResolver(), Formatting.None);

            //// Assert
            Assert.Equal(expectedJson, json);
        }
Esempio n. 10
0
        /// <summary>Serializes the <see cref="JsonSchema4" /> to a JSON string.</summary>
        /// <returns>The JSON string.</returns>
        public string ToJson()
        {
            var oldSchema = SchemaVersion;

            SchemaVersion = "http://json-schema.org/draft-04/schema#";

            var schemaType       = SchemaType.JsonSchema;
            var contractResolver = CreateJsonSerializerContractResolver(schemaType);
            var json             = JsonSchemaSerialization.ToJson(this, schemaType, contractResolver);

            SchemaVersion = oldSchema;
            return(json);
        }
Esempio n. 11
0
        public void When_property_is_renamed_then_it_does_not_land_in_extension_data()
        {
            //// Arrange
            var resolver = new PropertyRenameAndIgnoreSerializerContractResolver();

            resolver.RenameProperty(typeof(JsonSchemaProperty), "x-readOnly", "readOnly");
            resolver.RenameProperty(typeof(JsonSchema), "x-nullable", "nullable");

            var json = "{ \"readOnly\": true, \"nullable\": true, \"additionalProperties\": { \"nullable\": true } }";

            //// Act
            var obj = JsonSchemaSerialization.FromJson <JsonSchemaProperty>(json, resolver);

            //// Assert
            Assert.True(obj.IsReadOnly);
            Assert.True(obj.IsNullableRaw);
            Assert.True(obj.AdditionalPropertiesSchema.IsNullableRaw);
        }
Esempio n. 12
0
        /// <summary>Creates a Swagger specification from a JSON string.</summary>
        /// <param name="data">The JSON data.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="expectedSchemaType">The expected schema type which is used when the type cannot be determined.</param>
        /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The <see cref="OpenApiDocument"/>.</returns>
        public static async Task <OpenApiDocument> FromJsonAsync(string data, string documentPath, SchemaType expectedSchemaType,
                                                                 Func <OpenApiDocument, JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
        {
            // For explanation of the regex use https://regexr.com/ and the below unescaped pattern that is without named groups
            // (?:\"(openapi|swagger)\")(?:\s*:\s*)(?:\"([^"]*)\")
            var pattern = "(?:\\\"(?<schemaType>openapi|swagger)\\\")(?:\\s*:\\s*)(?:\\\"(?<schemaVersion>[^\"]*)\\\")";
            var match   = Regex.Match(data, pattern, RegexOptions.IgnoreCase);

            if (match.Success)
            {
                var schemaType    = match.Groups["schemaType"].Value.ToLower();
                var schemaVersion = match.Groups["schemaVersion"].Value.ToLower();

                if (schemaType == "swagger" && schemaVersion.StartsWith("2"))
                {
                    expectedSchemaType = SchemaType.Swagger2;
                }
                else if (schemaType == "openapi" && schemaVersion.StartsWith("3"))
                {
                    expectedSchemaType = SchemaType.OpenApi3;
                }
            }

            if (expectedSchemaType == SchemaType.JsonSchema)
            {
                throw new NotSupportedException("The schema type JsonSchema is not supported.");
            }

            var contractResolver = GetJsonSerializerContractResolver(expectedSchemaType);

            return(await JsonSchemaSerialization.FromJsonAsync <OpenApiDocument>(data, expectedSchemaType, documentPath, document =>
            {
                document.SchemaType = expectedSchemaType;
                if (referenceResolverFactory != null)
                {
                    return referenceResolverFactory(document);
                }
                else
                {
                    var schemaResolver = new OpenApiSchemaResolver(document, new JsonSchemaGeneratorSettings());
                    return new JsonReferenceResolver(schemaResolver);
                }
            }, contractResolver, cancellationToken).ConfigureAwait(false));
        }
Esempio n. 13
0
        public async Task When_date_reference_is_generated_from_swagger2_schema_then_generated_member_is_decorated_with_date_format_attribute()
        {
            // Arrange
            var json = @"{
  ""type"": ""object"",
  ""properties"": {
    ""MyType"": {
      ""$ref"": ""#/definitions/MyType""
    }
  },
  ""additionalProperties"": false,
	""definitions"": {
		""MyType"": {
			""type"": ""object"",
			""required"": [
				""EntryDate"",
			],
			""properties"": {
			    ""EntryDate"": {
				    ""$ref"": ""#/definitions/EntryDate""
				}
			}
		},
		""EntryDate"": {
			""example"": ""2020-08-28"",
			""type"": ""string"",
			""format"": ""date""
		}
	}
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, SchemaType.Swagger2, null, factory, new DefaultContractResolver());

            // Act
            var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings {
                SchemaType = SchemaType.Swagger2
            });
            var code = generator.GenerateFile("MyClass");

            //// Act
            Assert.Contains("[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]", code);
        }
Esempio n. 14
0
        public async Task WriteJsonSchemaAsync <T>(IFile file)
        {
            await using (var stream = file.OpenWrite())
            {
                await using (var textWriter = new StreamWriter(stream))
                {
                    var jsonSchema     = GetSchema <T>();
                    var jsonSchemaType = jsonSchemaGeneratorSettings.SchemaType;

                    var json = JsonSchemaSerialization.ToJson(
                        jsonSchema,
                        jsonSchemaType,
                        JsonSchema.CreateJsonSerializerContractResolver(jsonSchemaType),
                        Formatting.Indented);

                    await textWriter.WriteAsync(json);
                }
            }
        }
Esempio n. 15
0
        /// <summary>Creates a Swagger specification from a JSON string.</summary>
        /// <param name="data">The JSON data.</param>
        /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
        /// <param name="expectedSchemaType">The expected schema type which is used when the type cannot be determined.</param>
        /// <returns>The <see cref="SwaggerDocument"/>.</returns>
        public static async Task <SwaggerDocument> FromJsonAsync(string data, string documentPath = null, SchemaType expectedSchemaType = SchemaType.Swagger2)
        {
            if (data.Contains(@"""swagger"": ""2"))
            {
                expectedSchemaType = SchemaType.Swagger2;
            }
            else if (data.Contains(@"""openapi"": ""3"))
            {
                expectedSchemaType = SchemaType.OpenApi3;
            }
            else if (expectedSchemaType == SchemaType.JsonSchema)
            {
                throw new NotSupportedException("The schema type JsonSchema is not supported.");
            }

            var contractResolver = CreateJsonSerializerContractResolver(expectedSchemaType);

            return(await JsonSchemaSerialization.FromJsonAsync <SwaggerDocument>(data, expectedSchemaType, documentPath, document =>
            {
                var schemaResolver = new SwaggerSchemaResolver(document, new JsonSchemaGeneratorSettings());
                return new JsonReferenceResolver(schemaResolver);
            }, contractResolver).ConfigureAwait(false));
        }
Esempio n. 16
0
 /// <summary>Deserializes a JSON string to a <see cref="JsonSchema" />.</summary>
 /// <param name="data">The JSON string.</param>
 /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
 /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
 /// <param name="cancellationToken">The cancellation token</param>
 /// <returns>The JSON Schema.</returns>
 public static async Task <JsonSchema> FromJsonAsync(string data, string documentPath, Func <JsonSchema,
                                                                                             JsonReferenceResolver> referenceResolverFactory, CancellationToken cancellationToken = default)
 {
     return(await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value, cancellationToken).ConfigureAwait(false));
 }
Esempio n. 17
0
 /// <summary>Deserializes a JSON string to a <see cref="JsonSchema4" />.</summary>
 /// <param name="data">The JSON string.</param>
 /// <param name="documentPath">The document path (URL or file path) for resolving relative document references.</param>
 /// <param name="referenceResolverFactory">The JSON reference resolver factory.</param>
 /// <returns>The JSON Schema.</returns>
 public static async Task <JsonSchema4> FromJsonAsync(string data, string documentPath, Func <JsonSchema4, JsonReferenceResolver> referenceResolverFactory)
 {
     return(await JsonSchemaSerialization.FromJsonAsync(data, SerializationSchemaType, documentPath, referenceResolverFactory, ContractResolver.Value));
 }
Esempio n. 18
0
        public async Task When_schema_with_inheritance_and_references_is_generated_then_there_are_no_duplicates(SchemaType schemaType)
        {
            var json = @"
{
    ""type"": ""object"",
    ""properties"": {
        ""foo"": {
            ""$ref"": ""#/definitions/Teacher""
        }
    },
    ""definitions"": {
        ""Person"": {
            ""type"": ""object"",
            ""discriminator"": ""discriminator"",
            ""required"": [
                ""discriminator""
            ],
            ""properties"": {
                ""Skills"": {
                    ""type"": ""object"",
                    ""additionalProperties"": {
                        ""$ref"": ""#/definitions/SkillLevel""
                    }
                },
                ""discriminator"": {
                    ""type"": ""string""
                }
            }
        },
        ""SkillLevel"": {
            ""type"": ""integer"",
            ""description"": """",
            ""x-enumNames"": [
                ""Low"",
                ""Medium"",
                ""Height""
            ],
            ""enum"": [
                0,
                1,
                2
            ]
        },
        ""Teacher"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/Person""
                },
                {
                    ""type"": ""object"",
                    ""required"": [
                        ""SkillLevel""
                    ],
                    ""properties"": {
                        ""Course"": {
                            ""type"": ""string""
                        },
                        ""SkillLevel"": {
                            ""default"": 1,
                            ""allOf"": [
                                {
                                    ""$ref"": ""#/definitions/SkillLevel""
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }
}
";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings {
                TypeScriptVersion = 2.0m, SchemaType = schemaType
            });

            //// Act
            var code = generator.GenerateFile();

            //// Assert
            Assert.DoesNotContain("SkillLevel2", code);
        }
Esempio n. 19
0
        public async Task When_schema_with_inheritance_to_object_type_is_generated_then_the_object_type_is_generated(SchemaType schemaType)
        {
            var json = @"{
    ""type"": ""object"",
    ""properties"": {
        ""request1"": {
            ""$ref"": ""#/definitions/GenericRequest1""
        },
        ""request2"": {
            ""$ref"": ""#/definitions/GenericRequest2""
        }
    },
    ""definitions"": {
        ""GenericRequest1"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/GenericRequestBaseOfRequestBodyBase""
                },
                {
                    ""type"": ""object""
                }
            ]
        },
        ""GenericRequestBaseOfRequestBodyBase"": {
            ""type"": ""object"",
            ""required"": [
                ""Request""
            ],
            ""properties"": {
                ""Request"": {
                    ""$ref"": ""#/definitions/RequestBodyBase""
                }
            }
        },
        ""RequestBodyBase"": {
            ""type"": ""object""
        },
        ""GenericRequest2"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/GenericRequestBaseOfRequestBody""
                },
                {
                    ""type"": ""object""
                }
            ]
        },
        ""GenericRequestBaseOfRequestBody"": {
            ""type"": ""object"",
            ""required"": [
                ""Request""
            ],
            ""properties"": {
                ""Request"": {
                    ""$ref"": ""#/definitions/RequestBody""
                }
            }
        },
        ""RequestBody"": {
            ""allOf"": [
                {
                    ""$ref"": ""#/definitions/RequestBodyBase""
                },
                {
                    ""type"": ""object""
                }
            ]
        }
    }
}";

            var factory = JsonReferenceResolver.CreateJsonReferenceResolverFactory(new DefaultTypeNameGenerator());
            var schema  = await JsonSchemaSerialization.FromJsonAsync(json, schemaType, null, factory, new DefaultContractResolver());

            var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings {
                TypeScriptVersion = 2.0m, SchemaType = schemaType
            });

            //// Act
            var code = generator.GenerateFile();

            //// Assert
            Assert.DoesNotContain("request!: any;", code);
            Assert.DoesNotContain("request: any;", code);
            Assert.Contains("this.request = new RequestBodyBase()", code);
            Assert.Contains("this.request = new RequestBody()", code);
        }