public async Task When_generating_interface_contract_add_discriminator_string_literal() { //// Arrange var schema = JsonSchema.FromType<Nested>(new JsonSchemaGeneratorSettings { GenerateAbstractProperties = true, }); var data = schema.ToJson(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Interface, TypeScriptVersion = 1.8m, EnumStyle = TypeScriptEnumStyle.StringLiteral, }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("export interface Base {\n Type: EBase;\n}", code); }
public async Task When_classes_have_extension_code_then_class_body_is_copied() { //// Arrange var schema = JsonSchema.FromType <Foo>(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { ExtendedClasses = new[] { "Foo", "Bar" }, ExtensionCode = Code }); var code = generator.GenerateFile(); //// Assert Assert.DoesNotContain("FooBase", code); Assert.DoesNotContain("BarBase", code); Assert.DoesNotContain("generated.", code); Assert.Contains("return this.firstName + ' ' + this.lastName;", code); Assert.Contains("return this.bar ? this.bar.title : '';", code); }
public void FirstPersonTest() { var model = new glTF_VRM_Firstperson(); var json = model.ToJson(); Assert.AreEqual( @"{""firstPersonBone"":-1,""firstPersonBoneOffset"":{""x"":0,""y"":0,""z"":0},""meshAnnotations"":[],""lookAtTypeName"":""Bone"",""lookAtHorizontalInner"":{""xRange"":90,""yRange"":10},""lookAtHorizontalOuter"":{""xRange"":90,""yRange"":10},""lookAtVerticalDown"":{""xRange"":90,""yRange"":10},""lookAtVerticalUp"":{""xRange"":90,""yRange"":10}}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTF_VRM_Firstperson>().Serialize(model, c); Assert.AreEqual( @"{""firstPersonBoneOffset"":{""x"":0,""y"":0,""z"":0},""meshAnnotations"":[],""lookAtTypeName"":""Bone"",""lookAtHorizontalInner"":{""xRange"":90,""yRange"":10},""lookAtHorizontalOuter"":{""xRange"":90,""yRange"":10},""lookAtVerticalDown"":{""xRange"":90,""yRange"":10},""lookAtVerticalUp"":{""xRange"":90,""yRange"":10}}", json2); }
public async Task When_name_of_JsonPropertyAttribute_is_set_then_it_is_used_as_json_property_name_even_with_contactresolver_that_has_nameing_strategy() { var settings = new NJsonSchema.Generation.JsonSchemaGeneratorSettings(); settings.SerializerSettings = new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver { NamingStrategy = new Newtonsoft.Json.Serialization.CamelCaseNamingStrategy() } }; //// Arrange var schema = JsonSchema.FromType <JsonPropertyAttributeTests.MyJsonPropertyTestClass>(settings); //// Act var property = schema.Properties["NewName"]; //// Assert Assert.Equal("NewName", property.Name); }
public async Task When_dictionary_key_is_string_literal_then_typescript_has_string_literal_key_ts_2_1() { //// Arrange var schema = JsonSchema.FromType <EnumKeyDictionaryTest>(); var data = schema.ToJson(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { TypeStyle = TypeScriptTypeStyle.Interface, EnumNameGenerator = new DefaultEnumNameGenerator(), EnumStyle = TypeScriptEnumStyle.StringLiteral, TypeScriptVersion = 2.1m, }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("export type PropertyName = 0 | 1;", code); Assert.Contains("Mapping: { [key in PropertyName]?: string; } | undefined;", code); Assert.Contains("Mapping2: { [key in PropertyName]?: string; } | undefined;", code); }
public async Task When_property_is_required_then_required_attribute_is_rendered() { //// Arrange var schema = JsonSchema.FromType <ClassWithRequiredObject>(); var schemaData = schema.ToJson(); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, SchemaType = SchemaType.JsonSchema }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("[System.ComponentModel.DataAnnotations.Required]\n" + " public string Property { get; set; }\n", code); Assert.Contains("[System.ComponentModel.DataAnnotations.Required(AllowEmptyStrings = true)]\n" + " public string Property2 { get; set; }\n", code); }
public byte[] ToGlbBytes(bool UseUniJSONSerializer = false) { string json; if (UseUniJSONSerializer) { var c = new JsonSchemaValidationContext(this) { EnableDiagnosisForNotRequiredFields = true, }; json = JsonSchema.FromType(GetType()).Serialize(this, c); } else { json = ToJson(); } RemoveUnusedExtensions(json); return(Glb.ToBytes(json, buffers[0].GetBytes())); }
public async Task When_property_is_not_required_then_required_attribute_is_not_rendered_in_Swagger_mode() { //// Arrange var schema = JsonSchema.FromType <ClassWithoutRequiredObject>(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.Swagger2 }); var schemaData = schema.ToJson(); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, SchemaType = SchemaType.Swagger2 }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.DoesNotContain("[Required]", code); Assert.Contains("public string Property { get; set; }", code); }
public void MaterialTest() { var model = new glTFMaterial() { name = "a", emissiveFactor = new float[] { 0.5f, 0.5f, 0.5f }, }; var json = model.ToJson(); Assert.AreEqual(@"{""name"":""a"",""emissiveFactor"":[0.5,0.5,0.5],""doubleSided"":false}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTFMaterial>().Serialize(model, c); Assert.AreEqual(@"{""name"":""a"",""emissiveFactor"":[0.5,0.5,0.5],""doubleSided"":false}", json2); }
public void SkinTest() { var model = new glTFSkin() { name = "b", joints = new int[] { 1 }, }; var json = model.ToJson(); Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1]}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTFSkin>().Serialize(model, c); Assert.AreEqual(@"{""joints"":[1],""name"":""b""}", json2); }
public void ProcessIncludesDefaultRuleNotNull() { // Arrange var jsonSchemaGeneratorSettings = CreateJsonSchemaGeneratorSettings(); // Act var schema = JsonSchema.FromType <MockValidationTarget>(jsonSchemaGeneratorSettings); // Assert Assert.Contains("NotNull", schema.RequiredProperties); var test = schema.Properties["NotNull"]; var value = test.IsNullable(SchemaType.OpenApi3); Assert.False(value); var notNullChildProperty = schema.Properties["NotNullChild"]; Assert.Empty(notNullChildProperty.OneOf); Assert.NotNull(notNullChildProperty.Reference); }
public async Task When_parameter_is_abstract_then_generate_union_class() { //// Arrange var schema = JsonSchema.FromType <Nested>(); var data = schema.ToJson(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { UseLeafType = true, TypeStyle = TypeScriptTypeStyle.Class, TypeScriptVersion = 1.8m }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("export class OneChild extends Base", code); Assert.Contains("export class SecondChild extends Base", code); Assert.Contains("child: OneChild | SecondChild;", code); Assert.Contains("children: OneChild[] | SecondChild[];", code); }
public byte[] ToGlbBytes(bool UseUniJSONSerializer = false) { string json; if (UseUniJSONSerializer) { json = JsonSchema.FromType(GetType()).Serialize(this); } else { json = ToJson(); } var buffer = buffers[0]; using (var s = new MemoryStream()) { GlbHeader.WriteTo(s); var pos = s.Position; s.Position += 4; // skip total size int size = 12; { var chunk = new GlbChunk(json); size += chunk.WriteTo(s); } { var chunk = new GlbChunk(buffer.GetBytes()); size += chunk.WriteTo(s); } s.Position = pos; var bytes = BitConverter.GetBytes(size); s.Write(bytes, 0, bytes.Length); return(s.ToArray()); } }
public void ExtensionsTest() { var model = new glTF_VRM_extensions() { meta = null, humanoid = null, firstPerson = null, blendShapeMaster = null, secondaryAnimation = null, materialProperties = null, }; var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTF_VRM_extensions>().Serialize(model, c); var expected = String.Format(@"{{""exporterVersion"":""{0}"",""specVersion"":""0.0""}}", VRMVersion.VRM_VERSION); Assert.AreEqual(expected, json2); }
private static JsonSchema CreateAddonAdapter(JsonSchema docSchema, IProviderProcessorAdapter inputOutputAdapter) { var connectionParameterSchema = JsonSchema .FromType(inputOutputAdapter.ConnectionParametersType) .AddAsDefinition(docSchema); var adapterSchema = JsonSchemaEx .CreateObject($"Adapter_{inputOutputAdapter.Name}") .AddProperty("Type", new JsonSchemaProperty { Pattern = $"^{inputOutputAdapter.Name}$" }, true) .AddProperty("Connection", connectionParameterSchema, false); if (inputOutputAdapter.ProviderParametersType != null) { var providerParameterSchema = JsonSchema .FromType(inputOutputAdapter.ProviderParametersType) .AddStringProperty("Name", false); var providersSchema = JsonSchemaEx .CreateDictionary($"Sources_{inputOutputAdapter.Name}", providerParameterSchema) .AddAsDefinition(docSchema); adapterSchema .AddProperty("Providers", providersSchema, false); } if (inputOutputAdapter.ProcessorParametersType != null) { var processorParameterSchema = JsonSchema .FromType(inputOutputAdapter.ProcessorParametersType) .AddStringProperty("Name", false); var processorsSchema = JsonSchemaEx .CreateDictionary($"Processes_{inputOutputAdapter.Name}", processorParameterSchema) .AddAsDefinition(docSchema); adapterSchema .AddProperty("Processors", processorsSchema, false); } return(adapterSchema.AddAsDefinition(docSchema)); }
public void ProcessIncludesDefaultRuleNotEmpty() { // Arrange var jsonSchemaGeneratorSettings = CreateJsonSchemaGeneratorSettings(); // Act var schema = JsonSchema.FromType <MockValidationTarget>(jsonSchemaGeneratorSettings); // Assert Assert.Equal(1, schema.Properties["NotEmpty"].MinLength); Assert.False(schema.Properties["NotEmpty"].IsNullable(SchemaType.OpenApi3)); var notEmptyChildProperty = schema.Properties["NotEmptyChild"]; Assert.Empty(notEmptyChildProperty.OneOf); Assert.NotNull(notEmptyChildProperty.Reference); // Unable to get this to work right now // var notEmptyChildPropertyEnum = schema.Properties["NotEmptyChildEnum"]; // Assert.Empty(notEmptyChildPropertyEnum.OneOf); // Assert.NotNull(notEmptyChildPropertyEnum.Reference); }
public void GetByCEPAsync_ResponseSchema_Test(string cep) { var httpClientMock = "https://viacep.com.br/ws/"; string schema = JsonSchema.FromType <ViaCEP>(new JsonSchemaGeneratorSettings() { AlwaysAllowAdditionalObjectProperties = true }).ToJson(); new RestAssured() .Given() .Name("VIA Cep Teste") .Header("Content-Type", "text/html; charset=utf-8") .Header("Accept-Encoding", "gzip,deflate") .When() .Get($"{httpClientMock}{cep}/json/") .Then() //.Debug() .Schema(schema) .WriteAssertions() .AssertSchema(); }
public void NodeTest() { var model = new glTFNode() { name = "a", skin = 0, camera = -1, }; var json = model.ToJson(); Assert.AreEqual(@"{""name"":""a"",""skin"":0}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTFNode>().Serialize(model, c); Assert.AreEqual(@"{""name"":""a"",""extras"":{}}", json2); }
public async Task When_string_and_integer_enum_used_then_one_enum_is_generated_in_CSharp() { //// Arrange var schema = JsonSchema.FromType <StringAndIntegerEnumTestClass>(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer }); var data = schema.ToJson(); //// Act var generator = new CSharpGenerator(schema); var code = generator.GenerateFile("MyClass").Replace("\r", ""); //// Assert Assert.DoesNotContain("Ref_", code); Assert.Contains("public enum Bar\n", code); Assert.Contains("public enum Bar2\n", code); Assert.Contains(" B = 5,", code); // B must be 5 even if B = 1 is first defined Assert.Equal(3, code.Split(new[] { "public enum " }, StringSplitOptions.None).Count()); // two found (one string and one integer based enum) Assert.Equal(3, code.Split(new[] { "[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]" }, StringSplitOptions.None).Count()); // two found }
public async Task When_GenerateConstructorInterface_is_disabled_then_data_is_not_checked_and_default_initialization_is_always_exectued() { // Assert var schema = JsonSchema.FromType( typeof(MyDerivedClass), new JsonSchemaGeneratorSettings { GenerateAbstractProperties = true }); var generator = new TypeScriptGenerator(schema); generator.Settings.GenerateConstructorInterface = false; generator.Settings.MarkOptionalProperties = true; generator.Settings.TypeStyle = TypeScriptTypeStyle.Class; // Act var output = generator.GenerateFile(); // Assert Assert.DoesNotContain("if (!data) {", output); }
public void SecondaryAnimationColliderTest() { var model = new glTF_VRM_SecondaryAnimationCollider() { offset = new Vector3(1, 2, 3), radius = 42, }; var json = model.ToJson(); Assert.AreEqual(@"{""offset"":{""x"":1,""y"":2,""z"":3},""radius"":42}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTF_VRM_SecondaryAnimationCollider>().Serialize(model, c); // NOTE: New serializer outputs values which will not be used... Assert.AreEqual(json, json2); }
public async Task When_property_is_optional_and_GenerateNullableOptionalProperties_is_set_then_CSharp_property_is_nullable() { //// Arrange var schema = JsonSchema.FromType <ClassWithRequiredObject>(new JsonSchemaGeneratorSettings { SchemaType = SchemaType.OpenApi3 }); var schemaData = schema.ToJson(); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, SchemaType = SchemaType.OpenApi3, GenerateNullableReferenceTypes = true }); var code = generator.GenerateFile("MyClass"); //// Assert Assert.Contains("public object? Property { get; set; }= default!;", code); Assert.Contains("public object Property2 { get; set; }= default!;", code); }
public void BlendShapeBindTest() { var model = new glTF_VRM_BlendShapeBind() { mesh = 1, weight = 2, index = 3, }; var json = model.ToJson(); Assert.AreEqual(@"{""mesh"":1,""index"":3,""weight"":2}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTF_VRM_BlendShapeBind>().Serialize(model, c); Assert.AreEqual(json, json2); }
public SchemaDefinition GetSchema(Type type, Func <Type, string> topicResolver) { if (topicResolver == null) { throw new ArgumentException("topicResolver", "TopicResolver must be specified"); } if (type == null) { throw new ArgumentException("type", "Type must be specified"); } var schema = JsonSchema.FromType(type); var jsonSchema = schema.ToJson(); var topic = topicResolver(type); var sampleBuilder = new SampleBuilder(); var obj = sampleBuilder.GetSampleFromType(type); var sample = obj != null?JsonConvert.SerializeObject(obj) : string.Empty; return(new SchemaDefinition(type.Name, type.FullName, jsonSchema, topic, sample)); }
public JsonSchema GetSchema(Type t, HttpDataSerializerOptions options, bool useStringEnums, bool requireReferenceTypes) { var settings = GetSchemaSerializationSettings(useStringEnums); JsonSchema schema = JsonSchema.FromType(t, new JsonSchemaGeneratorSettings { FlattenInheritanceHierarchy = true, AlwaysAllowAdditionalObjectProperties = AllowAdditionalPropertiesForJsonSchemaValidation(options), GenerateEnumMappingDescription = true, DefaultReferenceTypeNullHandling = requireReferenceTypes ? ReferenceTypeNullHandling.NotNull : ReferenceTypeNullHandling.Null, SerializerSettings = settings, ReflectionService = new CustomReflectionService(), TypeMappers = new List <ITypeMapper> { new TokenStringTypeMapper(), new TokenDateTypeMapper(), new ClientTokenStringTypeMapper(), new ClientTokenDateTypeMapper() } }); return(schema); }
public async Task When_property_is_string_enum_then_schema_has_enum() { //// Arrange //// Act var schema = JsonSchema.FromType <Foo>(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.String, GenerateEnumMappingDescription = true }); var data = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.String, schema.Properties["Bar"].ActualTypeSchema.Type); Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.Enumeration.Count); Assert.Equal("A", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0)); Assert.Equal("B", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1)); Assert.Equal("C", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2)); Assert.DoesNotContain("=", schema.Properties["Bar"].ActualTypeSchema.Description); // string enums do not have mapping in description }
public async Task When_constructor_interface_and_conversion_code_is_generated_then_it_is_correct() { //// Arrange var schema = JsonSchema.FromType <Person>(new JsonSchemaGeneratorSettings()); var json = schema.ToJson(); //// Act var generator = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings { GenerateConstructorInterface = true, ConvertConstructorInterfaceData = true, TypeScriptVersion = 1.8m }); var output = generator.GenerateFile("MyClass"); //// Assert Assert.DoesNotContain("new MyClass(", output); // address property is converted: Assert.Contains("this.address = data.address && !(<any>data.address).toJSON ? new Address(data.address) : <Address>this.address;", output); // cars items are converted: Assert.Contains("this.cars[i] = item && !(<any>item).toJSON ? new Car(item) : <Car>item;", output); // skills values are converted: Assert.Contains("this.skills[key] = item && !(<any>item).toJSON ? new Skill(item) : <Skill>item;", output); // student car is converted: Assert.Contains("this.car = data.car && !(<any>data.car).toJSON ? new Car(data.car) : <Car>this.car;", output); // interface is correct Assert.Contains(@"export interface IMyClass { supervisor: MyClass; address: IAddress; cars: ICar[]; skills: { [key: string] : ISkill; }; foo: Car[][]; bar: { [key: string] : Skill[]; }; }".Replace("\r", "").Replace("\n", ""), output.Replace("\r", "").Replace("\n", "")); }
public async Task When_empty_class_inherits_from_dictionary_then_allOf_inheritance_still_works() { //// Arrange var schema = JsonSchema.FromType <MyContainer>(); var data = schema.ToJson(); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings()); //// Act var code = generator.GenerateFile(); //// Assert var dschema = schema.Definitions["EmptyClassInheritingDictionary"]; Assert.Equal(0, dschema.AllOf.Count); Assert.True(dschema.IsDictionary); Assert.Contains("Foobar.", data); Assert.Contains("Foobar.", code); Assert.DoesNotContain("class CustomDictionary :", code); Assert.Contains("public EmptyClassInheritingDictionary CustomDictionary", code); Assert.Contains("public partial class EmptyClassInheritingDictionary : System.Collections.Generic.Dictionary<string, object>", code); }
public void HumanoidBoneTest() { var model = new glTF_VRM_HumanoidBone() { bone = "hips", // NOTE: This field must not be null? }; var json = model.ToJson(); Assert.AreEqual(@"{""bone"":""hips"",""node"":-1,""useDefaultValues"":true}", json); Debug.Log(json); var c = new JsonSchemaValidationContext("") { EnableDiagnosisForNotRequiredFields = true, }; var json2 = JsonSchema.FromType <glTF_VRM_HumanoidBone>().Serialize(model, c); // NOTE: New serializer outputs values which will not be used... Assert.AreEqual( @"{""bone"":""hips"",""node"":-1,""useDefaultValues"":true,""min"":{""x"":0,""y"":0,""z"":0},""max"":{""x"":0,""y"":0,""z"":0},""center"":{""x"":0,""y"":0,""z"":0},""axisLength"":0}", json2); }
public async Task When_property_is_integer_enum_then_schema_has_enum() { //// Arrange //// Act var schema = JsonSchema.FromType <Foo>(new JsonSchemaGeneratorSettings { DefaultEnumHandling = EnumHandling.Integer, GenerateEnumMappingDescription = true }); var data = schema.ToJson(); //// Assert Assert.Equal(JsonObjectType.Integer, schema.Properties["Bar"].ActualTypeSchema.Type); Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.Enumeration.Count); Assert.Equal(0, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0)); Assert.Equal(5, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1)); Assert.Equal(6, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2)); Assert.Contains("Foo bar.", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled Assert.Contains("5 = B", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled }