File: SerializationErrorHandlingTests.cs

package info (click to toggle)
mono 4.6.2.7+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (351 lines) | stat: -rw-r--r-- 11,191 bytes parent folder | download
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
#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 Newtonsoft.Json.Converters;
using Newtonsoft.Json.Tests.TestObjects;
#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 System.IO;
using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;

namespace Newtonsoft.Json.Tests.Serialization
{
  [TestFixture]
  public class SerializationErrorHandlingTests : TestFixtureBase
  {
    [Test]
    public void ErrorDeserializingListHandled()
    {
      string json = @"[
  {
    ""Name"": ""Jim"",
    ""BirthDate"": ""\/Date(978048000000)\/"",
    ""LastModified"": ""\/Date(978048000000)\/""
  },
  {
    ""Name"": ""Jim"",
    ""BirthDate"": ""\/Date(978048000000)\/"",
    ""LastModified"": ""\/Date(978048000000)\/""
  }
]";

      VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
      Assert.AreEqual(1, c.Count);
      Assert.AreEqual(1, c.Messages.Count);
      Assert.AreEqual("[1] - Error message for member 1 = An item with the same key has already been added.", c.Messages[0]);
    }

    [Test]
    public void DeserializingErrorInChildObject()
    {
      ListErrorObjectCollection c = JsonConvert.DeserializeObject<ListErrorObjectCollection>(@"[
  {
    ""Member"": ""Value1"",
    ""Member2"": null
  },
  {
    ""Member"": ""Value2""
  },
  {
    ""ThrowError"": ""Value"",
    ""Object"": {
      ""Array"": [
        1,
        2
      ]
    }
  },
  {
    ""ThrowError"": ""Handle this!"",
    ""Member"": ""Value3""
  }
]");

      Assert.AreEqual(3, c.Count);
      Assert.AreEqual("Value1", c[0].Member);
      Assert.AreEqual("Value2", c[1].Member);
      Assert.AreEqual("Value3", c[2].Member);
      Assert.AreEqual("Handle this!", c[2].ThrowError);
    }

    [Test]
    public void SerializingErrorInChildObject()
    {
      ListErrorObjectCollection c = new ListErrorObjectCollection
        {
          new ListErrorObject
            {
              Member = "Value1",
              ThrowError = "Handle this!",
              Member2 = "Member1"
            },
          new ListErrorObject
            {
              Member = "Value2",
              Member2 = "Member2"
            },
          new ListErrorObject
            {
              Member = "Value3",
              ThrowError = "Handle that!",
              Member2 = "Member3"
            }
        };

      string json = JsonConvert.SerializeObject(c, Formatting.Indented);

      Assert.AreEqual(@"[
  {
    ""Member"": ""Value1"",
    ""ThrowError"": ""Handle this!"",
    ""Member2"": ""Member1""
  },
  {
    ""Member"": ""Value2""
  },
  {
    ""Member"": ""Value3"",
    ""ThrowError"": ""Handle that!"",
    ""Member2"": ""Member3""
  }
]", json);
    }

    [Test]
    public void DeserializingErrorInDateTimeCollection()
    {
      DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(@"[
  ""2009-09-09T00:00:00Z"",
  ""kjhkjhkjhkjh"",
  [
    1
  ],
  ""1977-02-20T00:00:00Z"",
  null,
  ""2000-12-01T00:00:00Z""
]", new IsoDateTimeConverter());

      Assert.AreEqual(3, c.Count);
      Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
      Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
      Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
    }

    [Test]
    public void DeserializingErrorHandlingUsingEvent()
    {
      List<string> errors = new List<string>();

      List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(
        @"[
        ""2009-09-09T00:00:00Z"",
        ""I am not a date and will error!"",
        [
          1
        ],
        ""1977-02-20T00:00:00Z"",
        null,
        ""2000-12-01T00:00:00Z""
      ]",
        new JsonSerializerSettings
          {
            Error = delegate(object sender, ErrorEventArgs args)
              {
                errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
                args.ErrorContext.Handled = true;
              },
            Converters = {new IsoDateTimeConverter()}
          });

