~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
27
using System;
 
28
using System.Collections;
 
29
using System.Collections.Generic;
 
30
using System.Dynamic;
 
31
using System.Linq;
 
32
using System.Linq.Expressions;
 
33
using System.Reflection;
 
34
using System.Runtime.CompilerServices;
 
35
using System.Runtime.Serialization.Formatters;
 
36
using System.Text;
 
37
using Newtonsoft.Json.Serialization;
 
38
using Newtonsoft.Json.Tests.TestObjects;
 
39
using Newtonsoft.Json.Utilities;
 
40
#if !NETFX_CORE
 
41
using NUnit.Framework;
 
42
#else
 
43
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
44
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
45
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
46
#endif
 
47
 
 
48
namespace Newtonsoft.Json.Tests.Serialization
 
49
{
 
50
  [TestFixture]
 
51
  public class DynamicTests : TestFixtureBase
 
52
  {
 
53
    [Test]
 
54
    public void SerializeDynamicObject()
 
55
    {
 
56
      TestDynamicObject dynamicObject = new TestDynamicObject();
 
57
      dynamicObject.Explicit = true;
 
58
 
 
59
      dynamic d = dynamicObject;
 
60
      d.Int = 1;
 
61
      d.Decimal = 99.9d;
 
62
      d.ChildObject = new DynamicChildObject();
 
63
 
 
64
      Dictionary<string, object> values = new Dictionary<string, object>();
 
65
 
 
66
      foreach (string memberName in dynamicObject.GetDynamicMemberNames())
 
67
      {
 
68
        object value;
 
69
        dynamicObject.TryGetMember(memberName, out value);
 
70
 
 
71
        values.Add(memberName, value);
 
72
      }
 
73
 
 
74
      Assert.AreEqual(d.Int, values["Int"]);
 
75
      Assert.AreEqual(d.Decimal, values["Decimal"]);
 
76
      Assert.AreEqual(d.ChildObject, values["ChildObject"]);
 
77
 
 
78
      string json = JsonConvert.SerializeObject(dynamicObject, Formatting.Indented);
 
79
      Assert.AreEqual(@"{
 
80
  ""Explicit"": true,
 
81
  ""Decimal"": 99.9,
 
82
  ""Int"": 1,
 
83
  ""ChildObject"": {
 
84
    ""Text"": null,
 
85
    ""Integer"": 0
 
86
  }
 
87
}", json);
 
88
 
 
89
      TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
 
90
      Assert.AreEqual(true, newDynamicObject.Explicit);
 
91
 
 
92
      d = newDynamicObject;
 
93
 
 
94
      Assert.AreEqual(99.9, d.Decimal);
 
95
      Assert.AreEqual(1, d.Int);
 
96
      Assert.AreEqual(dynamicObject.ChildObject.Integer, d.ChildObject.Integer);
 
97
      Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text);
 
98
    }
 
99
 
 
100
    [Test]
 
101
    public void SerializeDynamicObjectWithObjectTracking()
 
102
    {
 
103
      dynamic o = new ExpandoObject();
 
104
      o.Text = "Text!";
 
105
      o.Integer = int.MaxValue;
 
106
      o.DynamicChildObject = new DynamicChildObject
 
107
        {
 
108
          Integer = int.MinValue,
 
109
          Text = "Child text!"
 
110
        };
 
111
 
 
112
      string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
 
113
        {
 
114
          TypeNameHandling = TypeNameHandling.All,
 
115
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
116
        });
 
117
 
 
118
      Console.WriteLine(json);
 
119
 
 
120
      string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full);
 
121
      string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full);
 
122
 
 
123
      Assert.AreEqual(@"{
 
124
  ""$type"": """ + expandoObjectTypeName + @""",
 
125
  ""Text"": ""Text!"",
 
126
  ""Integer"": 2147483647,
 
127
  ""DynamicChildObject"": {
 
128
    ""$type"": """ + dynamicChildObjectTypeName + @""",
 
129
    ""Text"": ""Child text!"",
 
130
    ""Integer"": -2147483648
 
131
  }
 
132
}", json);
 
133
 
 
134
      dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 
135
        {
 
136
          TypeNameHandling = TypeNameHandling.All,
 
137
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
138
        });
 
139
 
 
140
      CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n);
 
141
      Assert.AreEqual("Text!", n.Text);
 
142
      Assert.AreEqual(int.MaxValue, n.Integer);
 
143
 
 
144
      CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
 
145
      Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
 
146
      Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
 
147
    }
 
148
 
 
149
    [Test]
 
150
    public void NoPublicDefaultConstructor()
 
151
    {
 
152
      ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.",
 
153
      () =>
 
154
      {
 
155
        var settings = new JsonSerializerSettings();
 
156
        settings.NullValueHandling = NullValueHandling.Ignore;
 
157
        var json = @"{
 
158
  ""contributors"": null
 
159
}";
 
160
 
 
161
        JsonConvert.DeserializeObject<DynamicObject>(json, settings);
 
162
      });
 
163
    }
 
164
 
 
165
    public class DictionaryDynamicObject : DynamicObject
 
166
    {
 
167
      public IDictionary<string, object> Values { get; private set; }
 
168
 
 
169
      protected DictionaryDynamicObject()
 
170
      {
 
171
        Values = new Dictionary<string, object>();
 
172
      }
 
173
 
 
174
      public override bool TrySetMember(SetMemberBinder binder, object value)
 
175
      {
 
176
        Values[binder.Name] = value;
 
177
        return true;
 
178
      }
 
179
    }
 
