File: JsonValueAndComplexTypesTests.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (331 lines) | stat: -rw-r--r-- 13,075 bytes parent folder | download | duplicates (11)
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using Xunit;

namespace System.Json
{
    /// <summary>
    /// Tests for the methods to convert between <see cref="JsonValue"/> instances and complex types.
    /// </summary>
    public class JsonValueAndComplexTypesTests
    {
        static readonly Type[] testTypes = new Type[]
            {
                typeof(DCType_1),
                typeof(StructGuid),
                typeof(StructInt16),
                typeof(DCType_3),
                typeof(SerType_4),
                typeof(SerType_5),
                typeof(DCType_7),
                typeof(DCType_9),
                typeof(SerType_11),
                typeof(DCType_15),
                typeof(DCType_16),
                typeof(DCType_18),
                typeof(DCType_19),
                typeof(DCType_20),
                typeof(SerType_22),
                typeof(DCType_25),
                typeof(SerType_26),
                typeof(DCType_31),
                typeof(DCType_32),
                typeof(SerType_33),
                typeof(DCType_34),
                typeof(DCType_36),
                typeof(DCType_38),
                typeof(DCType_40),
                typeof(DCType_42),
                typeof(DCType_65),
                typeof(ListType_1),
                typeof(ListType_2),
                typeof(BaseType),
                typeof(PolymorphicMember),
                typeof(PolymorphicAsInterfaceMember),
                typeof(CollectionsWithPolymorphicMember),
            };

        /// <summary>
        /// Tests for the <see cref="JsonValueExtensions.CreateFrom"/> method.
        /// </summary>
        [Fact]
        public void CreateFromTests()
        {
            InstanceCreatorSurrogate oldSurrogate = CreatorSettings.CreatorSurrogate;
            try
            {
                CreatorSettings.CreatorSurrogate = new NoInfinityFloatSurrogate();
                DateTime now = DateTime.Now;
                int seed = (10000 * now.Year) + (100 * now.Month) + now.Day;
                Log.Info("Seed: {0}", seed);
                Random rndGen = new Random(seed);
                foreach (Type testType in testTypes)
                {
                    object instance = InstanceCreator.CreateInstanceOf(testType, rndGen);
                    JsonValue jv = JsonValueExtensions.CreateFrom(instance);

                    if (instance == null)
                    {
                        Assert.Null(jv);
                    }
                    else
                    {
                        DataContractJsonSerializer dcjs = new DataContractJsonSerializer(instance == null ? testType : instance.GetType());
                        string fromDCJS;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            dcjs.WriteObject(ms, instance);
                            fromDCJS = Encoding.UTF8.GetString(ms.ToArray());
                        }

                        Log.Info("{0}: {1}", testType.Name, fromDCJS);

                        if (instance == null)
                        {
                            Assert.Null(jv);
                        }
                        else
                        {
                            string fromJsonValue = jv.ToString();
                            Assert.Equal(fromDCJS, fromJsonValue);
                        }
                    }
                }
            }
            finally
            {
                CreatorSettings.CreatorSurrogate = oldSurrogate;
            }
        }

