Subversion Repository Public Repository

ChrisCompleteCodeTrunk

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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#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

#pragma warning disable 618
using System;
using System.Collections.Generic;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;
using System.IO;
using Newtonsoft.Json.Tests.TestObjects;
#if !(NETFX_CORE || DNXCORE50)
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>(() =>
            {
                JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
                JToken stringToken = JToken.FromObject("pie");
                stringToken.Validate(schema);
            }, @"String 'pie' does not match regex pattern 'lol'.");
        }

        [Test]
        public void ValidateWithOutEventHandlerSuccess()
        {
            JsonSchema schema = JsonSchema.Parse("{'pattern':'lol'}");
            JToken stringToken = JToken.FromObject("pie lol");
            stringToken.Validate(schema);
        }

        [Test]
        public void ValidateFailureWithOutLineInfoBecauseOfEndToken()
        {
            // changed in 6.0.6 to now include line info!
            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. Line 1, position 1.", errors[0]);
            Assert.AreEqual(1, errors.Count);
        }

        [Test]
        public void ValidateRequiredFieldsWithLineInfo()
        {
            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
            GenerateSchemaAndSerializeFromType(new NullableDateTimeTestClass());
#endif
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
            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 || PORTABLE || DNXCORE50 || PORTABLE40)
            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>(() =>
            {
                JsonSchema schema = new JsonSchema();
                schema.Maximum = 10;
                schema.ExclusiveMaximum = true;

                JValue v = new JValue(10);
                v.Validate(schema);
            }, "Integer 10 equals maximum value of 10 and exclusive maximum is true.");
        }

        [Test]
        public void ExclusiveMaximum_Float()
        {
            ExceptionAssert.Throws<JsonSchemaException>(() =>
            {
                JsonSchema schema = new JsonSchema();
                schema.Maximum = 10.1;
                schema.ExclusiveMaximum = true;

                JValue v = new JValue(10.1);
                v.Validate(schema);
            }, "Float 10.1 equals maximum value of 10.1 and exclusive maximum is true.");
        }

        [Test]
        public void ExclusiveMinimum_Int()
        {
            ExceptionAssert.Throws<JsonSchemaException>(() =>
            {
                JsonSchema schema = new JsonSchema();
                schema.Minimum = 10;
                schema.ExclusiveMinimum = true;

                JValue v = new JValue(10);
                v.Validate(schema);
            }, "Integer 10 equals minimum value of 10 and exclusive minimum is true.");
        }

        [Test]
        public void ExclusiveMinimum_Float()
        {
            ExceptionAssert.Throws<JsonSchemaException>(() =>
            {
                JsonSchema schema = new JsonSchema();
                schema.Minimum = 10.1;
                schema.ExclusiveMinimum = true;

                JValue v = new JValue(10.1);
                v.Validate(schema);
            }, "Float 10.1 equals minimum value of 10.1 and exclusive minimum is true.");
        }

        [Test]
        public void DivisibleBy_Int()
        {
            ExceptionAssert.Throws<JsonSchemaException>(() =>
            {
                JsonSchema schema = new JsonSchema();
                schema.DivisibleBy = 3;

                JValue v = new JValue(10);
                v.Validate(schema);
            }, "Integer 10 is not evenly divisible by 3.");
        }

        [Test]
        public void DivisibleBy_Approx()
        {
            JsonSchema schema = new JsonSchema();
            schema.DivisibleBy = 0.01;

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

        [Test]
        public void UniqueItems_SimpleUnique()
        {
            JsonSchema schema = new JsonSchema();
            schema.UniqueItems = true;

            JArray a = new JArray(1, 2, 3);
            Assert.IsTrue(a.IsValid(schema));
        }

        [Test]
        public void UniqueItems_SimpleDuplicate()
        {
            JsonSchema schema = new JsonSchema();
            schema.UniqueItems = true;

            JArray a = new JArray(1, 2, 3, 2, 2);
            IList<string> errorMessages;
            Assert.IsFalse(a.IsValid(schema, out errorMessages));
            Assert.AreEqual(2, errorMessages.Count);
            Assert.AreEqual("Non-unique array item at index 3.", errorMessages[0]);
            Assert.AreEqual("Non-unique array item at index 4.", errorMessages[1]);
        }

        [Test]
        public void UniqueItems_ComplexDuplicate()
        {
            JsonSchema schema = new JsonSchema();
            schema.UniqueItems = true;

            JArray a = new JArray(1, new JObject(new JProperty("value", "value!")), 3, 2, new JObject(new JProperty("value", "value!")), 4, 2, new JObject(new JProperty("value", "value!")));
            IList<string> errorMessages;
            Assert.IsFalse(a.IsValid(schema, out errorMessages));
            Assert.AreEqual(3, errorMessages.Count);
            Assert.AreEqual("Non-unique array item at index 4.", errorMessages[0]);
            Assert.AreEqual("Non-unique array item at index 6.", errorMessages[1]);
            Assert.AreEqual("Non-unique array item at index 7.", errorMessages[2]);
        }

        [Test]
        public void UniqueItems_NestedDuplicate()
        {
            JsonSchema schema = new JsonSchema();
            schema.UniqueItems = true;
            schema.Items = new List<JsonSchema>
            {
                new JsonSchema
                {
                    UniqueItems = true
                }
            };
            schema.PositionalItemsValidation = false;

            JArray a = new JArray(
                new JArray(1, 2),
                new JArray(1, 1),
                new JArray(3, 4),
                new JArray(1, 2),
                new JArray(1, 1)
                );
            IList<string> errorMessages;
            Assert.IsFalse(a.IsValid(schema, out errorMessages));
            Assert.AreEqual(4, errorMessages.Count);
            Assert.AreEqual("Non-unique array item at index 1.", errorMessages[0]);
            Assert.AreEqual("Non-unique array item at index 3.", errorMessages[1]);
            Assert.AreEqual("Non-unique array item at index 1.", errorMessages[2]);
            Assert.AreEqual("Non-unique array item at index 4.", errorMessages[3]);
        }

        [Test]
        public void Enum_Properties()
        {
            JsonSchema schema = new JsonSchema();
            schema.Properties = new Dictionary<string, JsonSchema>
            {
                {
                    "bar",
                    new JsonSchema
                    {
                        Enum = new List<JToken>
                        {
                            new JValue(1),
                            new JValue(2)
                        }
                    }
                }
            };

            JObject o = new JObject(
                new JProperty("bar", 1)
                );
            IList<string> errorMessages;
            Assert.IsTrue(o.IsValid(schema, out errorMessages));
            Assert.AreEqual(0, errorMessages.Count);

            o = new JObject(
                new JProperty("bar", 3)
                );
            Assert.IsFalse(o.IsValid(schema, out errorMessages));
            Assert.AreEqual(1, errorMessages.Count);
        }

        [Test]
        public void UniqueItems_Property()
        {
            JsonSchema schema = new JsonSchema();
            schema.Properties = new Dictionary<string, JsonSchema>
            {
                {
                    "bar",
                    new JsonSchema
                    {
                        UniqueItems = true
                    }
                }
            };

            JObject o = new JObject(
                new JProperty("bar", new JArray(1, 2, 3, 3))
                );
            IList<string> errorMessages;
            Assert.IsFalse(o.IsValid(schema, out errorMessages));
            Assert.AreEqual(1, errorMessages.Count);
        }

        [Test]
        public void Items_Positional()
        {
            JsonSchema schema = new JsonSchema();
            schema.Items = new List<JsonSchema>
            {
                new JsonSchema { Type = JsonSchemaType.Object },
                new JsonSchema { Type = JsonSchemaType.Integer }
            };
            schema.PositionalItemsValidation = true;

            JArray a = new JArray(new JObject(), 1);
            IList<string> errorMessages;
            Assert.IsTrue(a.IsValid(schema, out errorMessages));
            Assert.AreEqual(0, errorMessages.Count);
        }
    }
}

#pragma warning restore 618

Commits for ChrisCompleteCodeTrunk/M3Workflow/Libraries/Json90r1/Source/Src/Newtonsoft.Json.Tests/Schema/ExtensionsTests.cs

Diff revisions: vs.
Revision Author Commited Message
1 BBDSCHRIS picture BBDSCHRIS Wed 22 Aug, 2018 20:08:03 +0000