-Line endings

This commit is contained in:
James Newton-King
2012-04-08 18:10:07 +12:00
parent a139d7bf20
commit 83618b1ea0
381 changed files with 96885 additions and 96885 deletions
@@ -1,313 +1,313 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !(SILVERLIGHT || NETFX_CORE)
using System.Data;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class ExtensionsTests : TestFixtureBase
{
[Test]
public void IsValid()
{
JsonSchema schema = JsonSchema.Parse("{'type':'integer'}");
JToken stringToken = JToken.FromObject("pie");
JToken integerToken = JToken.FromObject(1);
IList<string> errorMessages;
Assert.AreEqual(true, integerToken.IsValid(schema));
Assert.AreEqual(true, integerToken.IsValid(schema, out errorMessages));
Assert.AreEqual(0, errorMessages.Count);
Assert.AreEqual(false, stringToken.IsValid(schema));
Assert.AreEqual(false, stringToken.IsValid(schema, out errorMessages));
Assert.AreEqual(1, errorMessages.Count);
Assert.AreEqual("Invalid type. Expected Integer but got String.", errorMessages[0]);
}
[Test]
public void ValidateWithEventHandler()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
List<string> errors = new List<string>();
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
stringToken = JToken.FromObject("pie");
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("String 'pie' does not match regex pattern 'lol'.", errors[0]);
}
[Test]
public void ValidateWithOutEventHandlerFailure()
{
ExceptionAssert.Throws<JsonSchemaException>(@"String 'pie' does not match regex pattern 'lol'.",
() =>
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie");
stringToken.Validate(schema);
});
}
[Test]
public void ValidateWithOutEventHandlerSuccess()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
stringToken.Validate(schema);
}
[Test]
public void ValidateFailureWithOutLineInfoBecauseOfEndToken()
{
JsonSchema schema = JsonSchema.Parse("{'properties':{'lol':{'required':true}}}");
JObject o = JObject.Parse("{}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual("Required properties are missing from object: lol.", errors[0]);
Assert.AreEqual(1, errors.Count);
}
[Test]
public void ValidateFailureWithLineInfo()
{
JsonSchema schema = JsonSchema.Parse("{'properties':{'lol':{'type':'string'}}}");
JObject o = JObject.Parse("{'lol':1}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Path + " - " + args.Message));
Assert.AreEqual("lol - Invalid type. Expected String but got Integer. Line 1, position 8.", errors[0]);
Assert.AreEqual("1", o.SelectToken("lol").ToString());
Assert.AreEqual(1, errors.Count);
}
[Test]
public void Blog()
{
string schemaJson = @"
{
""description"": ""A person schema"",
""type"": ""object"",
""properties"":
{
""name"": {""type"":""string""},
""hobbies"": {
""type"": ""array"",
""items"": {""type"":""string""}
}
}
}
";
//JsonSchema schema;
//using (JsonTextReader reader = new JsonTextReader(new StringReader(schemaJson)))
//{
// JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
// schema = builder.Parse(reader);
//}
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
""name"": ""James"",
""hobbies"": ["".NET"", ""Blogging"", ""Reading"", ""Xbox"", ""LOLCATS""]
}");
bool valid = person.IsValid(schema);
// true
}
private void GenerateSchemaAndSerializeFromType<T>(T value)
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
JsonSchema typeSchema = generator.Generate(typeof (T));
string schema = typeSchema.ToString();
string json = JsonConvert.SerializeObject(value, Formatting.Indented);
JToken token = JToken.ReadFrom(new JsonTextReader(new StringReader(json)));
List<string> errors = new List<string>();
token.Validate(typeSchema, (sender, args) =>
{
errors.Add(args.Message);
});
if (errors.Count > 0)
Assert.Fail("Schema generated for type '{0}' is not valid." + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray()), typeof(T));
}
[Test]
public void GenerateSchemaAndSerializeFromTypeTests()
{
GenerateSchemaAndSerializeFromType(new List<string> { "1", "Two", "III" });
GenerateSchemaAndSerializeFromType(new List<int> { 1 });
GenerateSchemaAndSerializeFromType(new Version("1.2.3.4"));
GenerateSchemaAndSerializeFromType(new Store());
GenerateSchemaAndSerializeFromType(new Person());
GenerateSchemaAndSerializeFromType(new PersonRaw());
GenerateSchemaAndSerializeFromType(new CircularReferenceClass() { Name = "I'm required" });
GenerateSchemaAndSerializeFromType(new CircularReferenceWithIdClass());
GenerateSchemaAndSerializeFromType(new ClassWithArray());
GenerateSchemaAndSerializeFromType(new ClassWithGuid());
#if !NET20 && !PocketPC
GenerateSchemaAndSerializeFromType(new NullableDateTimeTestClass());
#endif
#if !(SILVERLIGHT || NETFX_CORE)
GenerateSchemaAndSerializeFromType(new DataSet());
#endif
GenerateSchemaAndSerializeFromType(new object());
GenerateSchemaAndSerializeFromType(1);
GenerateSchemaAndSerializeFromType("Hi");
GenerateSchemaAndSerializeFromType(new DateTime(2000, 12, 29, 23, 59, 0, DateTimeKind.Utc));
GenerateSchemaAndSerializeFromType(TimeSpan.FromTicks(1000000));
#if !NETFX_CORE
GenerateSchemaAndSerializeFromType(DBNull.Value);
#endif
GenerateSchemaAndSerializeFromType(new JsonPropertyWithHandlingValues());
}
[Test]
public void UndefinedPropertyOnNoPropertySchema()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"": ""test"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
}
}");
JObject o = JObject.Parse("{'g':1}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("Property 'g' has not been defined and the schema does not allow additional properties. Line 1, position 5.", errors[0]);
}
[Test]
public void ExclusiveMaximum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals maximum value of 10 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMaximum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10.1;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMinimum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals minimum value of 10 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMinimum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10.1;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
}
[Test]
public void DivisibleBy_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 is not evenly divisible by 3.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
JValue v = new JValue(10);
v.Validate(schema);
});
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !(SILVERLIGHT || NETFX_CORE)
using System.Data;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class ExtensionsTests : TestFixtureBase
{
[Test]
public void IsValid()
{
JsonSchema schema = JsonSchema.Parse("{'type':'integer'}");
JToken stringToken = JToken.FromObject("pie");
JToken integerToken = JToken.FromObject(1);
IList<string> errorMessages;
Assert.AreEqual(true, integerToken.IsValid(schema));
Assert.AreEqual(true, integerToken.IsValid(schema, out errorMessages));
Assert.AreEqual(0, errorMessages.Count);
Assert.AreEqual(false, stringToken.IsValid(schema));
Assert.AreEqual(false, stringToken.IsValid(schema, out errorMessages));
Assert.AreEqual(1, errorMessages.Count);
Assert.AreEqual("Invalid type. Expected Integer but got String.", errorMessages[0]);
}
[Test]
public void ValidateWithEventHandler()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
List<string> errors = new List<string>();
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(0, errors.Count);
stringToken = JToken.FromObject("pie");
stringToken.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("String 'pie' does not match regex pattern 'lol'.", errors[0]);
}
[Test]
public void ValidateWithOutEventHandlerFailure()
{
ExceptionAssert.Throws<JsonSchemaException>(@"String 'pie' does not match regex pattern 'lol'.",
() =>
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie");
stringToken.Validate(schema);
});
}
[Test]
public void ValidateWithOutEventHandlerSuccess()
{
JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
JToken stringToken = JToken.FromObject("pie lol");
stringToken.Validate(schema);
}
[Test]
public void ValidateFailureWithOutLineInfoBecauseOfEndToken()
{
JsonSchema schema = JsonSchema.Parse("{'properties':{'lol':{'required':true}}}");
JObject o = JObject.Parse("{}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual("Required properties are missing from object: lol.", errors[0]);
Assert.AreEqual(1, errors.Count);
}
[Test]
public void ValidateFailureWithLineInfo()
{
JsonSchema schema = JsonSchema.Parse("{'properties':{'lol':{'type':'string'}}}");
JObject o = JObject.Parse("{'lol':1}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Path + " - " + args.Message));
Assert.AreEqual("lol - Invalid type. Expected String but got Integer. Line 1, position 8.", errors[0]);
Assert.AreEqual("1", o.SelectToken("lol").ToString());
Assert.AreEqual(1, errors.Count);
}
[Test]
public void Blog()
{
string schemaJson = @"
{
""description"": ""A person schema"",
""type"": ""object"",
""properties"":
{
""name"": {""type"":""string""},
""hobbies"": {
""type"": ""array"",
""items"": {""type"":""string""}
}
}
}
";
//JsonSchema schema;
//using (JsonTextReader reader = new JsonTextReader(new StringReader(schemaJson)))
//{
// JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
// schema = builder.Parse(reader);
//}
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(@"{
""name"": ""James"",
""hobbies"": ["".NET"", ""Blogging"", ""Reading"", ""Xbox"", ""LOLCATS""]
}");
bool valid = person.IsValid(schema);
// true
}
private void GenerateSchemaAndSerializeFromType<T>(T value)
{
JsonSchemaGenerator generator = new JsonSchemaGenerator();
generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseAssemblyQualifiedName;
JsonSchema typeSchema = generator.Generate(typeof (T));
string schema = typeSchema.ToString();
string json = JsonConvert.SerializeObject(value, Formatting.Indented);
JToken token = JToken.ReadFrom(new JsonTextReader(new StringReader(json)));
List<string> errors = new List<string>();
token.Validate(typeSchema, (sender, args) =>
{
errors.Add(args.Message);
});
if (errors.Count > 0)
Assert.Fail("Schema generated for type '{0}' is not valid." + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray()), typeof(T));
}
[Test]
public void GenerateSchemaAndSerializeFromTypeTests()
{
GenerateSchemaAndSerializeFromType(new List<string> { "1", "Two", "III" });
GenerateSchemaAndSerializeFromType(new List<int> { 1 });
GenerateSchemaAndSerializeFromType(new Version("1.2.3.4"));
GenerateSchemaAndSerializeFromType(new Store());
GenerateSchemaAndSerializeFromType(new Person());
GenerateSchemaAndSerializeFromType(new PersonRaw());
GenerateSchemaAndSerializeFromType(new CircularReferenceClass() { Name = "I'm required" });
GenerateSchemaAndSerializeFromType(new CircularReferenceWithIdClass());
GenerateSchemaAndSerializeFromType(new ClassWithArray());
GenerateSchemaAndSerializeFromType(new ClassWithGuid());
#if !NET20 && !PocketPC
GenerateSchemaAndSerializeFromType(new NullableDateTimeTestClass());
#endif
#if !(SILVERLIGHT || NETFX_CORE)
GenerateSchemaAndSerializeFromType(new DataSet());
#endif
GenerateSchemaAndSerializeFromType(new object());
GenerateSchemaAndSerializeFromType(1);
GenerateSchemaAndSerializeFromType("Hi");
GenerateSchemaAndSerializeFromType(new DateTime(2000, 12, 29, 23, 59, 0, DateTimeKind.Utc));
GenerateSchemaAndSerializeFromType(TimeSpan.FromTicks(1000000));
#if !NETFX_CORE
GenerateSchemaAndSerializeFromType(DBNull.Value);
#endif
GenerateSchemaAndSerializeFromType(new JsonPropertyWithHandlingValues());
}
[Test]
public void UndefinedPropertyOnNoPropertySchema()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"": ""test"",
""type"": ""object"",
""additionalProperties"": false,
""properties"": {
}
}");
JObject o = JObject.Parse("{'g':1}");
List<string> errors = new List<string>();
o.Validate(schema, (sender, args) => errors.Add(args.Message));
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("Property 'g' has not been defined and the schema does not allow additional properties. Line 1, position 5.", errors[0]);
}
[Test]
public void ExclusiveMaximum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals maximum value of 10 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMaximum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Maximum = 10.1;
schema.ExclusiveMaximum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMinimum_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 equals minimum value of 10 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10);
v.Validate(schema);
});
}
[Test]
public void ExclusiveMinimum_Float()
{
ExceptionAssert.Throws<JsonSchemaException>("Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.Minimum = 10.1;
schema.ExclusiveMinimum = true;
JValue v = new JValue(10.1);
v.Validate(schema);
});
}
[Test]
public void DivisibleBy_Int()
{
ExceptionAssert.Throws<JsonSchemaException>("Integer 10 is not evenly divisible by 3.",
() =>
{
JsonSchema schema = new JsonSchema();
schema.DivisibleBy = 3;
JValue v = new JValue(10);
v.Validate(schema);
});
}
}
}
@@ -1,476 +1,476 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaBuilderTests : TestFixtureBase
{
[Test]
public void Simple()
{
string json = @"
{
""description"": ""A person"",
""type"": ""object"",
""properties"":
{
""name"": {""type"":""string""},
""hobbies"": {
""type"": ""array"",
""items"": {""type"":""string""}
}
}
}
";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("A person", schema.Description);
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(2, schema.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["name"].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Properties["hobbies"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["hobbies"].Items[0].Type);
}
[Test]
public void MultipleTypes()
{
string json = @"{
""description"":""Age"",
""type"":[""string"", ""integer""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Age", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Integer, schema.Type);
}
[Test]
public void MultipleItems()
{
string json = @"{
""description"":""MultipleItems"",
""type"":""array"",
""items"": [{""type"":""string""},{""type"":""array""}]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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);
}
[Test]
public void AdditionalProperties()
{
string json = @"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("AdditionalProperties", schema.Description);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type);
}
[Test]
public void Required()
{
string json = @"{
""description"":""Required"",
""required"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Required", schema.Description);
Assert.AreEqual(true, schema.Required);
}
[Test]
public void ExclusiveMinimum_ExclusiveMaximum()
{
string json = @"{
""exclusiveMinimum"":true,
""exclusiveMaximum"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(true, schema.ExclusiveMinimum);
Assert.AreEqual(true, schema.ExclusiveMaximum);
}
[Test]
public void ReadOnly()
{
string json = @"{
""description"":""ReadOnly"",
""readonly"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("ReadOnly", schema.Description);
Assert.AreEqual(true, schema.ReadOnly);
}
[Test]
public void Hidden()
{
string json = @"{
""description"":""Hidden"",
""hidden"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Hidden", schema.Description);
Assert.AreEqual(true, schema.Hidden);
}
[Test]
public void Id()
{
string json = @"{
""description"":""Id"",
""id"":""testid""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Id", schema.Description);
Assert.AreEqual("testid", schema.Id);
}
[Test]
public void Title()
{
string json = @"{
""description"":""Title"",
""title"":""testtitle""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Title", schema.Description);
Assert.AreEqual("testtitle", schema.Title);
}
[Test]
public void Pattern()
{
string json = @"{
""description"":""Pattern"",
""pattern"":""testpattern""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Pattern", schema.Description);
Assert.AreEqual("testpattern", schema.Pattern);
}
[Test]
public void Format()
{
string json = @"{
""description"":""Format"",
""format"":""testformat""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Format", schema.Description);
Assert.AreEqual("testformat", schema.Format);
}
[Test]
public void Requires()
{
string json = @"{
""description"":""Requires"",
""requires"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Requires", schema.Description);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Requires);
}
[Test]
public void IdentitySingle()
{
string json = @"{
""description"":""Identity"",
""identity"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Identity", schema.Description);
Assert.AreEqual(1, schema.Identity.Count);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Identity[0]);
}
[Test]
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]);
}
[Test]
public void MinimumMaximum()
{
string json = @"{
""description"":""MinimumMaximum"",
""minimum"":1.1,
""maximum"":1.2,
""minItems"":1,
""maxItems"":2,
""minLength"":5,
""maxLength"":50,
""divisibleBy"":3,
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MinimumMaximum", schema.Description);
Assert.AreEqual(1.1, schema.Minimum);
Assert.AreEqual(1.2, schema.Maximum);
Assert.AreEqual(1, schema.MinimumItems);
Assert.AreEqual(2, schema.MaximumItems);
Assert.AreEqual(5, schema.MinimumLength);
Assert.AreEqual(50, schema.MaximumLength);
Assert.AreEqual(3, schema.DivisibleBy);
}
[Test]
public void DisallowSingleType()
{
string json = @"{
""description"":""DisallowSingleType"",
""disallow"":""string""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowSingleType", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Disallow);
}
[Test]
public void DisallowMultipleTypes()
{
string json = @"{
""description"":""DisallowMultipleTypes"",
""disallow"":[""string"",""number""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowMultipleTypes", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Float, schema.Disallow);
}
[Test]
public void DefaultPrimitiveType()
{
string json = @"{
""description"":""DefaultPrimitiveType"",
""default"":1.1
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultPrimitiveType", schema.Description);
Assert.AreEqual(1.1, (double)schema.Default);
}
[Test]
public void DefaultComplexType()
{
string json = @"{
""description"":""DefaultComplexType"",
""default"":{""pie"":true}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultComplexType", schema.Description);
Assert.IsTrue(JToken.DeepEquals(JObject.Parse(@"{""pie"":true}"), schema.Default));
}
[Test]
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")]);
}
[Test]
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.Parse(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]);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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]);
}
[Test]
public void UnresolvedReference()
{
ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference for Id 'MyUnresolvedReference'.",
() =>
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""MyUnresolvedReference""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
});
}
[Test]
public void PatternProperties()
{
string json = @"{
""patternProperties"": {
""[abc]"": { ""id"":""Blah"" }
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.IsNotNull(schema.PatternProperties);
Assert.AreEqual(1, schema.PatternProperties.Count);
Assert.AreEqual("Blah", schema.PatternProperties["[abc]"].Id);
}
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
using Newtonsoft.Json.Schema;
using System.IO;
using Newtonsoft.Json.Linq;
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaBuilderTests : TestFixtureBase
{
[Test]
public void Simple()
{
string json = @"
{
""description"": ""A person"",
""type"": ""object"",
""properties"":
{
""name"": {""type"":""string""},
""hobbies"": {
""type"": ""array"",
""items"": {""type"":""string""}
}
}
}
";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("A person", schema.Description);
Assert.AreEqual(JsonSchemaType.Object, schema.Type);
Assert.AreEqual(2, schema.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["name"].Type);
Assert.AreEqual(JsonSchemaType.Array, schema.Properties["hobbies"].Type);
Assert.AreEqual(JsonSchemaType.String, schema.Properties["hobbies"].Items[0].Type);
}
[Test]
public void MultipleTypes()
{
string json = @"{
""description"":""Age"",
""type"":[""string"", ""integer""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Age", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Integer, schema.Type);
}
[Test]
public void MultipleItems()
{
string json = @"{
""description"":""MultipleItems"",
""type"":""array"",
""items"": [{""type"":""string""},{""type"":""array""}]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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);
}
[Test]
public void AdditionalProperties()
{
string json = @"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("AdditionalProperties", schema.Description);
Assert.AreEqual(JsonSchemaType.Object | JsonSchemaType.Boolean, schema.AdditionalProperties.Type);
}
[Test]
public void Required()
{
string json = @"{
""description"":""Required"",
""required"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Required", schema.Description);
Assert.AreEqual(true, schema.Required);
}
[Test]
public void ExclusiveMinimum_ExclusiveMaximum()
{
string json = @"{
""exclusiveMinimum"":true,
""exclusiveMaximum"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual(true, schema.ExclusiveMinimum);
Assert.AreEqual(true, schema.ExclusiveMaximum);
}
[Test]
public void ReadOnly()
{
string json = @"{
""description"":""ReadOnly"",
""readonly"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("ReadOnly", schema.Description);
Assert.AreEqual(true, schema.ReadOnly);
}
[Test]
public void Hidden()
{
string json = @"{
""description"":""Hidden"",
""hidden"":true
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Hidden", schema.Description);
Assert.AreEqual(true, schema.Hidden);
}
[Test]
public void Id()
{
string json = @"{
""description"":""Id"",
""id"":""testid""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Id", schema.Description);
Assert.AreEqual("testid", schema.Id);
}
[Test]
public void Title()
{
string json = @"{
""description"":""Title"",
""title"":""testtitle""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Title", schema.Description);
Assert.AreEqual("testtitle", schema.Title);
}
[Test]
public void Pattern()
{
string json = @"{
""description"":""Pattern"",
""pattern"":""testpattern""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Pattern", schema.Description);
Assert.AreEqual("testpattern", schema.Pattern);
}
[Test]
public void Format()
{
string json = @"{
""description"":""Format"",
""format"":""testformat""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Format", schema.Description);
Assert.AreEqual("testformat", schema.Format);
}
[Test]
public void Requires()
{
string json = @"{
""description"":""Requires"",
""requires"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Requires", schema.Description);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Requires);
}
[Test]
public void IdentitySingle()
{
string json = @"{
""description"":""Identity"",
""identity"":""PurpleMonkeyDishwasher""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("Identity", schema.Description);
Assert.AreEqual(1, schema.Identity.Count);
Assert.AreEqual("PurpleMonkeyDishwasher", schema.Identity[0]);
}
[Test]
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]);
}
[Test]
public void MinimumMaximum()
{
string json = @"{
""description"":""MinimumMaximum"",
""minimum"":1.1,
""maximum"":1.2,
""minItems"":1,
""maxItems"":2,
""minLength"":5,
""maxLength"":50,
""divisibleBy"":3,
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("MinimumMaximum", schema.Description);
Assert.AreEqual(1.1, schema.Minimum);
Assert.AreEqual(1.2, schema.Maximum);
Assert.AreEqual(1, schema.MinimumItems);
Assert.AreEqual(2, schema.MaximumItems);
Assert.AreEqual(5, schema.MinimumLength);
Assert.AreEqual(50, schema.MaximumLength);
Assert.AreEqual(3, schema.DivisibleBy);
}
[Test]
public void DisallowSingleType()
{
string json = @"{
""description"":""DisallowSingleType"",
""disallow"":""string""
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowSingleType", schema.Description);
Assert.AreEqual(JsonSchemaType.String, schema.Disallow);
}
[Test]
public void DisallowMultipleTypes()
{
string json = @"{
""description"":""DisallowMultipleTypes"",
""disallow"":[""string"",""number""]
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DisallowMultipleTypes", schema.Description);
Assert.AreEqual(JsonSchemaType.String | JsonSchemaType.Float, schema.Disallow);
}
[Test]
public void DefaultPrimitiveType()
{
string json = @"{
""description"":""DefaultPrimitiveType"",
""default"":1.1
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultPrimitiveType", schema.Description);
Assert.AreEqual(1.1, (double)schema.Default);
}
[Test]
public void DefaultComplexType()
{
string json = @"{
""description"":""DefaultComplexType"",
""default"":{""pie"":true}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.AreEqual("DefaultComplexType", schema.Description);
Assert.IsTrue(JToken.DeepEquals(JObject.Parse(@"{""pie"":true}"), schema.Default));
}
[Test]
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")]);
}
[Test]
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.Parse(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]);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(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]);
}
[Test]
public void UnresolvedReference()
{
ExceptionAssert.Throws<Exception>(@"Could not resolve schema reference for Id 'MyUnresolvedReference'.",
() =>
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""MyUnresolvedReference""}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
});
}
[Test]
public void PatternProperties()
{
string json = @"{
""patternProperties"": {
""[abc]"": { ""id"":""Blah"" }
}
}";
JsonSchemaBuilder builder = new JsonSchemaBuilder(new JsonSchemaResolver());
JsonSchema schema = builder.Parse(new JsonTextReader(new StringReader(json)));
Assert.IsNotNull(schema.PatternProperties);
Assert.AreEqual(1, schema.PatternProperties.Count);
Assert.AreEqual("Blah", schema.PatternProperties["[abc]"].Id);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,168 +1,168 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaModelBuilderTests : TestFixtureBase
{
[Test]
public void ExtendedComplex()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{""type"":""string"",""maxLength"":10},
""thirdproperty"":{
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""secondproperty"":{""type"":""any""},
""thirdproperty"":{
""extends"":{
""properties"":
{
""thirdproperty_firstproperty"":{""maxLength"":9,""minLength"":6,""pattern"":""hi2u""}
},
""additionalProperties"":{""maxLength"":9,""minLength"":6,""enum"":[""one"",""two""]}
},
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""pattern"":""hi""}
},
""additionalProperties"":{""type"":""string"",""enum"":[""two"",""three""]}
},
""fourthproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(secondSchema);
Assert.AreEqual(4, model.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, model.Properties["firstproperty"].Type);
Assert.AreEqual(JsonSchemaType.String, model.Properties["secondproperty"].Type);
Assert.AreEqual(10, model.Properties["secondproperty"].MaximumLength);
Assert.AreEqual(null, model.Properties["secondproperty"].Enum);
Assert.AreEqual(null, model.Properties["secondproperty"].Patterns);
Assert.AreEqual(JsonSchemaType.Object, model.Properties["thirdproperty"].Type);
Assert.AreEqual(3, model.Properties["thirdproperty"].AdditionalProperties.Enum.Count);
Assert.AreEqual("two", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[0]);
Assert.AreEqual("three", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[1]);
Assert.AreEqual("one", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[2]);
Assert.AreEqual(JsonSchemaType.String, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Type);
Assert.AreEqual(9, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MaximumLength);
Assert.AreEqual(7, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MinimumLength);
Assert.AreEqual(2, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns.Count);
Assert.AreEqual("hi", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[0]);
Assert.AreEqual("hi2u", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[1]);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Properties);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Items);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].AdditionalProperties);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Array, model.Type);
Assert.AreEqual(model, model.Items[0]);
}
[Test]
public void Required()
{
string schemaJson = @"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":{""type"":""string"",required:true},
""age"":{""type"":""integer"",required:true}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Object, model.Type);
Assert.AreEqual(3, model.Properties.Count);
Assert.AreEqual(false, model.Properties["name"].Required);
Assert.AreEqual(true, model.Properties["hobbies"].Required);
Assert.AreEqual(true, model.Properties["age"].Required);
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaModelBuilderTests : TestFixtureBase
{
[Test]
public void ExtendedComplex()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{""type"":""string"",""maxLength"":10},
""thirdproperty"":{
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""secondproperty"":{""type"":""any""},
""thirdproperty"":{
""extends"":{
""properties"":
{
""thirdproperty_firstproperty"":{""maxLength"":9,""minLength"":6,""pattern"":""hi2u""}
},
""additionalProperties"":{""maxLength"":9,""minLength"":6,""enum"":[""one"",""two""]}
},
""type"":""object"",
""properties"":
{
""thirdproperty_firstproperty"":{""pattern"":""hi""}
},
""additionalProperties"":{""type"":""string"",""enum"":[""two"",""three""]}
},
""fourthproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(secondSchema);
Assert.AreEqual(4, model.Properties.Count);
Assert.AreEqual(JsonSchemaType.String, model.Properties["firstproperty"].Type);
Assert.AreEqual(JsonSchemaType.String, model.Properties["secondproperty"].Type);
Assert.AreEqual(10, model.Properties["secondproperty"].MaximumLength);
Assert.AreEqual(null, model.Properties["secondproperty"].Enum);
Assert.AreEqual(null, model.Properties["secondproperty"].Patterns);
Assert.AreEqual(JsonSchemaType.Object, model.Properties["thirdproperty"].Type);
Assert.AreEqual(3, model.Properties["thirdproperty"].AdditionalProperties.Enum.Count);
Assert.AreEqual("two", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[0]);
Assert.AreEqual("three", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[1]);
Assert.AreEqual("one", (string)model.Properties["thirdproperty"].AdditionalProperties.Enum[2]);
Assert.AreEqual(JsonSchemaType.String, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Type);
Assert.AreEqual(9, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MaximumLength);
Assert.AreEqual(7, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].MinimumLength);
Assert.AreEqual(2, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns.Count);
Assert.AreEqual("hi", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[0]);
Assert.AreEqual("hi2u", model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Patterns[1]);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Properties);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].Items);
Assert.AreEqual(null, model.Properties["thirdproperty"].Properties["thirdproperty_firstproperty"].AdditionalProperties);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Array, model.Type);
Assert.AreEqual(model, model.Items[0]);
}
[Test]
public void Required()
{
string schemaJson = @"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":{""type"":""string"",required:true},
""age"":{""type"":""integer"",required:true}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaModel model = modelBuilder.Build(schema);
Assert.AreEqual(JsonSchemaType.Object, model.Type);
Assert.AreEqual(3, model.Properties.Count);
Assert.AreEqual(false, model.Properties["name"].Required);
Assert.AreEqual(true, model.Properties["hobbies"].Required);
Assert.AreEqual(true, model.Properties["age"].Required);
}
}
}
@@ -1,121 +1,121 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaNodeTests : TestFixtureBase
{
[Test]
public void AddSchema()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string"",""maxLength"":10},
""secondproperty"":{
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{
""extends"":{
""properties"":
{
""secondproperty_firstproperty"":{""maxLength"":9,""minLength"":6}
}
},
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{}
}
},
""thirdproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, secondSchema);
Assert.AreEqual(2, node.Schemas.Count);
Assert.AreEqual(2, node.Properties["firstproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Properties["secondproperty_firstproperty"].Schemas.Count);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, schema);
Assert.AreEqual(1, node.Schemas.Count);
Assert.AreEqual(node, node.Items[0]);
}
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaNodeTests : TestFixtureBase
{
[Test]
public void AddSchema()
{
string first = @"{
""id"":""first"",
""type"":""object"",
""properties"":
{
""firstproperty"":{""type"":""string"",""maxLength"":10},
""secondproperty"":{
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{""type"":""string"",""maxLength"":10,""minLength"":7}
}
}
},
""additionalProperties"":{}
}";
string second = @"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""properties"":
{
""firstproperty"":{""type"":""string""},
""secondproperty"":{
""extends"":{
""properties"":
{
""secondproperty_firstproperty"":{""maxLength"":9,""minLength"":6}
}
},
""type"":""object"",
""properties"":
{
""secondproperty_firstproperty"":{}
}
},
""thirdproperty"":{""type"":""string""}
},
""additionalProperties"":false
}";
JsonSchemaResolver resolver = new JsonSchemaResolver();
JsonSchema firstSchema = JsonSchema.Parse(first, resolver);
JsonSchema secondSchema = JsonSchema.Parse(second, resolver);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, secondSchema);
Assert.AreEqual(2, node.Schemas.Count);
Assert.AreEqual(2, node.Properties["firstproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Schemas.Count);
Assert.AreEqual(3, node.Properties["secondproperty"].Properties["secondproperty_firstproperty"].Schemas.Count);
}
[Test]
public void CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
JsonSchemaModelBuilder modelBuilder = new JsonSchemaModelBuilder();
JsonSchemaNode node = modelBuilder.AddSchema(null, schema);
Assert.AreEqual(1, node.Schemas.Count);
Assert.AreEqual(node, node.Items[0]);
}
}
}
@@ -1,431 +1,431 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaTests : TestFixtureBase
{
[Test]
public void Extends()
{
string json;
JsonSchemaResolver resolver = new JsonSchemaResolver();
json = @"{
""id"":""first"",
""type"":""object"",
""additionalProperties"":{}
}";
JsonSchema first = JsonSchema.Parse(json, resolver);
json =
@"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""additionalProperties"":{""type"":""string""}
}";
JsonSchema second = JsonSchema.Parse(json, resolver);
Assert.AreEqual(first, second.Extends);
json =
@"{
""id"":""third"",
""type"":""object"",
""extends"":{""$ref"":""second""},
""additionalProperties"":false
}";
JsonSchema third = JsonSchema.Parse(json, resolver);
Assert.AreEqual(second, third.Extends);
Assert.AreEqual(first, third.Extends.Extends);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter, resolver);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""$ref"": ""second""
}
}", writtenJson);
StringWriter writer1 = new StringWriter();
JsonTextWriter jsonWriter1 = new JsonTextWriter(writer1);
jsonWriter1.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter1);
writtenJson = writer1.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""id"": ""second"",
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": {
""id"": ""first"",
""type"": ""object"",
""additionalProperties"": {}
}
}
}", writtenJson);
}
[Test]
public void WriteTo_AdditionalProperties()
{
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}");
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""AdditionalProperties"",
""type"": [
""string"",
""integer""
],
""additionalProperties"": {
""type"": [
""boolean"",
""object""
]
}
}", json);
}
[Test]
public void WriteTo_Properties()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":
{
""type"":""array"",
""items"": {""type"":""string""}
}
}
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""A person"",
""type"": ""object"",
""properties"": {
""name"": {
""type"": ""string""
},
""hobbies"": {
""type"": ""array"",
""items"": {
""type"": ""string""
}
}
}
}", json);
}
[Test]
public void WriteTo_Enum()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""enum"": [
""string"",
""object"",
""array"",
""boolean"",
""number"",
""integer"",
""null"",
""any""
]
}", json);
}
[Test]
public void WriteTo_CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""CircularReferenceArray"",
""description"": ""CircularReference"",
""type"": ""array"",
""items"": {
""$ref"": ""CircularReferenceArray""
}
}", writtenJson);
}
[Test]
public void WriteTo_DisallowMultiple()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":[""string"",""object"",""array""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": [
""string"",
""object"",
""array""
]
}", json);
}
[Test]
public void WriteTo_DisallowSingle()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":""any""
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": ""any""
}", json);
}
[Test]
public void WriteTo_MultipleItems()
{
JsonSchema schema = JsonSchema.Parse(@"{
""items"":[{},{}]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": [
{},
{}
]
}", json);
}
[Test]
public void ReadOptions()
{
JsonSchema schema = JsonSchema.Parse(@"{
""type"": ""object"",
""properties"": {
""x"": {
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
}");
Assert.AreEqual(schema.Properties["x"].Options.Count, 3);
Assert.AreEqual(schema.Properties["x"].Options[0], "No");
Assert.AreEqual(schema.Properties["x"].Options[1], "Asc");
Assert.AreEqual(schema.Properties["x"].Options[-1], "Desc");
}
[Test]
public void WriteTo_ExclusiveMinimum_ExclusiveMaximum()
{
JsonSchema schema = new JsonSchema();
schema.ExclusiveMinimum = true;
schema.ExclusiveMaximum = true;
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""exclusiveMinimum"": true,
""exclusiveMaximum"": true
}", json);
}
[Test]
public void WriteTo_PatternProperties()
{
JsonSchema schema = new JsonSchema();
schema.PatternProperties = new Dictionary<string, JsonSchema>
{
{ "[abc]", new JsonSchema() }
};
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""patternProperties"": {
""[abc]"": {}
}
}", json);
}
}
}
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Schema;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Newtonsoft.Json.Tests.Schema
{
[TestFixture]
public class JsonSchemaTests : TestFixtureBase
{
[Test]
public void Extends()
{
string json;
JsonSchemaResolver resolver = new JsonSchemaResolver();
json = @"{
""id"":""first"",
""type"":""object"",
""additionalProperties"":{}
}";
JsonSchema first = JsonSchema.Parse(json, resolver);
json =
@"{
""id"":""second"",
""type"":""object"",
""extends"":{""$ref"":""first""},
""additionalProperties"":{""type"":""string""}
}";
JsonSchema second = JsonSchema.Parse(json, resolver);
Assert.AreEqual(first, second.Extends);
json =
@"{
""id"":""third"",
""type"":""object"",
""extends"":{""$ref"":""second""},
""additionalProperties"":false
}";
JsonSchema third = JsonSchema.Parse(json, resolver);
Assert.AreEqual(second, third.Extends);
Assert.AreEqual(first, third.Extends.Extends);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter, resolver);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""$ref"": ""second""
}
}", writtenJson);
StringWriter writer1 = new StringWriter();
JsonTextWriter jsonWriter1 = new JsonTextWriter(writer1);
jsonWriter1.Formatting = Formatting.Indented;
third.WriteTo(jsonWriter1);
writtenJson = writer1.ToString();
Assert.AreEqual(@"{
""id"": ""third"",
""type"": ""object"",
""additionalProperties"": false,
""extends"": {
""id"": ""second"",
""type"": ""object"",
""additionalProperties"": {
""type"": ""string""
},
""extends"": {
""id"": ""first"",
""type"": ""object"",
""additionalProperties"": {}
}
}
}", writtenJson);
}
[Test]
public void WriteTo_AdditionalProperties()
{
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""AdditionalProperties"",
""type"":[""string"", ""integer""],
""additionalProperties"":{""type"":[""object"", ""boolean""]}
}");
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""AdditionalProperties"",
""type"": [
""string"",
""integer""
],
""additionalProperties"": {
""type"": [
""boolean"",
""object""
]
}
}", json);
}
[Test]
public void WriteTo_Properties()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""A person"",
""type"":""object"",
""properties"":
{
""name"":{""type"":""string""},
""hobbies"":
{
""type"":""array"",
""items"": {""type"":""string""}
}
}
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""A person"",
""type"": ""object"",
""properties"": {
""name"": {
""type"": ""string""
},
""hobbies"": {
""type"": ""array"",
""items"": {
""type"": ""string""
}
}
}
}", json);
}
[Test]
public void WriteTo_Enum()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""enum"": [
""string"",
""object"",
""array"",
""boolean"",
""number"",
""integer"",
""null"",
""any""
]
}", json);
}
[Test]
public void WriteTo_CircularReference()
{
string json = @"{
""id"":""CircularReferenceArray"",
""description"":""CircularReference"",
""type"":[""array""],
""items"":{""$ref"":""CircularReferenceArray""}
}";
JsonSchema schema = JsonSchema.Parse(json);
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string writtenJson = writer.ToString();
Assert.AreEqual(@"{
""id"": ""CircularReferenceArray"",
""description"": ""CircularReference"",
""type"": ""array"",
""items"": {
""$ref"": ""CircularReferenceArray""
}
}", writtenJson);
}
[Test]
public void WriteTo_DisallowMultiple()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":[""string"",""object"",""array""]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": [
""string"",
""object"",
""array""
]
}", json);
}
[Test]
public void WriteTo_DisallowSingle()
{
JsonSchema schema = JsonSchema.Parse(@"{
""description"":""Type"",
""type"":[""string"",""array""],
""items"":{},
""disallow"":""any""
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""description"": ""Type"",
""type"": [
""string"",
""array""
],
""items"": {},
""disallow"": ""any""
}", json);
}
[Test]
public void WriteTo_MultipleItems()
{
JsonSchema schema = JsonSchema.Parse(@"{
""items"":[{},{}]
}");
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""items"": [
{},
{}
]
}", json);
}
[Test]
public void ReadOptions()
{
JsonSchema schema = JsonSchema.Parse(@"{
""type"": ""object"",
""properties"": {
""x"": {
""type"": ""integer"",
""enum"": [
0,
1,
-1
],
""options"": [
{
""value"": 0,
""label"": ""No""
},
{
""value"": 1,
""label"": ""Asc""
},
{
""value"": -1,
""label"": ""Desc""
}
]
}
}
}");
Assert.AreEqual(schema.Properties["x"].Options.Count, 3);
Assert.AreEqual(schema.Properties["x"].Options[0], "No");
Assert.AreEqual(schema.Properties["x"].Options[1], "Asc");
Assert.AreEqual(schema.Properties["x"].Options[-1], "Desc");
}
[Test]
public void WriteTo_ExclusiveMinimum_ExclusiveMaximum()
{
JsonSchema schema = new JsonSchema();
schema.ExclusiveMinimum = true;
schema.ExclusiveMaximum = true;
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""exclusiveMinimum"": true,
""exclusiveMaximum"": true
}", json);
}
[Test]
public void WriteTo_PatternProperties()
{
JsonSchema schema = new JsonSchema();
schema.PatternProperties = new Dictionary<string, JsonSchema>
{
{ "[abc]", new JsonSchema() }
};
StringWriter writer = new StringWriter();
JsonTextWriter jsonWriter = new JsonTextWriter(writer);
jsonWriter.Formatting = Formatting.Indented;
schema.WriteTo(jsonWriter);
string json = writer.ToString();
Assert.AreEqual(@"{
""patternProperties"": {
""[abc]"": {}
}
}", json);
}
}
}