Subversion Repository Public Repository

ChrisCompleteCodeTrunk

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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#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;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
#if !(NET20 || NET35)
using System.Dynamic;
#endif
using System.Runtime.Serialization;
using Newtonsoft.Json.Tests.Linq;

namespace Newtonsoft.Json.Tests.Serialization
{
    [TestFixture]
    public class ReferenceLoopHandlingTests : TestFixtureBase
    {
        [Test]
        public void ReferenceLoopHandlingTest()
        {
            JsonPropertyAttribute attribute = new JsonPropertyAttribute();
            Assert.AreEqual(null, attribute._defaultValueHandling);
            Assert.AreEqual(ReferenceLoopHandling.Error, attribute.ReferenceLoopHandling);

            attribute.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute._referenceLoopHandling);
            Assert.AreEqual(ReferenceLoopHandling.Ignore, attribute.ReferenceLoopHandling);
        }

        [Test]
        public void IgnoreObjectReferenceLoop()
        {
            ReferenceLoopHandlingObjectContainerAttribute o = new ReferenceLoopHandlingObjectContainerAttribute();
            o.Value = o;

            string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize
            });
            Assert.AreEqual("{}", json);
        }

        [Test]
        public void IgnoreObjectReferenceLoopWithPropertyOverride()
        {
            ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride o = new ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride();
            o.Value = o;

            string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize
            });
            StringAssert.AreEqual(@"{
  ""Value"": {
    ""Value"": {
      ""Value"": {
        ""Value"": {
          ""Value"": {
            ""Value"": null
          }
        }
      }
    }
  }
}", json);
        }

        [Test]
        public void IgnoreArrayReferenceLoop()
        {
            ReferenceLoopHandlingList a = new ReferenceLoopHandlingList();
            a.Add(a);

            string json = JsonConvert.SerializeObject(a, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize
            });
            Assert.AreEqual("[]", json);
        }

        [Test]
        public void IgnoreDictionaryReferenceLoop()
        {
            ReferenceLoopHandlingDictionary d = new ReferenceLoopHandlingDictionary();
            d.Add("First", d);

            string json = JsonConvert.SerializeObject(d, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize
            });
            Assert.AreEqual("{}", json);
        }

        [Test]
        public void SerializePropertyItemReferenceLoopHandling()
        {
            PropertyItemReferenceLoopHandling c = new PropertyItemReferenceLoopHandling();
            c.Text = "Text!";
            c.SetData(new List<PropertyItemReferenceLoopHandling> { c });

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

            StringAssert.AreEqual(@"{
  ""Text"": ""Text!"",
  ""Data"": [
    {
      ""Text"": ""Text!"",
      ""Data"": [
        {
          ""Text"": ""Text!"",
          ""Data"": [
            {
              ""Text"": ""Text!"",
              ""Data"": null
            }
          ]
        }
      ]
    }
  ]
}", json);
        }

#if !(PORTABLE || DNXCORE50 || NETFX_CORE || PORTABLE40)
        public class MainClass : ISerializable
        {
            public ChildClass Child { get; set; }

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("Child", Child);
            }
        }

        public class ChildClass : ISerializable
        {
            public string Name { get; set; }
            public MainClass Parent { get; set; }

            public void GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.AddValue("Parent", Parent);
                info.AddValue("Name", Name);
            }
        }

        [Test]
        public void ErrorISerializableCyclicReferenceLoop()
        {
            var main = new MainClass();
            var child = new ChildClass();

            child.Name = "Child1";
            child.Parent = main; // Obvious Circular Reference

            main.Child = child;

            var settings =
                new JsonSerializerSettings();

            ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.SerializeObject(main, settings), "Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+MainClass'. Path 'Child'.");
        }

        [Test]
        public void IgnoreISerializableCyclicReferenceLoop()
        {
            var main = new MainClass();
            var child = new ChildClass();

            child.Name = "Child1";
            child.Parent = main; // Obvious Circular Reference

            main.Child = child;

            var settings =
                new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };

            var c = JsonConvert.SerializeObject(main, settings);
            Assert.AreEqual(@"{""Child"":{""Name"":""Child1""}}", c);
        }
#endif

