File: IsoDateTimeConverterTests.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 (272 lines) | stat: -rw-r--r-- 10,860 bytes parent folder | download | duplicates (2)
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
#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 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 Newtonsoft.Json.Converters;
using Newtonsoft.Json.Utilities;
using System.Globalization;

namespace Newtonsoft.Json.Tests.Converters
{
  [TestFixture]
  public class IsoDateTimeConverterTests : TestFixtureBase
  {
    [Test]
    public void PropertiesShouldBeSet()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter();
      Assert.AreEqual(CultureInfo.CurrentCulture, converter.Culture);
      Assert.AreEqual(string.Empty, converter.DateTimeFormat);
      Assert.AreEqual(DateTimeStyles.RoundtripKind, converter.DateTimeStyles);

      converter = new IsoDateTimeConverter()
      {
        DateTimeFormat = "F",
        Culture = CultureInfo.InvariantCulture,
        DateTimeStyles = DateTimeStyles.None
      };

      Assert.AreEqual(CultureInfo.InvariantCulture, converter.Culture);
      Assert.AreEqual("F", converter.DateTimeFormat);
      Assert.AreEqual(DateTimeStyles.None, converter.DateTimeStyles);
    }

    [Test]
    public void SerializeDateTime()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter();

      DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Utc);
      string result;

      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""2000-12-15T22:11:03.055Z""", result);

      Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));

      d = new DateTime(2000, 12, 15, 22, 11, 3, 55, DateTimeKind.Local);
      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""2000-12-15T22:11:03.055" + d.GetUtcOffsetText() + @"""", result);
    }

    [Test]
    public void SerializeFormattedDateTimeInvariantCulture()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.InvariantCulture };

      DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
      string result;

      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);

      Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));

      d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""Friday, 15 December 2000 22:11:03""", result);
    }

    [Test]
    public void SerializeCustomFormattedDateTime()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter
                                         {
                                           DateTimeFormat = "dd/MM/yyyy",
                                           Culture = CultureInfo.InvariantCulture
                                         };

      string json = @"""09/12/2006""";

      DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);

      Assert.AreEqual(9, d.Day);
      Assert.AreEqual(12, d.Month);
      Assert.AreEqual(2006, d.Year);
    }

#if !SILVERLIGHT && !NETFX_CORE
    [Test]
    public void SerializeFormattedDateTimeNewZealandCulture()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter() { DateTimeFormat = "F", Culture = CultureInfo.GetCultureInfo("en-NZ") };

      DateTime d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Utc);
      string result;

      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);

      Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTime>(result, converter));

      d = new DateTime(2000, 12, 15, 22, 11, 3, 0, DateTimeKind.Local);
      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""Friday, 15 December 2000 10:11:03 p.m.""", result);
    }

    [Test]
    public void SerializeDateTimeCulture()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter() { Culture = CultureInfo.GetCultureInfo("en-NZ") };

      string json = @"""09/12/2006""";

      DateTime d = JsonConvert.DeserializeObject<DateTime>(json, converter);

      Assert.AreEqual(9, d.Day);
      Assert.AreEqual(12, d.Month);
      Assert.AreEqual(2006, d.Year);
    }
#endif

#if !PocketPC && !NET20
    [Test]
    public void SerializeDateTimeOffset()
    {
      IsoDateTimeConverter converter = new IsoDateTimeConverter();

      DateTimeOffset d = new DateTimeOffset(2000, 12, 15, 22, 11, 3, 55, TimeSpan.Zero);
      string result;

      result = JsonConvert.SerializeObject(d, converter);
      Assert.AreEqual(@"""2000-12-15T22:11:03.055+00:00""", result);

      Assert.AreEqual(d, JsonConvert.DeserializeObject<DateTimeOffset>(result, converter));
    }

    [Test]
    public void SerializeUTC()
    {
      DateTimeTestClass c = new DateTimeTestClass();
      c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
      c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
      c.PreField = "Pre";
      c.PostField = "Post";
      string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
      Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);

      //test the other edge case too
      c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
      c.DateTimeOffsetField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc).ToLocalTime();
      c.PreField = "Pre";
      c.PostField = "Post";
      json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
      Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-01-01T01:01:01Z"",""DateTimeOffsetField"":""2008-01-01T01:01:01+00:00"",""PostField"":""Post""}", json);
    }

    [Test]
    public void NullableSerializeUTC()
    {
      NullableDateTimeTestClass c = new NullableDateTimeTestClass();
      c.DateTimeField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
      c.DateTimeOffsetField = new DateTime(2008, 12, 12, 12, 12, 12, 0, DateTimeKind.Utc).ToLocalTime();
      c.PreField = "Pre";
      c.PostField = "Post";
      string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
      Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":""2008-12-12T12:12:12Z"",""DateTimeOffsetField"":""2008-12-12T12:12:12+00:00"",""PostField"":""Post""}", json);

      //test the other edge case too
      c.DateTimeField = null;
      c.DateTimeOffsetField = null;
      c.PreField = "Pre";
      c.PostField = "Post";
      json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
      Assert.AreEqual(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", json);
    }

    [Test]
    public void NullableDeserializeEmptyString()
    {
      string json = @"{""DateTimeField"":""""}";

      NullableDateTimeTestClass c = JsonConvert.DeserializeObject<NullableDateTimeTestClass>(json,
        new JsonSerializerSettings { Converters = new [] {new IsoDateTimeConverter()}});
      Assert.AreEqual(null, c.DateTimeField);
    }

    [Test]
    public void DeserializeNullToNonNullable()
    {
      ExceptionAssert.Throws<Exception>("Cannot convert null value to System.DateTime.",
      () =>
      {
        DateTimeTestClass c2 =
         JsonConvert.DeserializeObject<DateTimeTestClass>(@"{""PreField"":""Pre"",""DateTimeField"":null,""DateTimeOffsetField"":null,""PostField"":""Post""}", new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });
      });
    }

    [Test]
    public void SerializeShouldChangeNonUTCDates()
    {
      DateTime localDateTime = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Local);

      DateTimeTestClass c = new DateTimeTestClass();
      c.DateTimeField = localDateTime;
      c.PreField = "Pre";
      c.PostField = "Post";
      string json = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal }); //note that this fails without the Utc converter...
      c.DateTimeField = new DateTime(2008, 1, 1, 1, 1, 1, 0, DateTimeKind.Utc);
      string json2 = JsonConvert.SerializeObject(c, new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AssumeUniversal });

      TimeSpan offset = localDateTime.GetUtcOffset();

      // if the current timezone is utc then local already equals utc
      if (offset == TimeSpan.Zero)
        Assert.AreEqual(json, json2);
      else
        Assert.AreNotEqual(json, json2);
    }
#endif

    [Test]
    public void BlogCodeSample()
    {
      Person p = new Person
                   {
                     Name = "Keith",
                     BirthDate = new DateTime(1980, 3, 8),
                     LastModified = new DateTime(2009, 4, 12, 20, 44, 55),
                   };

      string jsonText = JsonConvert.SerializeObject(p, new IsoDateTimeConverter());
      // {
      //   "Name": "Keith",
      //   "BirthDate": "1980-03-08T00:00:00",
      //   "LastModified": "2009-04-12T20:44:55"
      // }

      Console.WriteLine(jsonText);

    }
  }
}