public void When_schema_contains_ref_to_definition_that_refs_another_definition_then_result_should_contain_correct_target_ref_type() { //// Arrange var schemaJson = @"{ 'x-typeName': 'foo', 'type': 'object', 'definitions': { 'pRef': { 'type': 'object', 'properties': { 'pRef2': { '$ref': '#/definitions/pRef2' }, } }, 'pRef2': { 'type': 'string' } }, 'properties': { 'pRefs': { 'type': 'array', 'items': { '$ref': '#/definitions/pRef' } } } }"; var schema = JsonSchema4.FromJson(schemaJson); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }; var gen = new CSharpGenerator(schema, settings); //// Act var output = gen.GenerateFile(); //// Assert Assert.IsTrue(output.Contains("public ObservableCollection<pRef>")); }
public void When_unique_items_is_set_and_items_are_objects_then_validation_works() { //// Arrange var jsonSchema = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""title"": ""Config"", ""type"": ""array"", ""uniqueItems"": true, ""items"": { ""title"": ""KeyValue Pair"", ""type"": ""object"", ""properties"": { ""key"": { ""title"": ""Key"", ""type"": ""string"", ""minLength"": 1 }, ""value"": { ""title"": ""Value"", ""type"": ""string"", ""minLength"": 1 } } } }"; var jsonData = @"[{ ""key"": ""a"", ""value"": ""b"" }, { ""key"": ""a"", ""value"": ""b"" }]"; //// Act var schema = JsonSchema4.FromJson(jsonSchema); var errors = schema.Validate(jsonData).ToList(); //// Assert Assert.AreEqual(1, errors.Count); }
public void When_type_is_array_and_items_and_item_is_not_defined_then_any_array_is_generated() { //// Arrange var json = @"{ 'properties': { 'emptySchema': { 'type': 'array' } } }"; var schema = JsonSchema4.FromJson(json); //// Act var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = "ns", }; var generator = new CSharpGenerator(schema, settings); var output = generator.GenerateFile("MyClass"); //// Assert Assert.IsTrue(output.Contains("public System.Collections.ObjectModel.ObservableCollection<object> EmptySchema { get; set; }")); }
public void When_property_has_boolean_default_it_is_reflected_in_the_poco() { var data = @"{'properties': { 'boolWithDefault': { 'type': 'boolean', 'default': false } }}"; var schema = JsonSchema4.FromJson(data); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = "ns", GenerateDefaultValues = true }; var gen = new CSharpGenerator(schema, settings); var output = gen.GenerateFile(); Assert.IsTrue(output.Contains("public bool BoolWithDefault { get; set; } = false;")); }
public void When_property_has_boolean_default_and_default_value_generation_is_disabled_then_default_value_is_not_generated() { var data = @"{'properties': { 'boolWithDefault': { 'type': 'boolean', 'default': false } }}"; var schema = JsonSchema4.FromJson(data); var settings = new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco, Namespace = "ns", GenerateDefaultValues = false }; var gen = new CSharpGenerator(schema, settings); var output = gen.GenerateFile("MyClass"); Assert.IsTrue(output.Contains("public bool BoolWithDefault { get; set; }")); Assert.IsFalse(output.Contains("public bool BoolWithDefault { get; set; } = false;")); }
public override Task <object> RunAsync(CommandLineProcessor processor, IConsoleHost host) { var settings = new CSharpGeneratorSettings { Namespace = Namespace, RequiredPropertiesMustBeDefined = RequiredPropertiesMustBeDefined, DateTimeType = DateTimeType, ArrayType = ArrayType, DictionaryType = DictionaryType, }; var schema = JsonSchema4.FromJson(InputJson); var generator = new CSharpGenerator(schema, settings); var code = generator.GenerateFile(); if (TryWriteFileOutput(host, () => code) == false) { return(Task.FromResult <object>(code)); } return(Task.FromResult <object>(null)); }
public void When_using_json_schema_with_references_in_service_then_references_are_correctly_resolved() { //// Arrange var jsonSchema = @"{ ""definitions"": { ""app"": { ""definitions"": { ""name"": { ""pattern"": ""^[a-z][a-z0-9-]{3,30}$"", ""type"": ""string"" } }, ""properties"": { ""name"": { ""$ref"": ""#/definitions/app/definitions/name"" } }, ""required"": [""name""], ""type"": ""object"" } }, ""properties"": { ""app"": { ""$ref"": ""#/definitions/app"" }, }, ""type"": ""object"" }"; //// Act var schema = JsonSchema4.FromJson(jsonSchema); var service = new SwaggerService(); service.Definitions["Foo"] = schema; //// Assert var jsonService = service.ToJson(); // no exception expected }
private static void RunTest(JObject suite, JToken value, bool expectedResult, ref int fails, ref int passes, ref int exceptions) { try { var schema = JsonSchema4.FromJson(suite["schema"].ToString()); var errors = schema.Validate(value); var success = expectedResult ? errors.Count == 0 : errors.Count > 0; if (!success) { Console.ForegroundColor = ConsoleColor.Red; } Console.WriteLine(" Result: " + success); if (!success) { Console.ForegroundColor = ConsoleColor.Gray; } if (!success) { fails++; } else { passes++; } } catch (Exception ex) { exceptions++; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" Exception: " + ex.GetType().FullName + " => " + ex.Message); Console.ForegroundColor = ConsoleColor.Gray; } }
public void When_property_has_same_name_as_class_then_it_is_renamed() { //// Arrange var schemaJson = @"{ ""type"": ""object"", ""properties"": { ""Foo"": { ""type"": ""string"" } } }"; var schema = JsonSchema4.FromJson(schemaJson); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); var code = generator.GenerateFile("Foo"); //// Assert Assert.IsTrue(code.Contains("[Newtonsoft.Json.JsonProperty(\"Foo\", Required = Newtonsoft.Json.Required.DisallowNull")); Assert.IsTrue(code.Contains("public string Foo1 { get; set; }")); }
public void When_null_is_allowed_then_properties_are_not_checked() { //// Arrange var schemaJson = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""array"", ""items"": { ""type"": [ ""object"", ""null"" ], ""properties"": { ""value"": { ""type"": ""integer"" } }, ""required"": [ ""value"" ], ""additionalProperties"": false } }"; var schema = JsonSchema4.FromJson(schemaJson); //// Act var errors = schema.Validate("[{\"value\":2},null]"); //// Assert Assert.AreEqual(0, errors.Count); }
public void When_enum_has_no_names_and_string_value_starts_with_number_then_underline_is_generated() { //// Arrange var schemaData = @"{ ""type"": ""object"", ""properties"": { ""Bar"": { ""oneOf"": [ { ""$ref"": ""#/definitions/StringEnum"" } ] } }, ""definitions"": { ""StringEnum"": { ""type"": ""string"", ""enum"": [ ""0562"", ""0532"" ], ""description"": """" } } }"; var schema = JsonSchema4.FromJson(schemaData); //// Act var generator = new CSharpGenerator(schema); var code = generator.GenerateFile(); //// Assert Assert.IsTrue(code.Contains("[EnumMember(Value = \"0562\")]")); Assert.IsTrue(code.Contains("_0562 = 0,")); Assert.IsTrue(code.Contains("[EnumMember(Value = \"0532\")]")); Assert.IsTrue(code.Contains("_0532 = 1,")); }
public void When_enum_has_no_type_then_enum_is_generated() { //// Arrange var json = @"{ ""type"": ""object"", ""properties"": { ""category"" : { ""enum"" : [ ""commercial"", ""residential"" ] } } }"; var schema = JsonSchema4.FromJson(json); var generator = new CSharpGenerator(schema); //// Act var code = generator.GenerateFile("MyClass"); //// Assert Assert.IsTrue(code.Contains("public enum MyClassCategory")); }
public void When_multipleOf_is_fraction_then_it_is_validated_correctly() { //// Arrange List <SimpleClass> testClasses = new List <SimpleClass>(); for (int i = 0; i < 100; i++) { testClasses.Add(new SimpleClass((decimal)(0.1 * i))); } string jsonData = JsonConvert.SerializeObject(testClasses, Formatting.Indented); var schema = JsonSchema4.FromJson(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""number"": { ""type"": ""number"", ""multipleOf"": 0.1, ""minimum"": 0.0, ""maximum"": 4903700.0 } }, ""required"": [ ""number"" ] } }"); //// Act var errors = schema.Validate(jsonData); //// Assert Assert.AreEqual(0, errors.Count); }
static void Main(string[] args) { var schema = JsonSchema4.FromJson(File.ReadAllText($@"{AppDomain.CurrentDomain.BaseDirectory}\ksy-json-schema.json")); var ksyValidationErrors = new Dictionary <string, ValidationError[]>(); //var deserializer = new DeserializerBuilder().WithNodeDeserializer(new MyNodeDeserializer()).Build(); //var deserializer = Deserializer.FromValueDeserializer(new MyValueDeserializer()); //var deserializer = new Deserializer(); var deserializer = new DeserializerBuilder().WithNodeTypeResolver(new MyNodeTypeReslover()).Build(); deserializer.Deserialize(new StringReader("a: true\r\nb: 'true'")); var ksyBaseDir = $@"{GitReposPath}\kaitai_struct_webide\formats\"; var ksyFiles = Directory.GetFiles(ksyBaseDir, "*.ksy", SearchOption.AllDirectories); foreach (var ksyFn in ksyFiles) { var ksyRelDir = ksyFn.Replace(ksyBaseDir, ""); var obj = deserializer.Deserialize(new StringReader(File.ReadAllText(ksyFn))); var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented); SaveIfNeeded($@"{KsyJsonPath}{ksyRelDir}.json", json); var validationErrors = schema.Validate(json).ToArray(); if (validationErrors.Length > 0) { ksyValidationErrors[ksyRelDir] = validationErrors; } } var allValidationErrors = ksyValidationErrors.SelectMany(x => x.Value.Select(err => new { fn = x.Key, err })).ToArray(); var csharp = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }).GenerateFile("KsyFile"); var typescript = new TypeScriptGenerator(schema, new TypeScriptGeneratorSettings()).GenerateFile("KsyFile"); }
public void When_allOf_schema_is_object_type_then_it_is_an_inherited_class_in_generated_code() { //// Arrange var json = @"{ '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'properties': { 'prop1' : { 'type' : 'string' } }, 'allOf': [ { '$ref': '#/definitions/Bar' } ], 'definitions': { 'Bar': { 'type': 'object', 'properties': { 'prop2' : { 'type' : 'string' } } } } }"; //// Act var schema = JsonSchema4.FromJson(json); var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); var code = generator.GenerateFile("Foo"); //// Assert Assert.IsTrue(code.Contains("class Foo : Bar")); Assert.IsTrue(code.Contains("public string Prop1 { get; set; }")); Assert.IsTrue(code.Contains("public string Prop2 { get; set; }")); }
public void When_enum_type_name_is_missing_then_default_value_is_still_correctly_set() { //// Arrange var schemaJson = @"{ ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""ConstructionCode"": { ""type"": ""integer"", ""x-enumNames"": [ ""FIRE_RSTV"", ""FRAME"", ""JOIST_MAS"", ""NON_CBST"" ], ""enum"": [ 0, 1, 2, 3 ], ""default"": 3 } } }"; var schema = JsonSchema4.FromJson(schemaJson); //// Act var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings { ClassStyle = CSharpClassStyle.Poco }); var code = generator.GenerateFile(); //// Assert Assert.IsTrue(code.Contains("public ConstructionCode ConstructionCode { get; set; } = ConstructionCode.NON_CBST;")); }
public static void Init(TestContext context) { Schema = JsonSchema4.FromJson(@"{ ""type"": ""object"", ""required"": [""prop1"", ""prop3""], ""additionalProperties"": false, ""properties"": { ""prop1"": { ""type"": ""string"" }, ""prop2"": { ""type"": ""number"", ""enum"": [""this"", ""that""] }, ""prop3"": {} } }"); Json = @"{ ""prop1"": 12, ""prop2"": ""something"", ""prop4"": null }"; }
public void When_no_additional_properties_are_allowed_then_this_error_is_returned() { //// Arrange var schemaData = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", ""typeName"": ""ReportItem"", ""additionalProperties"": false, ""required"": [ ""ReportID"", ""RequiresFilter"", ""MimeType"", ""ExternalID"", ""CreatedBy"", ""ExecutionScript"", ""ExecutionParameter"", ""Columns"" ], ""properties"": { ""ReportID"": { ""type"": ""string"", ""format"": ""guid"" }, ""RequiresFilter"": { ""type"": ""boolean"" }, ""MimeType"": { ""type"": ""string"" }, ""ExternalID"": { ""type"": ""string"" }, ""CreatedBy"": { ""type"": ""string"", ""format"": ""date-time"" }, ""ExecutionScript"": { ""type"": ""string"" }, ""ExecutionParameter"": { ""type"": ""string"" }, ""ExecutionOrderBy"": { ""type"": [ ""null"", ""string"" ] }, ""DynamicFilters"": { ""type"": [ ""array"", ""null"" ], ""items"": { ""type"": ""object"", ""typeName"": ""DynamicFilter"", ""additionalProperties"": false, ""required"": [ ""ID"", ""Script"", ""ScriptOrderBy"", ""Fields"", ""ScriptParams"" ], ""properties"": { ""ID"": { ""type"": ""string"" }, ""Script"": { ""type"": ""string"" }, ""ScriptOrderBy"": { ""type"": ""string"" }, ""Fields"": { ""type"": ""string"" }, ""ScriptParams"": { ""type"": ""object"", ""additionalProperties"": { ""type"": [ ""array"", ""boolean"", ""integer"", ""null"", ""number"", ""object"", ""string"" ] } } } } }, ""RequiresOrgID"": { ""type"": ""boolean"" }, ""ReportFilter"": { ""oneOf"": [ { ""$ref"": ""#/definitions/QueryFilter"" }, { ""type"": ""null"" } ] }, ""ReportRules"": { ""oneOf"": [ { ""$ref"": ""#/definitions/QueryRule"" }, { ""type"": ""null"" } ] }, ""Columns"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""typeName"": ""QueryColumn"", ""additionalProperties"": false, ""required"": [ ""isrequired"", ""column_name"" ], ""properties"": { ""isrequired"": { ""type"": ""boolean"" }, ""column_name"": { ""type"": ""string"" } } } } }, ""definitions"": { ""QueryFilter"": { ""type"": ""object"", ""typeName"": ""QueryFilter"", ""additionalProperties"": false, ""required"": [ ""display_errors"", ""allow_empty"", ""plugins"", ""filters"" ], ""properties"": { ""display_errors"": { ""type"": ""boolean"" }, ""allow_empty"": { ""type"": ""boolean"" }, ""plugins"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } }, ""filters"": { ""type"": ""array"", ""items"": { ""type"": ""object"", ""typeName"": ""Filter"", ""additionalProperties"": false, ""required"": [ ""id"", ""label"", ""type"", ""operators"" ], ""properties"": { ""id"": { ""type"": ""string"" }, ""label"": { ""type"": ""string"" }, ""type"": { ""type"": ""string"" }, ""operators"": { ""type"": ""array"", ""items"": { ""type"": ""string"" } }, ""input"": { ""type"": [ ""null"", ""string"" ] }, ""values"": { ""type"": [ ""null"", ""object"" ], ""additionalProperties"": { ""type"": [ ""array"", ""boolean"", ""integer"", ""null"", ""number"", ""object"", ""string"" ] } }, ""validation"": { ""oneOf"": [ { ""$ref"": ""#/definitions/Validation"" }, { ""type"": ""null"" } ] }, ""unique"": { ""type"": ""boolean"" }, ""description"": { ""type"": [ ""null"", ""string"" ] } } } } } }, ""QueryRule"": { ""type"": ""object"", ""typeName"": ""QueryRule"", ""additionalProperties"": false, ""properties"": { ""condition"": { ""type"": [ ""null"", ""string"" ] }, ""rules"": { ""type"": [ ""array"", ""null"" ], ""items"": { ""type"": ""object"", ""typeName"": ""Rule"", ""additionalProperties"": false, ""properties"": { ""id"": { ""type"": [ ""null"", ""string"" ] }, ""operator"": { ""type"": [ ""null"", ""string"" ] }, ""value"": { ""type"": [ ""null"", ""object"" ] }, ""readonly"": { ""type"": ""boolean"" }, ""condition"": { ""type"": [ ""null"", ""string"" ] } } } } } }, ""Validation"": { ""type"": ""object"", ""typeName"": ""Validation"", ""additionalProperties"": false, ""properties"": { ""min"": { ""type"": ""integer"" }, ""step"": { ""type"": ""number"", ""format"": ""double"" } } } } } "; var schema = JsonSchema4.FromJson(schemaData); //// Act var errors = schema.Validate(@"{""Key"": ""Value""}"); var error = errors.SingleOrDefault(e => e.Kind == ValidationErrorKind.NoAdditionalPropertiesAllowed); //// Assert Assert.IsNotNull(error); Assert.AreEqual("#", error.Path); }
protected CldrJsonParser(string schema) { this.schema = JsonSchema4.FromJson(schema); }
public Configuration Load() { logger.LogInfo("Loading configuration for solution"); if (!_ConfigurationFileExists()) { logger.LogInfo("No configuration file found, using default configuration."); return(_GetDefaultConfiguration()); } JObject settings = null; try { settings = JObject.Parse(File.ReadAllText(configurationFilename)); } catch (Exception e) { MessageBox.Show("Could not parse configuration file.\nPlease check the syntax of your configuration file!\nUsing default configuration instead.\n\nError:\n" + e.ToString(), "SwitchStartupProject Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); logger.LogError("Error while parsing configuration file:"); logger.LogError(e.ToString()); logger.LogInfo("Using default configuration."); return(_GetDefaultConfiguration()); } JsonSchema4 schema = null; try { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("LucidConcepts.SwitchStartupProject.Configuration.ConfigurationSchema.json"); using (var reader = new StreamReader(stream)) { schema = JsonSchema4.FromJson(reader.ReadToEnd()); } } catch (Exception e) { MessageBox.Show("Could not parse schema.\nError:\n" + e.ToString(), "SwitchStartupProject Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); logger.LogError("Error while parsing schema:"); logger.LogError(e.ToString()); logger.LogInfo("Using default configuration."); return(_GetDefaultConfiguration()); } var validationErrors = schema.Validate(settings); if (validationErrors.Any()) { var messages = string.Join("\n", validationErrors.Select(err => string.Format("{0}: {1}", err.Path, err.Kind))); MessageBox.Show("Could not validate schema of configuration file.\nPlease check your configuration file!\nUsing default configuration instead.\n\nErrors:\n" + messages, "SwitchStartupProject Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); logger.LogError("Could not validate schema of configuration file."); logger.LogInfo("Using default configuration."); return(_GetDefaultConfiguration()); } var version = _GetVersion(settings); if (version != knownVersion) { MessageBox.Show("Configuration file has unknown version " + version + ".\nVersion should be " + knownVersion + ".\nUsing default configuration instead.", "SwitchStartupProject Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); logger.LogError("Unknown configuration version " + version); logger.LogInfo("Using default configuration."); return(_GetDefaultConfiguration()); } var listAllProjects = _GetListAllProjects(settings); var multiProjectConfigurations = _GetMultiProjectConfigurations(settings); return(new Configuration(listAllProjects, multiProjectConfigurations.ToList())); }
private static JsonSchema4 LoadJsonSchema(string schemaId) { string json = ReadFileFromAssembly(schemaId); return(JsonSchema4.FromJson(json)); }