#if !(NET20 || NET35 || PORTABLE40)
        public class DictionaryDynamicObject : DynamicObject
        {
            public IDictionary<string, object> Values { get; private set; }

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

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

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

            public override IEnumerable<string> GetDynamicMemberNames()
            {
                return Values.Keys;
            }
        }

        [Test]
        public void ErrorDynamicCyclicReferenceLoop()
        {
            dynamic parent = new DictionaryDynamicObject();
            dynamic child = new DictionaryDynamicObject();
            parent.child = child;
            child.parent = parent;

            var settings = new JsonSerializerSettings();

            ExceptionAssert.Throws<JsonSerializationException>(() => JsonConvert.SerializeObject(parent, settings), "Self referencing loop detected with type 'Newtonsoft.Json.Tests.Serialization.ReferenceLoopHandlingTests+DictionaryDynamicObject'. Path 'child'.");
        }

        [Test]
        public void IgnoreDynamicCyclicReferenceLoop()
        {
            dynamic parent = new DictionaryDynamicObject();
            dynamic child = new DictionaryDynamicObject();
            parent.child = child;
            parent.name = "parent";
            child.parent = parent;
            child.name = "child";

            var settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };

            var c = JsonConvert.SerializeObject(parent, settings);
            Assert.AreEqual(@"{""child"":{""name"":""child""},""name"":""parent""}", c);
        }
#endif

        [Test]
        public void EqualityComparer()
        {
            AccountWithEquals account = new AccountWithEquals
            {
                Name = "main"
            };
            AccountWithEquals manager = new AccountWithEquals
            {
                Name = "main"
            };
            account.Manager = manager;

            ExceptionAssert.Throws<JsonSerializationException>(
                () => JsonConvert.SerializeObject(account),
                "Self referencing loop detected for property 'Manager' with type 'Newtonsoft.Json.Tests.Serialization.AccountWithEquals'. Path ''.");

            string json = JsonConvert.SerializeObject(account, new JsonSerializerSettings
            {
                EqualityComparer = new ReferenceEqualsEqualityComparer(),
                Formatting = Formatting.Indented
            });

            StringAssert.AreEqual(@"{
  ""Name"": ""main"",
  ""Manager"": {
    ""Name"": ""main"",
    ""Manager"": null
  }
}", json);
        }
    }

    public class ReferenceEqualsEqualityComparer : IEqualityComparer
    {
        bool IEqualityComparer.Equals(object x, object y)
        {
            return ReferenceEquals(x, y);
        }

        int IEqualityComparer.GetHashCode(object obj)
        {
#if !(NETFX_CORE)
            // put objects in a bucket based on their reference
            return RuntimeHelpers.GetHashCode(obj);
#else
    // put all objects in the same bucket so ReferenceEquals is called on all
            return -1;
#endif
        }
    }

    public class AccountWithEquals
    {
        public string Name { get; set; }
        public AccountWithEquals Manager { get; set; }

        public override bool Equals(object obj)
        {
            AccountWithEquals a = obj as AccountWithEquals;
            if (a == null)
            {
                return false;
            }

            return Name == a.Name;
        }

        public override int GetHashCode()
        {
            if (Name == null)
            {
                return 0;
            }

            return Name.GetHashCode();
        }
    }

    public class PropertyItemReferenceLoopHandling
    {
        private IList<PropertyItemReferenceLoopHandling> _data;
        private int _accessCount;

        public string Text { get; set; }

        [JsonProperty(ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
        public IList<PropertyItemReferenceLoopHandling> Data
        {
            get
            {
                if (_accessCount >= 3)
                {
                    return null;
                }

                _accessCount++;
                return new List<PropertyItemReferenceLoopHandling>(_data);
            }
        }

        public void SetData(IList<PropertyItemReferenceLoopHandling> data)
        {
            _data = data;
        }
    }

    [JsonArray(ItemReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
    public class ReferenceLoopHandlingList : List<ReferenceLoopHandlingList>
    {
    }

    [JsonDictionary(ItemReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
    public class ReferenceLoopHandlingDictionary : Dictionary<string, ReferenceLoopHandlingDictionary>
    {
    }

    [JsonObject(ItemReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
    public class ReferenceLoopHandlingObjectContainerAttribute
    {
        public ReferenceLoopHandlingObjectContainerAttribute Value { get; set; }
    }

    [JsonObject(ItemReferenceLoopHandling = ReferenceLoopHandling.Ignore)]
    public class ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride
    {
        private ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride _value;
        private int _getCount;

        [JsonProperty(ReferenceLoopHandling = ReferenceLoopHandling.Serialize)]
        public ReferenceLoopHandlingObjectContainerAttributeWithPropertyOverride Value
        {
            get
            {
                if (_getCount < 5)
                {
                    _getCount++;
                    return _value;
                }
                return null;
            }
            set { _value = value; }
        }
    }
}

Commits for ChrisCompleteCodeTrunk/M3Workflow/Libraries/Json90r1/Source/Src/Newtonsoft.Json.Tests/Serialization/ReferenceLoopHandlingTests.cs

Diff revisions: vs.
Revision Author Commited Message
1 BBDSCHRIS picture BBDSCHRIS Wed 22 Aug, 2018 20:08:03 +0000