      // 2009-09-09T00:00:00Z
      // 1977-02-20T00:00:00Z
      // 2000-12-01T00:00:00Z

      // The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
      // Unexpected token parsing date. Expected String, got StartArray.
      // Cannot convert null value to System.DateTime.

      Assert.AreEqual(3, c.Count);
      Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
      Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
      Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);

      Assert.AreEqual(3, errors.Count);
#if !(NET20 || NET35 || WINDOWS_PHONE)
      Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", errors[0]);
#else
      Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]);
#endif
      Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray.", errors[1]);
      Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime.", errors[2]);
    }

    [Test]
    public void DeserializingErrorInDateTimeCollectionWithAttributeWithEventNotCalled()
    {
      bool eventErrorHandlerCalled = false;

      DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(
        @"[
  ""2009-09-09T00:00:00Z"",
  ""kjhkjhkjhkjh"",
  [
    1
  ],
  ""1977-02-20T00:00:00Z"",
  null,
  ""2000-12-01T00:00:00Z""
]",
        new JsonSerializerSettings
          {
            Error = (s, a) => eventErrorHandlerCalled = true,
            Converters =
              {
                new IsoDateTimeConverter()
              }
          });

      Assert.AreEqual(3, c.Count);
      Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
      Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
      Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);

      Assert.AreEqual(false, eventErrorHandlerCalled);
    }

    [Test]
    public void SerializePerson()
    {
      PersonError person = new PersonError
        {
          Name = "George Michael Bluth",
          Age = 16,
          Roles = null,
          Title = "Mister Manager"
        };

      string json = JsonConvert.SerializeObject(person, Formatting.Indented);

      Console.WriteLine(json);
      //{
      //  "Name": "George Michael Bluth",
      //  "Age": 16,
      //  "Title": "Mister Manager"
      //}

      Assert.AreEqual(@"{
  ""Name"": ""George Michael Bluth"",
  ""Age"": 16,
  ""Title"": ""Mister Manager""
}", json);
    }

    [Test]
    public void DeserializeNestedUnhandled()
    {
      List<string> errors = new List<string>();

      string json = @"[[""kjhkjhkjhkjh""]]";

      Exception e = null;
      try
      {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Error += delegate(object sender, ErrorEventArgs args)
        {
          // only log an error once
          if (args.CurrentObject == args.ErrorContext.OriginalObject)
            errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
        };

        serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
      }
      catch (Exception ex)
      {
        e = ex;
      }

      Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", e.Message);

      Assert.AreEqual(1, errors.Count);
      Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", errors[0]);
    }

    [Test]
    public void MultipleRequiredPropertyErrors()
    {
      string json = "{}";
      List<string> errors = new List<string>();
      JsonSerializer serializer = new JsonSerializer();
      serializer.Error += delegate(object sender, ErrorEventArgs args)
        {
          errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
          args.ErrorContext.Handled = true;
        };
      serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers));
      
      Assert.AreEqual(2, errors.Count);
      Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Line 1, position 2.", errors[0]);
      Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Line 1, position 2.", errors[1]);
    }

    [Test]
    public void HandlingArrayErrors()
    {
      string json = "[\"a\",\"b\",\"45\",34]";

      List<string> errors = new List<string>();

      JsonSerializer serializer = new JsonSerializer();
      serializer.Error += delegate(object sender, ErrorEventArgs args)
      {
        errors.Add(args.ErrorContext.Path + " - " + args.ErrorContext.Member + " - " + args.ErrorContext.Error.Message);
        args.ErrorContext.Handled = true;
      };

      serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[]));

      Assert.AreEqual(2, errors.Count);
      Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Line 1, position 4.", errors[0]);
      Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Line 1, position 8.", errors[1]);
    }
  }

  [JsonObject]
  public class MyTypeWithRequiredMembers
  {
    [JsonProperty(Required = Required.AllowNull)]
    public string Required1;
    [JsonProperty(Required = Required.AllowNull)]
    public string Required2;
  }
}