        /// <summary>
        /// Tests for the <see cref="JsonValueExtensions.ReadAsType{T}(JsonValue)"/> method.
        /// </summary>
        [Fact]
        public void ReadAsTests()
        {
            InstanceCreatorSurrogate oldSurrogate = CreatorSettings.CreatorSurrogate;
            try
            {
                CreatorSettings.CreatorSurrogate = new NoInfinityFloatSurrogate();
                DateTime now = DateTime.Now;
                int seed = (10000 * now.Year) + (100 * now.Month) + now.Day;
                Log.Info("Seed: {0}", seed);
                Random rndGen = new Random(seed);

                this.ReadAsTest<DCType_1>(rndGen);
                this.ReadAsTest<StructGuid>(rndGen);
                this.ReadAsTest<StructInt16>(rndGen);
                this.ReadAsTest<DCType_3>(rndGen);
                this.ReadAsTest<SerType_4>(rndGen);
                this.ReadAsTest<SerType_5>(rndGen);
                this.ReadAsTest<DCType_7>(rndGen);
                this.ReadAsTest<DCType_9>(rndGen);
                this.ReadAsTest<SerType_11>(rndGen);
                this.ReadAsTest<DCType_15>(rndGen);
                this.ReadAsTest<DCType_16>(rndGen);
                this.ReadAsTest<DCType_18>(rndGen);
                this.ReadAsTest<DCType_19>(rndGen);
                this.ReadAsTest<DCType_20>(rndGen);
                this.ReadAsTest<SerType_22>(rndGen);
                this.ReadAsTest<DCType_25>(rndGen);
                this.ReadAsTest<SerType_26>(rndGen);
                this.ReadAsTest<DCType_31>(rndGen);
                this.ReadAsTest<DCType_32>(rndGen);
                this.ReadAsTest<SerType_33>(rndGen);
                this.ReadAsTest<DCType_34>(rndGen);
                this.ReadAsTest<DCType_36>(rndGen);
                this.ReadAsTest<DCType_38>(rndGen);
                this.ReadAsTest<DCType_40>(rndGen);
                this.ReadAsTest<DCType_42>(rndGen);
                this.ReadAsTest<DCType_65>(rndGen);
                this.ReadAsTest<ListType_1>(rndGen);
                this.ReadAsTest<ListType_2>(rndGen);
                this.ReadAsTest<BaseType>(rndGen);
                this.ReadAsTest<PolymorphicMember>(rndGen);
                this.ReadAsTest<PolymorphicAsInterfaceMember>(rndGen);
                this.ReadAsTest<CollectionsWithPolymorphicMember>(rndGen);
            }
            finally
            {
                CreatorSettings.CreatorSurrogate = oldSurrogate;
            }
        }

        /// <summary>
        /// Tests for the <see cref="JsonValueExtensions.CreateFrom"/> for <see cref="DateTime"/>
        /// and <see cref="DateTimeOffset"/> values.
        /// </summary>
        [Fact]
        public void CreateFromDateTimeTest()
        {
            DateTime dt = DateTime.Now;
            DateTimeOffset dto = DateTimeOffset.Now;

            JsonValue jvDt1 = (JsonValue)dt;
            JsonValue jvDt2 = JsonValueExtensions.CreateFrom(dt);

            JsonValue jvDto1 = (JsonValue)dto;
            JsonValue jvDto2 = JsonValueExtensions.CreateFrom(dto);

            Assert.Equal(dt, (DateTime)jvDt1);
            Assert.Equal(dt, (DateTime)jvDt2);

            Assert.Equal(dto, (DateTimeOffset)jvDto1);
            Assert.Equal(dto, (DateTimeOffset)jvDto2);

            Assert.Equal(dt, jvDt1.ReadAs<DateTime>());
            Assert.Equal(dt, jvDt2.ReadAs<DateTime>());

            Assert.Equal(dto, jvDto1.ReadAs<DateTimeOffset>());
            Assert.Equal(dto, jvDto2.ReadAs<DateTimeOffset>());

            Assert.Equal(jvDt1.ToString(), jvDt2.ToString());
            Assert.Equal(jvDto1.ToString(), jvDto2.ToString());
        }

        /// <summary>
        /// Tests for creating <see cref="JsonValue"/> instances from dynamic objects.
        /// </summary>
        [Fact]
        public void CreateFromDynamic()
        {
            string expectedJson = "{\"int\":12,\"str\":\"hello\",\"jv\":[1,{\"a\":true}],\"dyn\":{\"char\":\"c\",\"null\":null}}";
            MyDynamicObject obj = new MyDynamicObject();
            obj.fields.Add("int", 12);
            obj.fields.Add("str", "hello");
            obj.fields.Add("jv", new JsonArray(1, new JsonObject { { "a", true } }));
            MyDynamicObject dyn = new MyDynamicObject();
            obj.fields.Add("dyn", dyn);
            dyn.fields.Add("char", 'c');
            dyn.fields.Add("null", null);

            JsonValue jv = JsonValueExtensions.CreateFrom(obj);
            Assert.Equal(expectedJson, jv.ToString());
        }

