summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/test/System.Json.Test.Integration/JsonValueTests.cs
blob: 26735eec252b91f5d9b6f26711179eeff7f09d7d (plain)
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
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Xunit;
using Xunit.Extensions;

namespace System.Json
{
    /// <summary>
    /// JsonValue unit tests
    /// </summary>
    public class JsonValueTests
    {

        public static IEnumerable<object[]> StreamLoadingTestData
        {
            get
            {
                bool[] useSeekableStreams = new bool[] { true, false };
                Dictionary<string, Encoding> allEncodings = new Dictionary<string, Encoding>
                {
                    { "UTF8, no BOM", new UTF8Encoding(false) },
                    { "Unicode, no BOM", new UnicodeEncoding(false, false) },
                    { "BigEndianUnicode, no BOM", new UnicodeEncoding(true, false) },
                };

                string[] jsonStrings = { "[1, 2, null, false, {\"foo\": 1, \"bar\":true, \"baz\":null}, 1.23e+56]", "4" };

                foreach (string jsonString in jsonStrings)
                {
                    foreach (bool useSeekableStream in useSeekableStreams)
                    {
                        foreach (var kvp in allEncodings)
                        {
                            yield return new object[] { jsonString, useSeekableStream, kvp.Key, kvp.Value };
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Tests for <see cref="JsonValue.Load(Stream)"/>.
        /// </summary>
        [Theory]
        [PropertyData("StreamLoadingTestData")]
        public void StreamLoading(string jsonString, bool useSeekableStream, string encodingName, Encoding encoding)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(ms, encoding);
                sw.Write(jsonString);
                sw.Flush();
                Log.Info("[{0}] {1}: size of the json stream: {2}", useSeekableStream ? "seekable" : "non-seekable", encodingName, ms.Position);
                ms.Position = 0;
                JsonValue parsed = JsonValue.Parse(jsonString);
                JsonValue loaded = useSeekableStream ? JsonValue.Load(ms) : JsonValue.Load(new NonSeekableStream(ms));
                using (StringReader sr = new StringReader(jsonString))
                {
                    JsonValue loadedFromTextReader = JsonValue.Load(sr);
                    Assert.Equal(parsed.ToString(), loaded.ToString());
                    Assert.Equal(parsed.ToString(), loadedFromTextReader.ToString());
                }
            }
        }

        [Fact]
        public void ZeroedStreamLoadingThrowsFormatException()
        {
            ExpectException<FormatException>(delegate
            {
                using (MemoryStream ms = new MemoryStream(new byte[10]))
                {
                    JsonValue.Load(ms);
                }
            });
        }

        /// <summary>
        /// Tests for handling with escaped characters.
        /// </summary>
        [Fact]
        public void EscapedCharacters()
        {
            string str = null;
            JsonValue value = null;
            str = (string)value;
            Assert.Null(str);
            value = "abc\b\t\r\u1234\uDC80\uDB11def\\\0ghi";
            str = (string)value;
            Assert.Equal("\"abc\\u0008\\u0009\\u000d\u1234\\udc80\\udb11def\\\\\\u0000ghi\"", value.ToString());
            value = '\u0000';
            str = (string)value;
            Assert.Equal("\u0000", str);
        }

        /// <summary>
        /// Tests for JSON objects with the special '__type' object member.
        /// </summary>
        [Fact]
        public void TypeHintAttributeTests()
        {
            string json = "{\"__type\":\"TypeHint\",\"a\":123}";
            JsonValue jv = JsonValue.Parse(json);
            string newJson = jv.ToString();
            Assert.Equal(json, newJson);

            json = "{\"b\":567,\"__type\":\"TypeHint\",\"a\":123}";
            jv = JsonValue.Parse(json);
            newJson = jv.ToString();
            Assert.Equal(json, newJson);

            json = "[12,{\"__type\":\"TypeHint\",\"a\":123,\"obj\":{\"__type\":\"hint2\",\"b\":333}},null]";
            jv = JsonValue.Parse(json);
            newJson = jv.ToString();
            Assert.Equal(json, newJson);
        }

        /// <summary>
        /// Tests for reading JSON with different member names.
        /// </summary>
        [Fact]
        public void ObjectNameTests()
        {
            string[] objectNames = new string[]
            {
                "simple",
                "with spaces",
                "with<>brackets",
                "",
            };

            foreach (string objectName in objectNames)
            {
                string json = String.Format(CultureInfo.InvariantCulture, "{{\"{0}\":123}}", objectName);
                JsonValue jv = JsonValue.Parse(json);
                Assert.Equal(123, jv[objectName].ReadAs<int>());
                string newJson = jv.ToString();
                Assert.Equal(json, newJson);

                JsonObject jo = new JsonObject { { objectName, 123 } };
                Assert.Equal(123, jo[objectName].ReadAs<int>());
                newJson = jo.ToString();
                Assert.Equal(json, newJson);
            }

            ExpectException<FormatException>(() => JsonValue.Parse("{\"nonXmlChar\u0000\":123}"));
        }

        /// <summary>
        /// Miscellaneous tests for parsing JSON.
        /// </summary>
        [Fact]
        public void ParseMiscellaneousTest()
        {
            string[] jsonValues =
            {
                "[]",
                "[1]",
                "[1,2,3,[4.1,4.2],5]",
                "{}",
                "{\"a\":1}",
                "{\"a\":1,\"b\":2,\"c\":3,\"d\":4}",
                "{\"a\":1,\"b\":[2,3],\"c\":3}",
                "{\"a\":1,\"b\":2,\"c\":[1,2,3,[4.1,4.2],5],\"d\":4}",
                "{\"a\":1,\"b\":[2.1,2.2],\"c\":3,\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}",
                "{\"a\":1,\"b\":[2.1,2.2,[[[{\"b1\":2.21}]]],2.3],\"c\":{\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}}"
            };

            foreach (string json in jsonValues)
            {
                JsonValue jv = JsonValue.Parse(json);
                Log.Info("{0}", jv.ToString());

                string jvstr = jv.ToString();
                Assert.Equal(json, jvstr);
            }
        }

        /// <summary>
        /// Negative tests for parsing "unbalanced" JSON (i.e., JSON documents which aren't properly closed).
        /// </summary>
        [Fact]
        public void ParseUnbalancedJsonTest()
        {
            string[] jsonValues =
            {
                "[",
                "[1,{]",
                "[1,2,3,{{}}",
                "}",
                "{\"a\":}",
                "{\"a\":1,\"b\":[,\"c\":3,\"d\":4}",
                "{\"a\":1,\"b\":[2,\"c\":3}",
                "{\"a\":1,\"b\":[2.1,2.2,\"c\":3,\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}",
                "{\"a\":1,\"b\":[2.1,2.2,[[[[{\"b1\":2.21}]]],\"c\":{\"d\":4,\"e\":[4.1,4.2,4.3,[4.41,4.42],4.4],\"f\":5}}"
            };

            foreach (string json in jsonValues)
            {
                Log.Info("Testing unbalanced JSON: {0}", json);
                ExpectException<FormatException>(() => JsonValue.Parse(json));
            }
        }

        /// <summary>
        /// Test for parsing a deeply nested JSON object.
        /// </summary>
        [Fact]
        public void ParseDeeplyNestedJsonObjectString()
        {
            StringBuilder builderExpected = new StringBuilder();
            builderExpected.Append('{');
            int depth = 10000;
            for (int i = 0; i < depth; i++)
            {
                string key = i.ToString(CultureInfo.InvariantCulture);
                builderExpected.AppendFormat("\"{0}\":{{", key);
            }

            for (int i = 0; i < depth + 1; i++)
            {
                builderExpected.Append('}');
            }

            string json = builderExpected.ToString();
            JsonValue jsonValue = JsonValue.Parse(json);
            string jvstr = jsonValue.ToString();

            Assert.Equal(json, jvstr);
        }

        /// <summary>
        /// Test for parsing a deeply nested JSON array.
        /// </summary>
        [Fact]
        public void ParseDeeplyNestedJsonArrayString()
        {
            StringBuilder builderExpected = new StringBuilder();
            builderExpected.Append('[');
            int depth = 10000;
            for (int i = 0; i < depth; i++)
            {
                builderExpected.Append('[');
            }

            for (int i = 0; i < depth + 1; i++)
            {
                builderExpected.Append(']');
            }

            string json = builderExpected.ToString();
            JsonValue jsonValue = JsonValue.Parse(json);
            string jvstr = jsonValue.ToString();

            Assert.Equal(json, jvstr);
        }

        /// <summary>
        /// Test for parsing a deeply nested JSON graph, containing both objects and arrays.
        /// </summary>
        [Fact]
        public void ParseDeeplyNestedJsonString()
        {
            StringBuilder builderExpected = new StringBuilder();
            builderExpected.Append('{');
            int depth = 10000;
            for (int i = 0; i < depth; i++)
            {
                string key = i.ToString(CultureInfo.InvariantCulture);
                builderExpected.AppendFormat("\"{0}\":[{{", key);
            }

            for (int i = 0; i < depth; i++)
            {
                builderExpected.Append("}]");
            }

            builderExpected.Append('}');

            string json = builderExpected.ToString();
            JsonValue jsonValue = JsonValue.Parse(json);
            string jvstr = jsonValue.ToString();

            Assert.Equal(json, jvstr);
        }

        internal static void ExpectException<T>(Action action) where T : Exception
        {
            ExpectException<T>(action, null);
        }

        internal static void ExpectException<T>(Action action, string partOfExceptionString) where T : Exception
        {
            try
            {
                action();
                Assert.False(true, "This should have thrown");
            }
            catch (T e)
            {
                if (partOfExceptionString != null)
                {
                    Assert.True(e.Message.Contains(partOfExceptionString));
                }
            }
        }

        internal class NonSeekableStream : Stream
        {
            Stream innerStream;

            public NonSeekableStream(Stream innerStream)
            {
                this.innerStream = innerStream;
            }

            public override bool CanRead
            {
                get { return true; }
            }

            public override bool CanSeek
            {
                get { return false; }
            }

            public override bool CanWrite
            {
                get { return false; }
            }

            public override long Position
            {
                get
                {
                    throw new NotSupportedException();
                }

                set
                {
                    throw new NotSupportedException();
                }
            }

            public override long Length
            {
                get
                {
                    throw new NotSupportedException();
                }
            }

            public override void Flush()
            {
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                return this.innerStream.Read(buffer, offset, count);
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                throw new NotSupportedException();
            }

            public override void SetLength(long value)
            {
                throw new NotSupportedException();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                throw new NotSupportedException();
            }
        }
    }
}