Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ExtensionsTests.cs « Schema « Newtonsoft.Json.Tests « Src - github.com/mono/Newtonsoft.Json.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 36e042ab8aa0e567266eebde226884da51240790 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#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;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !SILVERLIGHT
using System.Data;
#endif

namespace Newtonsoft.Json.Tests.Schema
{
  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]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = @"String 'pie' does not match regex pattern 'lol'.")]
    public void ValidateWithOutEventHandlerFailure()
    {
      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
      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));
      GenerateSchemaAndSerializeFromType(DBNull.Value);
      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]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 equals maximum value of 10 and exclusive maximum is true.")]
    public void ExclusiveMaximum_Int()
    {
      JsonSchema schema = new JsonSchema();
      schema.Maximum = 10;
      schema.ExclusiveMaximum = true;

      JValue v = new JValue(10);
      v.Validate(schema);
    }

    [Test]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.")]
    public void ExclusiveMaximum_Float()
    {
      JsonSchema schema = new JsonSchema();
      schema.Maximum = 10.1;
      schema.ExclusiveMaximum = true;

      JValue v = new JValue(10.1);
      v.Validate(schema);
    }

    [Test]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 equals minimum value of 10 and exclusive minimum is true.")]
    public void ExclusiveMinimum_Int()
    {
      JsonSchema schema = new JsonSchema();
      schema.Minimum = 10;
      schema.ExclusiveMinimum = true;

      JValue v = new JValue(10);
      v.Validate(schema);
    }

    [Test]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.")]
    public void ExclusiveMinimum_Float()
    {
      JsonSchema schema = new JsonSchema();
      schema.Minimum = 10.1;
      schema.ExclusiveMinimum = true;

      JValue v = new JValue(10.1);
      v.Validate(schema);
    }

    [Test]
    [ExpectedException(typeof(JsonSchemaException), ExpectedMessage = "Integer 10 is not evenly divisible by 3.")]
    public void DivisibleBy_Int()
    {
      JsonSchema schema = new JsonSchema();
      schema.DivisibleBy = 3;

      JValue v = new JValue(10);
      v.Validate(schema);
    }
  }
}