public void MultipleItems() { string json = @"{ ""description"":""MultipleItems"", ""type"":""array"", ""items"": [{""type"":""string""},{""type"":""array""}] }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual("MultipleItems", schema.Description); Assert.AreEqual(JsonSchemaType.String, schema.Items[0].Type); Assert.AreEqual(JsonSchemaType.Array, schema.Items[1].Type); }
public void IdentityMultiple() { string json = @"{ ""description"":""Identity"", ""identity"":[""PurpleMonkeyDishwasher"",""Antelope""] }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json))); Assert.AreEqual("Identity", schema.Description); Assert.AreEqual(2, schema.Identity.Count); Assert.AreEqual("PurpleMonkeyDishwasher", schema.Identity[0]); Assert.AreEqual("Antelope", schema.Identity[1]); }
public void UnresolvedReference() { ExceptionAssert.Throws <Exception>(() => { string json = @"{ ""id"":""CircularReferenceArray"", ""description"":""CircularReference"", ""type"":[""array""], ""items"":{""$ref"":""MyUnresolvedReference""} }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); }, @"Could not resolve schema reference 'MyUnresolvedReference'."); }
public void PatternProperties() { string json = @"{ ""patternProperties"": { ""[abc]"": { ""id"":""Blah"" } } }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.IsNotNull(schema.PatternProperties); Assert.AreEqual(1, schema.PatternProperties.Count); Assert.AreEqual("Blah", schema.PatternProperties["[abc]"].Id); }
public void IndirectAttributeHandler() { AttributeHandler.RemoveHandler <CustomAttributeHandler>(); AttributeHandler.AddHandler <CustomAttributeHandler>(); JsonSchema expected = new JsonSchemaBuilder() .Type(SchemaValueType.Object) .Properties( ("MyProperty", new JsonSchemaBuilder().Type(SchemaValueType.String).MaxLength(AttributeWithIndirectHandler.MaxLength)) ); JsonSchema actual = new JsonSchemaBuilder().FromType <TypeWithCustomAttribute2>(); Assert.AreEqual(expected, actual); }
public void PropertiesAsDeclaredByType() { var config = new SchemaGeneratorConfiguration { PropertyOrder = PropertyOrder.AsDeclared }; JsonSchema schema = new JsonSchemaBuilder() .FromType <SpecifiedOrderDerived>(config); var properties = schema.Keywords.OfType <PropertiesKeyword>().Single(); Assert.AreEqual(nameof(SpecifiedOrder.Second), properties.Properties.Keys.ElementAt(0)); Assert.AreEqual(nameof(SpecifiedOrder.First), properties.Properties.Keys.ElementAt(1)); Assert.AreEqual(nameof(SpecifiedOrderDerived.Third), properties.Properties.Keys.ElementAt(2)); }
public void References_Array() { string json = @"{ ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], ""properties"": { ""array"": {""$ref"": ""#/array/0""}, ""arrayprop"": {""$ref"": ""#/array/1/prop""} } }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["array"].Type); Assert.AreEqual(JsonSchemaType.Object, schema.Properties["arrayprop"].Type); }
public void Issue85_RecursiveGeneration_PropertyAsListOfSelf() { JsonSchema expected = new JsonSchemaBuilder() .Type(SchemaValueType.Object) .Properties( (nameof(TestMenu.Name), new JsonSchemaBuilder() .Type(SchemaValueType.String) ), (nameof(TestMenu.Children), new JsonSchemaBuilder() .Type(SchemaValueType.Array) .Items(new JsonSchemaBuilder().Ref("#")) ) ); VerifyGeneration <TestMenu>(expected); }
/// <summary> /// Converts an object to an Avro generic record based on the supplied schema /// </summary> /// <param name="obj"></param> /// <param name="recordSchema"></param> /// <param name="customValueGetter"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public static AvroRecord ToAvroRecord <T>( this T obj, string recordSchema, ICustomValueGetter customValueGetter = null) where T : class { var typeSchema = new JsonSchemaBuilder().BuildSchema(recordSchema); if (!(typeSchema is RecordSchema)) { throw new ApplicationException("Invalid record schema"); } _customValueGetter = customValueGetter; return((AvroRecord)ToAvroRecord(obj, typeSchema)); }
public void References_IndexNotInteger() { string json = @"{ ""array"": [{""type"": ""integer""},{""prop"":{""type"": ""object""}}], ""properties"": { ""array"": {""$ref"": ""#/array/0""}, ""arrayprop"": {""$ref"": ""#/array/one""} } }"; ExceptionAssert.Throws <JsonException>(() => { JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); builder.Read(new JsonTextReader(new StringReader(json))); }, "Could not resolve schema reference '#/array/one'."); }
public void VerifyNameChanges(PropertyNamingMethod namingMethod, string expectedName) { var config = new SchemaGeneratorConfiguration { PropertyNamingMethod = namingMethod }; var expected = new JsonSchemaBuilder() .Type(SchemaValueType.Object) .Properties( (expectedName, new JsonSchemaBuilder().Type(SchemaValueType.String)) ) .Build(); var actual = new JsonSchemaBuilder().FromType <Target>(config).Build(); AssertEqual(expected, actual); }
public void Reference_NonStandardLocation() { string json = @"{ ""properties"": { ""bar"": {""$ref"": ""#/common/foo""}, ""foo"": {""$ref"": ""#/common/foo""} }, ""common"": { ""foo"": {""type"": ""integer""} } }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual(schema.Properties["foo"], schema.Properties["bar"]); }
public void TypeNullability(Nullability nullability, Type type, SchemaValueType valueType) { var config = new SchemaGeneratorConfiguration { Nullability = nullability }; var expected = new JsonSchemaBuilder() .Type(valueType) .Build(); var actual = new JsonSchemaBuilder() .FromType(type, config) .Build(); Assert.AreEqual(expected, actual); }
public void AdditionalProperties() { string json = @"{ ""description"":""AdditionalProperties"", ""type"":[""string"", ""integer""], ""additionalProperties"":{""type"":[""object"", ""boolean""]} }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual("AdditionalProperties", schema.Description); Assert.AreEqual( JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type ); }
public void CircularReference() { string json = @"{ ""id"":""CircularReferenceArray"", ""description"":""CircularReference"", ""type"":[""array""], ""items"":{""$ref"":""CircularReferenceArray""} }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual("CircularReference", schema.Description); Assert.AreEqual("CircularReferenceArray", schema.Id); Assert.AreEqual(JsonSchemaType.Array, schema.Type); Assert.AreEqual(schema, schema.Items[0]); }
public void Enum() { string json = @"{ ""description"":""Type"", ""type"":[""string"",""array""], ""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""] }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual("Type", schema.Description); Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Array, schema.Type); Assert.AreEqual(8, schema.Enum.Count); Assert.AreEqual("string", (string)schema.Enum[0]); Assert.AreEqual("any", (string)schema.Enum[schema.Enum.Count - 1]); }
private JsonSchema NormalizeSchema(JsonSchema schema) { if (schema.Keywords == null) { return(JsonSchema.True); } var builder = new JsonSchemaBuilder(); foreach (var keyword in schema.Keywords) { foreach (var kw in NormalizeKeyword(schema, keyword)) { builder.Add(kw); } } return(builder.Build()); }
public void EscapedReferences() { string json = @"{ ""tilda~field"": {""type"": ""integer""}, ""slash/field"": {""type"": ""object""}, ""percent%field"": {""type"": ""array""}, ""properties"": { ""tilda"": {""$ref"": ""#/tilda~0field""}, ""slash"": {""$ref"": ""#/slash~1field""}, ""percent"": {""$ref"": ""#/percent%25field""} } }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.AreEqual(JsonSchemaType.Integer, schema.Properties["tilda"].Type); Assert.AreEqual(JsonSchemaType.Object, schema.Properties["slash"].Type); Assert.AreEqual(JsonSchemaType.Array, schema.Properties["percent"].Type); }
public void Options() { string json = @"{ ""description"":""NZ Island"", ""type"":""string"", ""options"": [ {""value"":""NI"",""label"":""North Island""}, {""value"":""SI"",""label"":""South Island""} ] }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json))); Assert.AreEqual("NZ Island", schema.Description); Assert.AreEqual(JsonSchemaType.String, schema.Type); Assert.AreEqual(2, schema.Options.Count); Assert.AreEqual("North Island", schema.Options[new JValue("NI")]); Assert.AreEqual("South Island", schema.Options[new JValue("SI")]); }
public void WhenCompleteType_Validator_ValidationSucceeds() { var schema = new JsonSchemaBuilder() .WithNamespace("Unity.Properties.Samples.Schema") .WithContainer( new JsonSchemaBuilder.ContainerBuilder("HelloWorld", true) .WithProperty("Data", "int", "5") .WithProperty("Floats", "list", "", "float") .WithProperty("MyStruct", "SomeData") ) .ToJson(); object obj; if (!Properties.Serialization.Json.TryDeserializeObject(schema, out obj)) { return; } var validator = new JsonSchemaValidator(); Assert.IsTrue(validator.ValidatePropertyDefinition(obj as IDictionary <string, object>).IsValid); }
public void GivenDateTimeProperty_WhenUsingSchemaWithTimeAsTimestampMicroseconds_ThenShouldWork() { //Arrange var toSerialize = new ClassWithDateTime { ArriveBy = DateTime.UtcNow }; //Act var schema = Schema.Create(toSerialize); // Change schema logical type from timestamp-millis to timestamp-micros (a bit hacky) var schemaJson = schema.ToString().Replace(LogicalTypeSchema.LogicalTypeEnum.TimestampMilliseconds, LogicalTypeSchema.LogicalTypeEnum.TimestampMicroseconds); var microsecondsSchema = new JsonSchemaBuilder().BuildSchema(schemaJson); byte[] result; using (MemoryStream resultStream = new MemoryStream()) { using (var writer = new Encoder(microsecondsSchema, resultStream, CodecType.Null)) { writer.Append(toSerialize); } result = resultStream.ToArray(); } var avro2Json = AvroConvert.Avro2Json(result, microsecondsSchema.ToString()); var deserialized = JsonConvert.DeserializeObject <ClassWithDateTime>(avro2Json); //Assert Assert.NotNull(result); Assert.NotNull(deserialized); Assert.Equal(toSerialize.ArriveBy.Millisecond, deserialized.ArriveBy.Millisecond); Assert.Equal(toSerialize.ArriveBy.Second, deserialized.ArriveBy.Second); Assert.Equal(toSerialize.ArriveBy.Minute, deserialized.ArriveBy.Minute); Assert.Equal(toSerialize.ArriveBy.Hour, deserialized.ArriveBy.Hour); Assert.Equal(toSerialize.ArriveBy.Day, deserialized.ArriveBy.Day); Assert.Equal(toSerialize.ArriveBy.Month, deserialized.ArriveBy.Month); Assert.Equal(toSerialize.ArriveBy.Year, deserialized.ArriveBy.Year); }
public void RequiredArray() { string json = @"{ ""properties"": { ""firstProperty"": { ""type"" : ""string"" }, ""secondProperty"": { ""type"" : ""string"" }, ""thirdProperty"": { ""type"" : ""string"" }, }, ""required"": [ ""firstProperty"", ""thirdProperty"" ] }"; JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver()); JsonSchema schema = builder.Read(new JsonTextReader(new StringReader(json))); Assert.IsTrue(schema.Properties["firstProperty"].Required.Value); Assert.IsFalse(schema.Properties["secondProperty"].Required.HasValue); Assert.IsTrue(schema.Properties["thirdProperty"].Required.Value); }
public void TypesWithAnEvenNumberOfPropertiesShouldBeMutable() { var configuration = new SchemaGeneratorConfiguration { Refiners = { new Refiner() } }; JsonSchema expected = new JsonSchemaBuilder() .Type(SchemaValueType.Object) .Properties( ("Value1", new JsonSchemaBuilder().Type(SchemaValueType.Integer)), ("Value2", new JsonSchemaBuilder().Type(SchemaValueType.String)) ); JsonSchema actual = new JsonSchemaBuilder().FromType <TwoProps>(configuration); Console.WriteLine(JsonSerializer.Serialize(expected, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine(JsonSerializer.Serialize(actual, new JsonSerializerOptions { WriteIndented = true })); Assert.AreEqual(expected, actual); }
public void Issue85_RecursiveGeneration_PropertyAsListOfSelf() { JsonSchema expected = new JsonSchemaBuilder() .Type(SchemaValueType.Object) .Properties( (nameof(TestMenu.Name), new JsonSchemaBuilder() .Type(SchemaValueType.String) ), (nameof(TestMenu.Children), new JsonSchemaBuilder() .Type(SchemaValueType.Array) .Items(new JsonSchemaBuilder().Ref("#")) ) ); JsonSchema actual = new JsonSchemaBuilder().FromType <TestMenu>(); Console.WriteLine(JsonSerializer.Serialize(expected, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine(JsonSerializer.Serialize(actual, new JsonSerializerOptions { WriteIndented = true })); Assert.AreEqual(expected, actual); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.WriteOnly(Value); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.MultipleOf(Value); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.ReadOnly(Value); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.ExclusiveMaximum(Value); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.Type(Type); }
/// <summary> /// Applies the keyword to the <see cref="JsonSchemaBuilder"/>. /// </summary> /// <param name="builder">The builder.</param> public void Apply(JsonSchemaBuilder builder) { builder.UniqueItems(Value); }