180
 
 
181
    [Test]
 
182
    public void AllowNonPublicDefaultConstructor()
 
183
    {
 
184
      var settings = new JsonSerializerSettings();
 
185
      settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;
 
186
 
 
187
      var json = @"{
 
188
  ""contributors"": null,
 
189
  ""retweeted"": false,
 
190
  ""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
 
191
  ""in_reply_to_user_id_str"": null,
 
192
  ""retweet_count"": 0,
 
193
  ""geo"": null,
 
194
  ""id_str"": ""40678260320768000"",
 
195
  ""in_reply_to_status_id"": null,
 
196
  ""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
 
197
  ""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
 
198
  ""place"": null,
 
199
  ""coordinates"": null,
 
200
  ""truncated"": false,
 
201
  ""favorited"": false,
 
202
  ""user"": {
 
203
    ""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
 
204
    ""url"": ""http://bit.ly/dcFwWC"",
 
205
    ""screen_name"": ""marutisuzukisx4"",
 
206
    ""verified"": false,
 
207
    ""friends_count"": 45,
 
208
    ""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
 
209
    ""follow_request_sent"": null,
 
210
    ""time_zone"": ""Chennai"",
 
211
    ""profile_text_color"": ""333333"",
 
212
    ""location"": ""India"",
 
213
    ""notifications"": null,
 
214
    ""profile_sidebar_fill_color"": ""efefef"",
 
215
    ""id_str"": ""196143889"",
 
216
    ""contributors_enabled"": false,
 
217
    ""lang"": ""en"",
 
218
    ""profile_background_tile"": false,
 
219
    ""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
 
220
    ""followers_count"": 117,
 
221
    ""show_all_inline_media"": true,
 
222
    ""listed_count"": 1,
 
223
    ""geo_enabled"": true,
 
224
    ""profile_link_color"": ""009999"",
 
225
    ""profile_sidebar_border_color"": ""eeeeee"",
 
226
    ""protected"": false,
 
227
    ""name"": ""Maruti Suzuki SX4"",
 
228
    ""statuses_count"": 637,
 
229
    ""following"": null,
 
230
    ""profile_use_background_image"": true,
 
231
    ""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
 
232
    ""id"": 196143889,
 
233
    ""is_translator"": false,
 
234
    ""utc_offset"": 19800,
 
235
    ""favourites_count"": 0,
 
236
    ""profile_background_color"": ""131516""
 
237
  },
 
238
  ""in_reply_to_screen_name"": null,
 
239
  ""id"": 40678260320768000,
 
240
  ""in_reply_to_status_id_str"": null,
 
241
  ""in_reply_to_user_id"": null
 
242
}";
 
243
 
 
244
      DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);
 
245
 
 
246
      Assert.AreEqual(false, foo.Values["retweeted"]);
 
247
    }
 
248
  }
 
249
 
 
250
  public class DynamicChildObject
 
251
  {
 
252
    public string Text { get; set; }
 
253
    public int Integer { get; set; }
 
254
  }
 
255
 
 
256
  public class TestDynamicObject : DynamicObject
 
257
  {
 
258
    private readonly Dictionary<string, object> _members;
 
259
 
 
260
    public int Int;
 
261
    [JsonProperty]
 
262
    public bool Explicit;
 
263
    public DynamicChildObject ChildObject { get; set; }
 
264
 
 
265
    internal Dictionary<string, object> Members
 
266
    {
 
267
      get { return _members; }
 
268
    }
 
269
 
 
270
    public TestDynamicObject()
 
271
    {
 
272
      _members = new Dictionary<string, object>();
 
273
    }
 
274
 
 
275
    public override IEnumerable<string> GetDynamicMemberNames()
 
276
    {
 
277
      return _members.Keys.Union(new[] { "Int", "ChildObject" });
 
278
    }
 
279
 
 
280
    public override bool TryConvert(ConvertBinder binder, out object result)
 
281
    {
 
282
      Type targetType = binder.Type;
 
283
 
 
284
      if (targetType == typeof(IDictionary<string, object>) ||
 
285
          targetType == typeof(IDictionary))
 
286
      {
 
287
        result = new Dictionary<string, object>(_members);
 
288
        return true;
 
289
      }
 
290
      else
 
291
      {
 
292
        return base.TryConvert(binder, out result);
 
293
      }
 
294
    }
 
295
 
 
296
    public override bool TryDeleteMember(DeleteMemberBinder binder)
 
297
    {
 
298
      return _members.Remove(binder.Name);
 
299
    }
 
300
 
 
301
    public override bool TryGetMember(GetMemberBinder binder, out object result)
 
302
    {
 
303
      return _members.TryGetValue(binder.Name, out result);
 
304
    }
 
305
 
 
306
    public override bool TrySetMember(SetMemberBinder binder, object value)
 
307
    {
 
308
      _members[binder.Name] = value;
 
309
      return true;
 
310
    }
 
311
  }
 
312
 
 
313
  public class ErrorSettingDynamicObject : DynamicObject
 
314
  {
 
315
    public override bool TrySetMember(SetMemberBinder binder, object value)
 
316
    {
 
317
      return false;
 
318
    }
 
319
  }
 
320
}
 
321
#endif
 
 
b'\\ No newline at end of file'