File: DynamicTests.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 (289 lines) | stat: -rw-r--r-- 9,006 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#if !(NET35 || NET20 || WINDOWS_PHONE)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters;
using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Utilities;
#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

namespace Newtonsoft.Json.Tests.Serialization
{
  [TestFixture]
  public class DynamicTests : TestFixtureBase
  {
    public class DynamicChildObject
    {
      public string Text { get; set; }
      public int Integer { get; set; }
    }

    public class TestDynamicObject : DynamicObject
    {
      private readonly Dictionary<string, object> _members;

      public int Int;
      public DynamicChildObject ChildObject { get; set; }

      internal Dictionary<string, object> Members
      {
        get { return _members; }
      }

      public TestDynamicObject()
      {
        _members = new Dictionary<string, object>();
      }

      public override IEnumerable<string> GetDynamicMemberNames()
      {
        return _members.Keys.Union(new[] { "Int", "ChildObject" });
      }

      public override bool TryConvert(ConvertBinder binder, out object result)
      {
        Type targetType = binder.Type;

        if (targetType == typeof(IDictionary<string, object>) ||
            targetType == typeof(IDictionary))
        {
          result = new Dictionary<string, object>(_members);
          return true;
        }
        else
        {
          return base.TryConvert(binder, out result);
        }
      }

      public override bool TryDeleteMember(DeleteMemberBinder binder)
      {
        return _members.Remove(binder.Name);
      }

      public override bool TryGetMember(GetMemberBinder binder, out object result)
      {
        return _members.TryGetValue(binder.Name, out result);
      }

      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
        _members[binder.Name] = value;
        return true;
      }
    }

