All files
[pithos-ms-client] / trunk / Libraries / Json40r2 / Source / Src / Newtonsoft.Json.Tests / Serialization / SerializationErrorHandlingTests.cs
1 #region License
2 // Copyright (c) 2007 James Newton-King
3 //
4 // Permission is hereby granted, free of charge, to any person
5 // obtaining a copy of this software and associated documentation
6 // files (the "Software"), to deal in the Software without
7 // restriction, including without limitation the rights to use,
8 // copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following
11 // conditions:
12 //
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 // OTHER DEALINGS IN THE SOFTWARE.
24 #endregion
25
26 using System;
27 using System.Collections.Generic;
28 using System.Linq;
29 using System.Text;
30 using Newtonsoft.Json.Converters;
31 using Newtonsoft.Json.Tests.TestObjects;
32 using NUnit.Framework;
33 using Newtonsoft.Json.Serialization;
34 using System.IO;
35 using ErrorEventArgs=Newtonsoft.Json.Serialization.ErrorEventArgs;
36
37 namespace Newtonsoft.Json.Tests.Serialization
38 {
39   public class SerializationErrorHandlingTests : TestFixtureBase
40   {
41     [Test]
42     public void ErrorDeserializingListHandled()
43     {
44       string json = @"[
45   {
46     ""Name"": ""Jim"",
47     ""BirthDate"": ""\/Date(978048000000)\/"",
48     ""LastModified"": ""\/Date(978048000000)\/""
49   },
50   {
51     ""Name"": ""Jim"",
52     ""BirthDate"": ""\/Date(978048000000)\/"",
53     ""LastModified"": ""\/Date(978048000000)\/""
54   }
55 ]";
56
57       VersionKeyedCollection c = JsonConvert.DeserializeObject<VersionKeyedCollection>(json);
58       Assert.AreEqual(1, c.Count);
59       Assert.AreEqual(1, c.Messages.Count);
60       Assert.AreEqual("Error message for member 1 = An item with the same key has already been added.", c.Messages[0]);
61     }
62
63     [Test]
64     public void DeserializingErrorInChildObject()
65     {
66       ListErrorObjectCollection c = JsonConvert.DeserializeObject<ListErrorObjectCollection>(@"[
67   {
68     ""Member"": ""Value1"",
69     ""Member2"": null
70   },
71   {
72     ""Member"": ""Value2""
73   },
74   {
75     ""ThrowError"": ""Value"",
76     ""Object"": {
77       ""Array"": [
78         1,
79         2
80       ]
81     }
82   },
83   {
84     ""ThrowError"": ""Handle this!"",
85     ""Member"": ""Value3""
86   }
87 ]");
88
89       Assert.AreEqual(3, c.Count);
90       Assert.AreEqual("Value1", c[0].Member);
91       Assert.AreEqual("Value2", c[1].Member);
92       Assert.AreEqual("Value3", c[2].Member);
93       Assert.AreEqual("Handle this!", c[2].ThrowError);
94     }
95
96     [Test]
97     public void SerializingErrorInChildObject()
98     {
99       ListErrorObjectCollection c = new ListErrorObjectCollection
100         {
101           new ListErrorObject
102             {
103               Member = "Value1",
104               ThrowError = "Handle this!",
105               Member2 = "Member1"
106             },
107           new ListErrorObject
108             {
109               Member = "Value2",
110               Member2 = "Member2"
111             },
112           new ListErrorObject
113             {
114               Member = "Value3",
115               ThrowError = "Handle that!",
116               Member2 = "Member3"
117             }
118         };
119
120       string json = JsonConvert.SerializeObject(c, Formatting.Indented);
121
122       Assert.AreEqual(@"[
123   {
124     ""Member"": ""Value1"",
125     ""ThrowError"": ""Handle this!"",
126     ""Member2"": ""Member1""
127   },
128   {
129     ""Member"": ""Value2""
130   },
131   {
132     ""Member"": ""Value3"",
133     ""ThrowError"": ""Handle that!"",
134     ""Member2"": ""Member3""
135   }
136 ]", json);
137     }
138
139     [Test]
140     public void DeserializingErrorInDateTimeCollection()
141     {
142       DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(@"[
143   ""2009-09-09T00:00:00Z"",
144   ""kjhkjhkjhkjh"",
145   [
146     1
147   ],
148   ""1977-02-20T00:00:00Z"",
149   null,
150   ""2000-12-01T00:00:00Z""
151 ]", new IsoDateTimeConverter());
152
153       Assert.AreEqual(3, c.Count);
154       Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
155       Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
156       Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
157     }
158
159     [Test]
160     public void DeserializingErrorHandlingUsingEvent()
161     {
162       List<string> errors = new List<string>();
163
164       List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
165         ""2009-09-09T00:00:00Z"",
166         ""I am not a date and will error!"",
167         [
168           1
169         ],
170         ""1977-02-20T00:00:00Z"",
171         null,
172         ""2000-12-01T00:00:00Z""
173       ]",
174         new JsonSerializerSettings
175           {
176             Error = delegate(object sender, ErrorEventArgs args)
177               {
178                 errors.Add(args.ErrorContext.Error.Message);
179                 args.ErrorContext.Handled = true;
180               },
181             Converters = { new IsoDateTimeConverter() }
182           });
183
184       // 2009-09-09T00:00:00Z
185       // 1977-02-20T00:00:00Z
186       // 2000-12-01T00:00:00Z
187
188       // The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
189       // Unexpected token parsing date. Expected String, got StartArray.
190       // Cannot convert null value to System.DateTime.
191
192       Assert.AreEqual(3, c.Count);
193       Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
194       Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
195       Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
196
197       Assert.AreEqual(3, errors.Count);
198 #if !(NET20 || NET35 || WINDOWS_PHONE)
199       Assert.AreEqual("The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.", errors[0]);
200 #else
201       Assert.AreEqual("The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]);
202 #endif
203       Assert.AreEqual("Unexpected token parsing date. Expected String, got StartArray.", errors[1]);
204       Assert.AreEqual("Cannot convert null value to System.DateTime.", errors[2]);
205     }
206
207     [Test]
208     public void DeserializingErrorInDateTimeCollectionWithAttributeWithEventNotCalled()
209     {
210       bool eventErrorHandlerCalled = false;
211
212       DateTimeErrorObjectCollection c = JsonConvert.DeserializeObject<DateTimeErrorObjectCollection>(@"[
213   ""2009-09-09T00:00:00Z"",
214   ""kjhkjhkjhkjh"",
215   [
216     1
217   ],
218   ""1977-02-20T00:00:00Z"",
219   null,
220   ""2000-12-01T00:00:00Z""
221 ]",
222         new JsonSerializerSettings
223         {
224           Error = (s, a) => eventErrorHandlerCalled = true,
225           Converters =
226               {
227                 new IsoDateTimeConverter()
228               }
229         });
230
231       Assert.AreEqual(3, c.Count);
232       Assert.AreEqual(new DateTime(2009, 9, 9, 0, 0, 0, DateTimeKind.Utc), c[0]);
233       Assert.AreEqual(new DateTime(1977, 2, 20, 0, 0, 0, DateTimeKind.Utc), c[1]);
234       Assert.AreEqual(new DateTime(2000, 12, 1, 0, 0, 0, DateTimeKind.Utc), c[2]);
235
236       Assert.AreEqual(false, eventErrorHandlerCalled);
237     }
238
239     [Test]
240     public void SerializePerson()
241     {
242       PersonError person = new PersonError
243         {
244           Name = "George Michael Bluth",
245           Age = 16,
246           Roles = null,
247           Title = "Mister Manager"
248         };
249
250       string json = JsonConvert.SerializeObject(person, Formatting.Indented);
251
252       Console.WriteLine(json);
253       //{
254       //  "Name": "George Michael Bluth",
255       //  "Age": 16,
256       //  "Title": "Mister Manager"
257       //}
258
259       Assert.AreEqual(@"{
260   ""Name"": ""George Michael Bluth"",
261   ""Age"": 16,
262   ""Title"": ""Mister Manager""
263 }", json);
264     }
265
266     [Test]
267     public void DeserializeNestedUnhandled()
268     {
269       List<string> errors = new List<string>();
270
271       string json = @"[[""kjhkjhkjhkjh""]]";
272
273       try
274       {
275         JsonSerializer serializer = new JsonSerializer();
276         serializer.Error += delegate(object sender, ErrorEventArgs args)
277           {
278             // only log an error once
279             if (args.CurrentObject == args.ErrorContext.OriginalObject)
280               errors.Add(args.ErrorContext.Error.Message);
281           };
282
283         serializer.Deserialize(new StringReader(json), typeof(List<List<DateTime>>));
284       }
285       catch (Exception ex)
286       {
287         Console.WriteLine(ex.Message);
288       }
289
290       Assert.AreEqual(1, errors.Count);
291       Assert.AreEqual(@"Error converting value ""kjhkjhkjhkjh"" to type 'System.DateTime'.", errors[0]);
292     }
293   }
294 }