        void ReadAsTest<T>(Random rndGen)
        {
            T instance = InstanceCreator.CreateInstanceOf<T>(rndGen);
            Log.Info("ReadAsTest<{0}>, instance = {1}", typeof(T).Name, instance);
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(T));
            JsonValue jv;
            using (MemoryStream ms = new MemoryStream())
            {
                dcjs.WriteObject(ms, instance);
                Log.Info("{0}: {1}", typeof(T).Name, Encoding.UTF8.GetString(ms.ToArray()));
                ms.Position = 0;
                jv = JsonValue.Load(ms);
            }

            if (instance == null)
            {
                Assert.Null(jv);
            }
            else
            {
                T newInstance = jv.ReadAsType<T>();
                Assert.Equal(instance, newInstance);
            }
        }

        /// <summary>
        /// Test class.
        /// </summary>
        public class MyDynamicObject : DynamicObject
        {
            /// <summary>
            /// Test member
            /// </summary>
            public Dictionary<string, object> fields = new Dictionary<string, object>();

            /// <summary>
            /// Returnes the member names in this dynamic object.
            /// </summary>
            /// <returns>The member names in this dynamic object.</returns>
            public override IEnumerable<string> GetDynamicMemberNames()
            {
                return fields.Keys;
            }

            /// <summary>
            /// Attempts to get a named member from this dynamic object.
            /// </summary>
            /// <param name="binder">The dynamic binder which contains the member name.</param>
            /// <param name="result">The value of the member, if it exists in this dynamic object.</param>
            /// <returns><code>true</code> if the member can be returned; <code>false</code> otherwise.</returns>
            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                if (binder != null && binder.Name != null && this.fields.ContainsKey(binder.Name))
                {
                    result = this.fields[binder.Name];
                    return true;
                }

                return base.TryGetMember(binder, out result);
            }

            /// <summary>
            /// Attempts to set a named member from this dynamic object.
            /// </summary>
            /// <param name="binder">The dynamic binder which contains the member name.</param>
            /// <param name="value">The value of the member to be set.</param>
            /// <returns><code>true</code> if the member can be set; <code>false</code> otherwise.</returns>
            public override bool TrySetMember(SetMemberBinder binder, object value)
            {
                if (binder != null && binder.Name != null)
                {
                    this.fields[binder.Name] = value;
                    return true;
                }

                return base.TrySetMember(binder, value);
            }
        }

        // Currently there are some differences in treatment of infinity between
        // JsonValue (which writes them as Infinity/-Infinity) and DataContractJsonSerializer
        // (which writes them as INF/-INF). This prevents those values from being used in the test.
        // This also allows the creation of an instance of an IEmptyInterface type, used in the test.
        class NoInfinityFloatSurrogate : InstanceCreatorSurrogate
        {
            public override bool CanCreateInstanceOf(Type type)
            {
                return type == typeof(float) || type == typeof(double) || type == typeof(IEmptyInterface) || type == typeof(BaseType);
            }

            public override object CreateInstanceOf(Type type, Random rndGen)
            {
                if (type == typeof(float))
                {
                    float result;
                    do
                    {
                        result = PrimitiveCreator.CreateInstanceOfSingle(rndGen);
                    }
                    while (float.IsInfinity(result));
                    return result;
                }
                else if (type == typeof(double))
                {
                    double result;
                    do
                    {
                        result = PrimitiveCreator.CreateInstanceOfDouble(rndGen);
                    }
                    while (double.IsInfinity(result));
                    return result;
                }
                else
                {
                    return new DerivedType(rndGen);
                }
            }
        }
    }
}