    public class ErrorSettingDynamicObject : DynamicObject
    {
      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
        return false;
      }
    }

    [Test]
    public void SerializeDynamicObject()
    {
      TestDynamicObject dynamicObject = new TestDynamicObject();

      dynamic d = dynamicObject;
      d.Int = 1;
      d.Decimal = 99.9d;
      d.ChildObject = new DynamicChildObject();

      Dictionary<string, object> values = new Dictionary<string, object>();

      foreach (string memberName in dynamicObject.GetDynamicMemberNames())
      {
        object value;
        dynamicObject.TryGetMember(memberName, out value);

        values.Add(memberName, value);
      }

      Assert.AreEqual(d.Int, values["Int"]);
      Assert.AreEqual(d.Decimal, values["Decimal"]);
      Assert.AreEqual(d.ChildObject, values["ChildObject"]);

      string json = JsonConvert.SerializeObject(dynamicObject, Formatting.Indented);
      Assert.AreEqual(@"{
  ""Decimal"": 99.9,
  ""Int"": 1,
  ""ChildObject"": {
    ""Text"": null,
    ""Integer"": 0
  }
}", json);

      TestDynamicObject newDynamicObject = JsonConvert.DeserializeObject<TestDynamicObject>(json);
      d = newDynamicObject;

      Assert.AreEqual(99.9, d.Decimal);
      Assert.AreEqual(1, d.Int);
      Assert.AreEqual(dynamicObject.ChildObject.Integer, d.ChildObject.Integer);
      Assert.AreEqual(dynamicObject.ChildObject.Text, d.ChildObject.Text);
    }

    [Test]
    public void SerializeDynamicObjectWithObjectTracking()
    {
      dynamic o = new ExpandoObject();
      o.Text = "Text!";
      o.Integer = int.MaxValue;
      o.DynamicChildObject = new DynamicChildObject
        {
          Integer = int.MinValue,
          Text = "Child text!"
        };

      string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
        {
          TypeNameHandling = TypeNameHandling.All,
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
        });

      Console.WriteLine(json);

      string dynamicChildObjectTypeName = ReflectionUtils.GetTypeName(typeof(DynamicChildObject), FormatterAssemblyStyle.Full);
      string expandoObjectTypeName = ReflectionUtils.GetTypeName(typeof(ExpandoObject), FormatterAssemblyStyle.Full);

      Assert.AreEqual(@"{
  ""$type"": """ + expandoObjectTypeName + @""",
  ""Text"": ""Text!"",
  ""Integer"": 2147483647,
  ""DynamicChildObject"": {
    ""$type"": """ + dynamicChildObjectTypeName + @""",
    ""Text"": ""Child text!"",
    ""Integer"": -2147483648
  }
}", json);

      dynamic n = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
        {
          TypeNameHandling = TypeNameHandling.All,
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
        });

      CustomAssert.IsInstanceOfType(typeof(ExpandoObject), n);
      Assert.AreEqual("Text!", n.Text);
      Assert.AreEqual(int.MaxValue, n.Integer);

      CustomAssert.IsInstanceOfType(typeof(DynamicChildObject), n.DynamicChildObject);
      Assert.AreEqual("Child text!", n.DynamicChildObject.Text);
      Assert.AreEqual(int.MinValue, n.DynamicChildObject.Integer);
    }

    [Test]
    public void NoPublicDefaultConstructor()
    {
      ExceptionAssert.Throws<JsonSerializationException>("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.",
      () =>
      {
        var settings = new JsonSerializerSettings();
        settings.NullValueHandling = NullValueHandling.Ignore;
        var json = @"{
  ""contributors"": null
}";

        JsonConvert.DeserializeObject<DynamicObject>(json, settings);
      });
    }

    public class DictionaryDynamicObject : DynamicObject
    {
      public IDictionary<string, object> Values { get; private set; }

      protected DictionaryDynamicObject()
      {
        Values = new Dictionary<string, object>();
      }

      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
        Values[binder.Name] = value;
        return true;
      }
    }

    [Test]
    public void AllowNonPublicDefaultConstructor()
    {
      var settings = new JsonSerializerSettings();
      settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;

      var json = @"{
  ""contributors"": null,
  ""retweeted"": false,
  ""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
  ""in_reply_to_user_id_str"": null,
  ""retweet_count"": 0,
  ""geo"": null,
  ""id_str"": ""40678260320768000"",
  ""in_reply_to_status_id"": null,
  ""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
  ""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
  ""place"": null,
  ""coordinates"": null,
  ""truncated"": false,
  ""favorited"": false,
  ""user"": {
    ""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
    ""url"": ""http://bit.ly/dcFwWC"",
    ""screen_name"": ""marutisuzukisx4"",
    ""verified"": false,
    ""friends_count"": 45,
    ""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
    ""follow_request_sent"": null,
    ""time_zone"": ""Chennai"",
    ""profile_text_color"": ""333333"",
    ""location"": ""India"",
    ""notifications"": null,
    ""profile_sidebar_fill_color"": ""efefef"",
    ""id_str"": ""196143889"",
    ""contributors_enabled"": false,
    ""lang"": ""en"",
    ""profile_background_tile"": false,
    ""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
    ""followers_count"": 117,
    ""show_all_inline_media"": true,
    ""listed_count"": 1,
    ""geo_enabled"": true,
    ""profile_link_color"": ""009999"",
    ""profile_sidebar_border_color"": ""eeeeee"",
    ""protected"": false,
    ""name"": ""Maruti Suzuki SX4"",
    ""statuses_count"": 637,
    ""following"": null,
    ""profile_use_background_image"": true,
    ""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
    ""id"": 196143889,
    ""is_translator"": false,
    ""utc_offset"": 19800,
    ""favourites_count"": 0,
    ""profile_background_color"": ""131516""
  },
  ""in_reply_to_screen_name"": null,
  ""id"": 40678260320768000,
  ""in_reply_to_status_id_str"": null,
  ""in_reply_to_user_id"": null
}";

      DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);

      Assert.AreEqual(false, foo.Values["retweeted"]);
    }
  }
}
#endif