• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #region Copyright notice and license
2 // Protocol Buffers - Google's data interchange format
3 // Copyright 2008 Google Inc.  All rights reserved.
4 //
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file or at
7 // https://developers.google.com/open-source/licenses/bsd
8 #endregion
9 
10 using Google.Protobuf.Reflection;
11 using Google.Protobuf.TestProtos;
12 using Google.Protobuf.WellKnownTypes;
13 using NUnit.Framework;
14 using System;
15 
16 namespace Google.Protobuf
17 {
18     /// <summary>
19     /// Unit tests for JSON parsing.
20     /// </summary>
21     public class JsonParserTest
22     {
23         // Sanity smoke test
24         [Test]
AllTypesRoundtrip()25         public void AllTypesRoundtrip()
26         {
27             AssertRoundtrip(SampleMessages.CreateFullTestAllTypes());
28         }
29 
30         [Test]
Maps()31         public void Maps()
32         {
33             AssertRoundtrip(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } });
34             AssertRoundtrip(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } });
35             AssertRoundtrip(new TestMap { MapBoolBool = { { false, true }, { true, false } } });
36         }
37 
38         [Test]
39         [TestCase(" 1 ")]
40         [TestCase("+1")]
41         [TestCase("1,000")]
42         [TestCase("1.5")]
IntegerMapKeysAreStrict(string keyText)43         public void IntegerMapKeysAreStrict(string keyText)
44         {
45             // Test that integer parsing is strict. We assume that if this is correct for int32,
46             // it's correct for other numeric key types.
47             var json = "{ \"mapInt32Int32\": { \"" + keyText + "\" : \"1\" } }";
48             Assert.Throws<InvalidProtocolBufferException>(() => JsonParser.Default.Parse<TestMap>(json));
49         }
50 
51         [Test]
OriginalFieldNameAccepted()52         public void OriginalFieldNameAccepted()
53         {
54             var json = "{ \"single_int32\": 10 }";
55             var expected = new TestAllTypes { SingleInt32 = 10 };
56             Assert.AreEqual(expected, TestAllTypes.Parser.ParseJson(json));
57         }
58 
59         [Test]
SourceContextRoundtrip()60         public void SourceContextRoundtrip()
61         {
62             AssertRoundtrip(new SourceContext { FileName = "foo.proto" });
63         }
64 
65         [Test]
SingularWrappers_DefaultNonNullValues()66         public void SingularWrappers_DefaultNonNullValues()
67         {
68             var message = new TestWellKnownTypes
69             {
70                 StringField = "",
71                 BytesField = ByteString.Empty,
72                 BoolField = false,
73                 FloatField = 0f,
74                 DoubleField = 0d,
75                 Int32Field = 0,
76                 Int64Field = 0,
77                 Uint32Field = 0,
78                 Uint64Field = 0
79             };
80             AssertRoundtrip(message);
81         }
82 
83         [Test]
SingularWrappers_NonDefaultValues()84         public void SingularWrappers_NonDefaultValues()
85         {
86             var message = new TestWellKnownTypes
87             {
88                 StringField = "x",
89                 BytesField = ByteString.CopyFrom(1, 2, 3),
90                 BoolField = true,
91                 FloatField = 12.5f,
92                 DoubleField = 12.25d,
93                 Int32Field = 1,
94                 Int64Field = 2,
95                 Uint32Field = 3,
96                 Uint64Field = 4
97             };
98             AssertRoundtrip(message);
99         }
100 
101         [Test]
SingularWrappers_ExplicitNulls()102         public void SingularWrappers_ExplicitNulls()
103         {
104             // When we parse the "valueField": null part, we remember it... basically, it's one case
105             // where explicit default values don't fully roundtrip.
106             var message = new TestWellKnownTypes { ValueField = Value.ForNull() };
107             var json = new JsonFormatter(new JsonFormatter.Settings(true)).Format(message);
108             var parsed = JsonParser.Default.Parse<TestWellKnownTypes>(json);
109             Assert.AreEqual(message, parsed);
110         }
111 
112         [Test]
113         [TestCase(typeof(BoolValue), "true", true)]
114         [TestCase(typeof(Int32Value), "32", 32)]
115         [TestCase(typeof(Int64Value), "32", 32L)]
116         [TestCase(typeof(Int64Value), "\"32\"", 32L)]
117         [TestCase(typeof(UInt32Value), "32", 32U)]
118         [TestCase(typeof(UInt64Value), "\"32\"", 32UL)]
119         [TestCase(typeof(UInt64Value), "32", 32UL)]
120         [TestCase(typeof(StringValue), "\"foo\"", "foo")]
121         [TestCase(typeof(FloatValue), "1.5", 1.5f)]
122         [TestCase(typeof(DoubleValue), "1.5", 1.5d)]
Wrappers_Standalone(System.Type wrapperType, string json, object expectedValue)123         public void Wrappers_Standalone(System.Type wrapperType, string json, object expectedValue)
124         {
125             IMessage parsed = (IMessage)Activator.CreateInstance(wrapperType);
126             IMessage expected = (IMessage)Activator.CreateInstance(wrapperType);
127             JsonParser.Default.Merge(parsed, "null");
128             Assert.AreEqual(expected, parsed);
129 
130             JsonParser.Default.Merge(parsed, json);
131             expected.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(expected, expectedValue);
132             Assert.AreEqual(expected, parsed);
133         }
134 
135         [Test]
ExplicitNullValue()136         public void ExplicitNullValue()
137         {
138             string json = "{\"valueField\": null}";
139             var message = JsonParser.Default.Parse<TestWellKnownTypes>(json);
140             Assert.AreEqual(new TestWellKnownTypes { ValueField = Value.ForNull() }, message);
141         }
142 
143         [Test]
BytesWrapper_Standalone()144         public void BytesWrapper_Standalone()
145         {
146             ByteString data = ByteString.CopyFrom(1, 2, 3);
147             // Can't do this with attributes...
148             var parsed = JsonParser.Default.Parse<BytesValue>(WrapInQuotes(data.ToBase64()));
149             var expected = new BytesValue { Value = data };
150             Assert.AreEqual(expected, parsed);
151         }
152 
153         [Test]
RepeatedWrappers()154         public void RepeatedWrappers()
155         {
156             var message = new RepeatedWellKnownTypes
157             {
158                 BoolField = { true, false },
159                 BytesField = { ByteString.CopyFrom(1, 2, 3), ByteString.CopyFrom(4, 5, 6), ByteString.Empty },
160                 DoubleField = { 12.5, -1.5, 0d },
161                 FloatField = { 123.25f, -20f, 0f },
162                 Int32Field = { int.MaxValue, int.MinValue, 0 },
163                 Int64Field = { long.MaxValue, long.MinValue, 0L },
164                 StringField = { "First", "Second", "" },
165                 Uint32Field = { uint.MaxValue, uint.MinValue, 0U },
166                 Uint64Field = { ulong.MaxValue, ulong.MinValue, 0UL },
167             };
168             AssertRoundtrip(message);
169         }
170 
171         [Test]
RepeatedField_NullElementProhibited()172         public void RepeatedField_NullElementProhibited()
173         {
174             string json = "{ \"repeated_foreign_message\": [null] }";
175             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
176         }
177 
178         [Test]
RepeatedField_NullOverallValueAllowed()179         public void RepeatedField_NullOverallValueAllowed()
180         {
181             string json = "{ \"repeated_foreign_message\": null }";
182             Assert.AreEqual(new TestAllTypes(), TestAllTypes.Parser.ParseJson(json));
183         }
184 
185         [Test]
186         [TestCase("{ \"mapInt32Int32\": { \"10\": null }")]
187         [TestCase("{ \"mapStringString\": { \"abc\": null }")]
188         [TestCase("{ \"mapInt32ForeignMessage\": { \"10\": null }")]
MapField_NullValueProhibited(string json)189         public void MapField_NullValueProhibited(string json)
190         {
191             Assert.Throws<InvalidProtocolBufferException>(() => TestMap.Parser.ParseJson(json));
192         }
193 
194         [Test]
MapField_NullOverallValueAllowed()195         public void MapField_NullOverallValueAllowed()
196         {
197             string json = "{ \"mapInt32Int32\": null }";
198             Assert.AreEqual(new TestMap(), TestMap.Parser.ParseJson(json));
199         }
200 
201         [Test]
IndividualWrapperTypes()202         public void IndividualWrapperTypes()
203         {
204             Assert.AreEqual(new StringValue { Value = "foo" }, StringValue.Parser.ParseJson("\"foo\""));
205             Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("1"));
206             // Can parse strings directly too
207             Assert.AreEqual(new Int32Value { Value = 1 }, Int32Value.Parser.ParseJson("\"1\""));
208         }
209 
210         private static void AssertRoundtrip<T>(T message) where T : IMessage<T>, new()
211         {
212             var clone = message.Clone();
213             var json = JsonFormatter.Default.Format(message);
214             var parsed = JsonParser.Default.Parse<T>(json);
215             Assert.AreEqual(clone, parsed);
216         }
217 
218         [Test]
219         [TestCase("0", 0)]
220         [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this...
221         [TestCase("1", 1)]
222         [TestCase("-1", -1)]
223         [TestCase("2147483647", 2147483647)]
224         [TestCase("-2147483648", -2147483648)]
StringToInt32_Valid(string jsonValue, int expectedParsedValue)225         public void StringToInt32_Valid(string jsonValue, int expectedParsedValue)
226         {
227             string json = "{ \"singleInt32\": \"" + jsonValue + "\"}";
228             var parsed = TestAllTypes.Parser.ParseJson(json);
229             Assert.AreEqual(expectedParsedValue, parsed.SingleInt32);
230         }
231 
232         [Test]
233         [TestCase("+0")]
234         [TestCase(" 1")]
235         [TestCase("1 ")]
236         [TestCase("00")]
237         [TestCase("-00")]
238         [TestCase("--1")]
239         [TestCase("+1")]
240         [TestCase("1.5")]
241         [TestCase("1e10")]
242         [TestCase("2147483648")]
243         [TestCase("-2147483649")]
StringToInt32_Invalid(string jsonValue)244         public void StringToInt32_Invalid(string jsonValue)
245         {
246             string json = "{ \"singleInt32\": \"" + jsonValue + "\"}";
247             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
248         }
249 
250         [Test]
251         [TestCase("0", 0U)]
252         [TestCase("1", 1U)]
253         [TestCase("4294967295", 4294967295U)]
StringToUInt32_Valid(string jsonValue, uint expectedParsedValue)254         public void StringToUInt32_Valid(string jsonValue, uint expectedParsedValue)
255         {
256             string json = "{ \"singleUint32\": \"" + jsonValue + "\"}";
257             var parsed = TestAllTypes.Parser.ParseJson(json);
258             Assert.AreEqual(expectedParsedValue, parsed.SingleUint32);
259         }
260 
261         // Assume that anything non-bounds-related is covered in the Int32 case
262         [Test]
263         [TestCase("-1")]
264         [TestCase("4294967296")]
StringToUInt32_Invalid(string jsonValue)265         public void StringToUInt32_Invalid(string jsonValue)
266         {
267             string json = "{ \"singleUint32\": \"" + jsonValue + "\"}";
268             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
269         }
270 
271         [Test]
272         [TestCase("0", 0L)]
273         [TestCase("1", 1L)]
274         [TestCase("-1", -1L)]
275         [TestCase("9223372036854775807", 9223372036854775807)]
276         [TestCase("-9223372036854775808", -9223372036854775808)]
StringToInt64_Valid(string jsonValue, long expectedParsedValue)277         public void StringToInt64_Valid(string jsonValue, long expectedParsedValue)
278         {
279             string json = "{ \"singleInt64\": \"" + jsonValue + "\"}";
280             var parsed = TestAllTypes.Parser.ParseJson(json);
281             Assert.AreEqual(expectedParsedValue, parsed.SingleInt64);
282         }
283 
284         // Assume that anything non-bounds-related is covered in the Int32 case
285         [Test]
286         [TestCase("-9223372036854775809")]
287         [TestCase("9223372036854775808")]
StringToInt64_Invalid(string jsonValue)288         public void StringToInt64_Invalid(string jsonValue)
289         {
290             string json = "{ \"singleInt64\": \"" + jsonValue + "\"}";
291             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
292         }
293 
294         [Test]
295         [TestCase("0", 0UL)]
296         [TestCase("1", 1UL)]
297         [TestCase("18446744073709551615", 18446744073709551615)]
StringToUInt64_Valid(string jsonValue, ulong expectedParsedValue)298         public void StringToUInt64_Valid(string jsonValue, ulong expectedParsedValue)
299         {
300             string json = "{ \"singleUint64\": \"" + jsonValue + "\"}";
301             var parsed = TestAllTypes.Parser.ParseJson(json);
302             Assert.AreEqual(expectedParsedValue, parsed.SingleUint64);
303         }
304 
305         // Assume that anything non-bounds-related is covered in the Int32 case
306         [Test]
307         [TestCase("-1")]
308         [TestCase("18446744073709551616")]
StringToUInt64_Invalid(string jsonValue)309         public void StringToUInt64_Invalid(string jsonValue)
310         {
311             string json = "{ \"singleUint64\": \"" + jsonValue + "\"}";
312             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
313         }
314 
315         [Test]
316         [TestCase("0", 0d)]
317         [TestCase("1", 1d)]
318         [TestCase("1.000000", 1d)]
319         [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value
320         [TestCase("-1", -1d)]
321         [TestCase("1e1", 10d)]
322         [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents
323         [TestCase("1E1", 10d)] // Either case is fine
324         [TestCase("-1e1", -10d)]
325         [TestCase("1.5e1", 15d)]
326         [TestCase("-1.5e1", -15d)]
327         [TestCase("15e-1", 1.5d)]
328         [TestCase("-15e-1", -1.5d)]
329         [TestCase("1.79769e308", 1.79769e308)]
330         [TestCase("-1.79769e308", -1.79769e308)]
331         [TestCase("Infinity", double.PositiveInfinity)]
332         [TestCase("-Infinity", double.NegativeInfinity)]
333         [TestCase("NaN", double.NaN)]
StringToDouble_Valid(string jsonValue, double expectedParsedValue)334         public void StringToDouble_Valid(string jsonValue, double expectedParsedValue)
335         {
336             string json = "{ \"singleDouble\": \"" + jsonValue + "\"}";
337             var parsed = TestAllTypes.Parser.ParseJson(json);
338             Assert.AreEqual(expectedParsedValue, parsed.SingleDouble);
339         }
340 
341         [Test]
342         [TestCase("1.7977e308")]
343         [TestCase("-1.7977e308")]
344         [TestCase("1e309")]
345         [TestCase("1,0")]
346         [TestCase("1.0.0")]
347         [TestCase("+1")]
348         [TestCase("00")]
349         [TestCase("01")]
350         [TestCase("-00")]
351         [TestCase("-01")]
352         [TestCase("--1")]
353         [TestCase(" Infinity")]
354         [TestCase(" -Infinity")]
355         [TestCase("NaN ")]
356         [TestCase("Infinity ")]
357         [TestCase("-Infinity ")]
358         [TestCase(" NaN")]
359         [TestCase("INFINITY")]
360         [TestCase("nan")]
361         [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking...
StringToDouble_Invalid(string jsonValue)362         public void StringToDouble_Invalid(string jsonValue)
363         {
364             string json = "{ \"singleDouble\": \"" + jsonValue + "\"}";
365             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
366         }
367 
368         [Test]
369         [TestCase("0", 0f)]
370         [TestCase("1", 1f)]
371         [TestCase("1.000000", 1f)]
372         [TestCase("-1", -1f)]
373         [TestCase("3.402823e38", 3.402823e38f)]
374         [TestCase("-3.402823e38", -3.402823e38f)]
375         [TestCase("1.5e1", 15f)]
376         [TestCase("15e-1", 1.5f)]
StringToFloat_Valid(string jsonValue, float expectedParsedValue)377         public void StringToFloat_Valid(string jsonValue, float expectedParsedValue)
378         {
379             string json = "{ \"singleFloat\": \"" + jsonValue + "\"}";
380             var parsed = TestAllTypes.Parser.ParseJson(json);
381             Assert.AreEqual(expectedParsedValue, parsed.SingleFloat);
382         }
383 
384         [Test]
385         [TestCase("3.402824e38")]
386         [TestCase("-3.402824e38")]
387         [TestCase("1,0")]
388         [TestCase("1.0.0")]
389         [TestCase("+1")]
390         [TestCase("00")]
391         [TestCase("--1")]
StringToFloat_Invalid(string jsonValue)392         public void StringToFloat_Invalid(string jsonValue)
393         {
394             string json = "{ \"singleFloat\": \"" + jsonValue + "\"}";
395             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
396         }
397 
398         [Test]
399         [TestCase("0", 0)]
400         [TestCase("-0", 0)] // Not entirely clear whether we intend to allow this...
401         [TestCase("1", 1)]
402         [TestCase("-1", -1)]
403         [TestCase("2147483647", 2147483647)]
404         [TestCase("-2147483648", -2147483648)]
405         [TestCase("1e1", 10)]
406         [TestCase("-1e1", -10)]
407         [TestCase("10.00", 10)]
408         [TestCase("-10.00", -10)]
NumberToInt32_Valid(string jsonValue, int expectedParsedValue)409         public void NumberToInt32_Valid(string jsonValue, int expectedParsedValue)
410         {
411             string json = "{ \"singleInt32\": " + jsonValue + "}";
412             var parsed = TestAllTypes.Parser.ParseJson(json);
413             Assert.AreEqual(expectedParsedValue, parsed.SingleInt32);
414         }
415 
416         [Test]
417         [TestCase("+0", typeof(InvalidJsonException))]
418         [TestCase("00", typeof(InvalidJsonException))]
419         [TestCase("-00", typeof(InvalidJsonException))]
420         [TestCase("--1", typeof(InvalidJsonException))]
421         [TestCase("+1", typeof(InvalidJsonException))]
422         [TestCase("1.5", typeof(InvalidProtocolBufferException))]
423         // Value is out of range
424         [TestCase("1e10", typeof(InvalidProtocolBufferException))]
425         [TestCase("2147483648", typeof(InvalidProtocolBufferException))]
426         [TestCase("-2147483649", typeof(InvalidProtocolBufferException))]
NumberToInt32_Invalid(string jsonValue, System.Type expectedExceptionType)427         public void NumberToInt32_Invalid(string jsonValue, System.Type expectedExceptionType)
428         {
429             string json = "{ \"singleInt32\": " + jsonValue + "}";
430             Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json));
431         }
432 
433         [Test]
434         [TestCase("0", 0U)]
435         [TestCase("1", 1U)]
436         [TestCase("4294967295", 4294967295U)]
NumberToUInt32_Valid(string jsonValue, uint expectedParsedValue)437         public void NumberToUInt32_Valid(string jsonValue, uint expectedParsedValue)
438         {
439             string json = "{ \"singleUint32\": " + jsonValue + "}";
440             var parsed = TestAllTypes.Parser.ParseJson(json);
441             Assert.AreEqual(expectedParsedValue, parsed.SingleUint32);
442         }
443 
444         // Assume that anything non-bounds-related is covered in the Int32 case
445         [Test]
446         [TestCase("-1")]
447         [TestCase("4294967296")]
NumberToUInt32_Invalid(string jsonValue)448         public void NumberToUInt32_Invalid(string jsonValue)
449         {
450             string json = "{ \"singleUint32\": " + jsonValue + "}";
451             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
452         }
453 
454         [Test]
455         [TestCase("0", 0L)]
456         [TestCase("1", 1L)]
457         [TestCase("-1", -1L)]
458         // long.MaxValue isn't actually representable as a double. This string value is the highest
459         // representable value which isn't greater than long.MaxValue.
460         [TestCase("9223372036854774784", 9223372036854774784)]
461         [TestCase("-9223372036854775808", -9223372036854775808)]
NumberToInt64_Valid(string jsonValue, long expectedParsedValue)462         public void NumberToInt64_Valid(string jsonValue, long expectedParsedValue)
463         {
464             string json = "{ \"singleInt64\": " + jsonValue + "}";
465             var parsed = TestAllTypes.Parser.ParseJson(json);
466             Assert.AreEqual(expectedParsedValue, parsed.SingleInt64);
467         }
468 
469         // Assume that anything non-bounds-related is covered in the Int32 case
470         [Test]
471         [TestCase("9223372036854775808")]
472         // Theoretical bound would be -9223372036854775809, but when that is parsed to a double
473         // we end up with the exact value of long.MinValue due to lack of precision. The value here
474         // is the "next double down".
475         [TestCase("-9223372036854780000")]
NumberToInt64_Invalid(string jsonValue)476         public void NumberToInt64_Invalid(string jsonValue)
477         {
478             string json = "{ \"singleInt64\": " + jsonValue + "}";
479             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
480         }
481 
482         [Test]
483         [TestCase("0", 0UL)]
484         [TestCase("1", 1UL)]
485         // ulong.MaxValue isn't representable as a double. This value is the largest double within
486         // the range of ulong.
487         [TestCase("18446744073709549568", 18446744073709549568UL)]
NumberToUInt64_Valid(string jsonValue, ulong expectedParsedValue)488         public void NumberToUInt64_Valid(string jsonValue, ulong expectedParsedValue)
489         {
490             string json = "{ \"singleUint64\": " + jsonValue + "}";
491             var parsed = TestAllTypes.Parser.ParseJson(json);
492             Assert.AreEqual(expectedParsedValue, parsed.SingleUint64);
493         }
494 
495         // Assume that anything non-bounds-related is covered in the Int32 case
496         [Test]
497         [TestCase("-1")]
498         [TestCase("18446744073709551616")]
NumberToUInt64_Invalid(string jsonValue)499         public void NumberToUInt64_Invalid(string jsonValue)
500         {
501             string json = "{ \"singleUint64\": " + jsonValue + "}";
502             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
503         }
504 
505         [Test]
506         [TestCase("0", 0d)]
507         [TestCase("1", 1d)]
508         [TestCase("1.000000", 1d)]
509         [TestCase("1.0000000000000000000000001", 1d)] // We don't notice that we haven't preserved the exact value
510         [TestCase("-1", -1d)]
511         [TestCase("1e1", 10d)]
512         [TestCase("1e01", 10d)] // Leading decimals are allowed in exponents
513         [TestCase("1E1", 10d)] // Either case is fine
514         [TestCase("-1e1", -10d)]
515         [TestCase("1.5e1", 15d)]
516         [TestCase("-1.5e1", -15d)]
517         [TestCase("15e-1", 1.5d)]
518         [TestCase("-15e-1", -1.5d)]
519         [TestCase("1.79769e308", 1.79769e308)]
520         [TestCase("-1.79769e308", -1.79769e308)]
NumberToDouble_Valid(string jsonValue, double expectedParsedValue)521         public void NumberToDouble_Valid(string jsonValue, double expectedParsedValue)
522         {
523             string json = "{ \"singleDouble\": " + jsonValue + "}";
524             var parsed = TestAllTypes.Parser.ParseJson(json);
525             Assert.AreEqual(expectedParsedValue, parsed.SingleDouble);
526         }
527 
528         [Test]
529         [TestCase("1.7977e308")]
530         [TestCase("-1.7977e308")]
531         [TestCase("1e309")]
532         [TestCase("1,0")]
533         [TestCase("1.0.0")]
534         [TestCase("+1")]
535         [TestCase("00")]
536         [TestCase("--1")]
537         [TestCase("\u00BD")] // 1/2 as a single Unicode character. Just sanity checking...
NumberToDouble_Invalid(string jsonValue)538         public void NumberToDouble_Invalid(string jsonValue)
539         {
540             string json = "{ \"singleDouble\": " + jsonValue + "}";
541             Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json));
542         }
543 
544         [Test]
545         [TestCase("0", 0f)]
546         [TestCase("1", 1f)]
547         [TestCase("1.000000", 1f)]
548         [TestCase("-1", -1f)]
549         [TestCase("3.402823e38", 3.402823e38f)]
550         [TestCase("-3.402823e38", -3.402823e38f)]
551         [TestCase("1.5e1", 15f)]
552         [TestCase("15e-1", 1.5f)]
NumberToFloat_Valid(string jsonValue, float expectedParsedValue)553         public void NumberToFloat_Valid(string jsonValue, float expectedParsedValue)
554         {
555             string json = "{ \"singleFloat\": " + jsonValue + "}";
556             var parsed = TestAllTypes.Parser.ParseJson(json);
557             Assert.AreEqual(expectedParsedValue, parsed.SingleFloat);
558         }
559 
560         [Test]
561         [TestCase("3.402824e38", typeof(InvalidProtocolBufferException))]
562         [TestCase("-3.402824e38", typeof(InvalidProtocolBufferException))]
563         [TestCase("1,0", typeof(InvalidJsonException))]
564         [TestCase("1.0.0", typeof(InvalidJsonException))]
565         [TestCase("+1", typeof(InvalidJsonException))]
566         [TestCase("00", typeof(InvalidJsonException))]
567         [TestCase("--1", typeof(InvalidJsonException))]
NumberToFloat_Invalid(string jsonValue, System.Type expectedExceptionType)568         public void NumberToFloat_Invalid(string jsonValue, System.Type expectedExceptionType)
569         {
570             string json = "{ \"singleFloat\": " + jsonValue + "}";
571             Assert.Throws(expectedExceptionType, () => TestAllTypes.Parser.ParseJson(json));
572         }
573 
574         // The simplest way of testing that the value has parsed correctly is to reformat it,
575         // as we trust the formatting. In many cases that will give the same result as the input,
576         // so in those cases we accept an expectedFormatted value of null. Sometimes the results
577         // will be different though, due to a different number of digits being provided.
578         [Test]
579         // Z offset
580         [TestCase("2015-10-09T14:46:23.123456789Z", null)]
581         [TestCase("2015-10-09T14:46:23.123456Z", null)]
582         [TestCase("2015-10-09T14:46:23.123Z", null)]
583         [TestCase("2015-10-09T14:46:23Z", null)]
584         [TestCase("2015-10-09T14:46:23.123456000Z", "2015-10-09T14:46:23.123456Z")]
585         [TestCase("2015-10-09T14:46:23.1234560Z", "2015-10-09T14:46:23.123456Z")]
586         [TestCase("2015-10-09T14:46:23.123000000Z", "2015-10-09T14:46:23.123Z")]
587         [TestCase("2015-10-09T14:46:23.1230Z", "2015-10-09T14:46:23.123Z")]
588         [TestCase("2015-10-09T14:46:23.00Z", "2015-10-09T14:46:23Z")]
589 
590         // +00:00 offset
591         [TestCase("2015-10-09T14:46:23.123456789+00:00", "2015-10-09T14:46:23.123456789Z")]
592         [TestCase("2015-10-09T14:46:23.123456+00:00", "2015-10-09T14:46:23.123456Z")]
593         [TestCase("2015-10-09T14:46:23.123+00:00", "2015-10-09T14:46:23.123Z")]
594         [TestCase("2015-10-09T14:46:23+00:00", "2015-10-09T14:46:23Z")]
595         [TestCase("2015-10-09T14:46:23.123456000+00:00", "2015-10-09T14:46:23.123456Z")]
596         [TestCase("2015-10-09T14:46:23.1234560+00:00", "2015-10-09T14:46:23.123456Z")]
597         [TestCase("2015-10-09T14:46:23.123000000+00:00", "2015-10-09T14:46:23.123Z")]
598         [TestCase("2015-10-09T14:46:23.1230+00:00", "2015-10-09T14:46:23.123Z")]
599         [TestCase("2015-10-09T14:46:23.00+00:00", "2015-10-09T14:46:23Z")]
600 
601         // Other offsets (assume by now that the subsecond handling is okay)
602         [TestCase("2015-10-09T15:46:23.123456789+01:00", "2015-10-09T14:46:23.123456789Z")]
603         [TestCase("2015-10-09T13:46:23.123456789-01:00", "2015-10-09T14:46:23.123456789Z")]
604         [TestCase("2015-10-09T15:16:23.123456789+00:30", "2015-10-09T14:46:23.123456789Z")]
605         [TestCase("2015-10-09T14:16:23.123456789-00:30", "2015-10-09T14:46:23.123456789Z")]
606         [TestCase("2015-10-09T16:31:23.123456789+01:45", "2015-10-09T14:46:23.123456789Z")]
607         [TestCase("2015-10-09T13:01:23.123456789-01:45", "2015-10-09T14:46:23.123456789Z")]
608         [TestCase("2015-10-10T08:46:23.123456789+18:00", "2015-10-09T14:46:23.123456789Z")]
609         [TestCase("2015-10-08T20:46:23.123456789-18:00", "2015-10-09T14:46:23.123456789Z")]
610 
611         // Leap years and min/max
612         [TestCase("2016-02-29T14:46:23.123456789Z", null)]
613         [TestCase("2000-02-29T14:46:23.123456789Z", null)]
614         [TestCase("0001-01-01T00:00:00Z", null)]
615         [TestCase("9999-12-31T23:59:59.999999999Z", null)]
Timestamp_Valid(string jsonValue, string expectedFormatted)616         public void Timestamp_Valid(string jsonValue, string expectedFormatted)
617         {
618             expectedFormatted = expectedFormatted ?? jsonValue;
619             string json = WrapInQuotes(jsonValue);
620             var parsed = Timestamp.Parser.ParseJson(json);
621             Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString());
622         }
623 
624         [Test]
625         [TestCase("2015-10-09 14:46:23.123456789Z", Description = "No T between date and time")]
626         [TestCase("2015/10/09T14:46:23.123456789Z", Description = "Wrong date separators")]
627         [TestCase("2015-10-09T14.46.23.123456789Z", Description = "Wrong time separators")]
628         [TestCase("2015-10-09T14:46:23,123456789Z", Description = "Wrong fractional second separators (valid ISO-8601 though)")]
629         [TestCase(" 2015-10-09T14:46:23.123456789Z", Description = "Whitespace at start")]
630         [TestCase("2015-10-09T14:46:23.123456789Z ", Description = "Whitespace at end")]
631         [TestCase("2015-10-09T14:46:23.1234567890", Description = "Too many digits")]
632         [TestCase("2015-10-09T14:46:23.123456789", Description = "No offset")]
633         [TestCase("2015-13-09T14:46:23.123456789Z", Description = "Invalid month")]
634         [TestCase("2015-10-32T14:46:23.123456789Z", Description = "Invalid day")]
635         [TestCase("2015-10-09T24:00:00.000000000Z", Description = "Invalid hour (valid ISO-8601 though)")]
636         [TestCase("2015-10-09T14:60:23.123456789Z", Description = "Invalid minutes")]
637         [TestCase("2015-10-09T14:46:60.123456789Z", Description = "Invalid seconds")]
638         [TestCase("2015-10-09T14:46:23.123456789+18:01", Description = "Offset too large (positive)")]
639         [TestCase("2015-10-09T14:46:23.123456789-18:01", Description = "Offset too large (negative)")]
640         [TestCase("2015-10-09T14:46:23.123456789-00:00", Description = "Local offset (-00:00) makes no sense here")]
641         [TestCase("0001-01-01T00:00:00+00:01", Description = "Value before earliest when offset applied")]
642         [TestCase("9999-12-31T23:59:59.999999999-00:01", Description = "Value after latest when offset applied")]
643         [TestCase("2100-02-29T14:46:23.123456789Z", Description = "Feb 29th on a non-leap-year")]
Timestamp_Invalid(string jsonValue)644         public void Timestamp_Invalid(string jsonValue)
645         {
646             string json = WrapInQuotes(jsonValue);
647             Assert.Throws<InvalidProtocolBufferException>(() => Timestamp.Parser.ParseJson(json));
648         }
649 
650         [Test]
StructValue_Null()651         public void StructValue_Null()
652         {
653             Assert.AreEqual(new Value { NullValue = 0 }, Value.Parser.ParseJson("null"));
654         }
655 
656         [Test]
StructValue_String()657         public void StructValue_String()
658         {
659             Assert.AreEqual(new Value { StringValue = "hi" }, Value.Parser.ParseJson("\"hi\""));
660         }
661 
662         [Test]
StructValue_Bool()663         public void StructValue_Bool()
664         {
665             Assert.AreEqual(new Value { BoolValue = true }, Value.Parser.ParseJson("true"));
666             Assert.AreEqual(new Value { BoolValue = false }, Value.Parser.ParseJson("false"));
667         }
668 
669         [Test]
StructValue_List()670         public void StructValue_List()
671         {
672             Assert.AreEqual(Value.ForList(Value.ForNumber(1), Value.ForString("x")), Value.Parser.ParseJson("[1, \"x\"]"));
673         }
674 
675         [Test]
ParseListValue()676         public void ParseListValue()
677         {
678             Assert.AreEqual(new ListValue { Values = { Value.ForNumber(1), Value.ForString("x") } }, ListValue.Parser.ParseJson("[1, \"x\"]"));
679         }
680 
681         [Test]
StructValue_Struct()682         public void StructValue_Struct()
683         {
684             Assert.AreEqual(
685                 Value.ForStruct(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } }),
686                 Value.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }"));
687         }
688 
689         [Test]
ParseStruct()690         public void ParseStruct()
691         {
692             Assert.AreEqual(new Struct { Fields = { { "x", Value.ForNumber(1) }, { "y", Value.ForString("z") } } },
693                 Struct.Parser.ParseJson("{ \"x\": 1, \"y\": \"z\" }"));
694         }
695 
696         // TODO for duration parsing: upper and lower bounds.
697         // +/- 315576000000 seconds
698 
699         [Test]
700         [TestCase("1.123456789s", null)]
701         [TestCase("1.123456s", null)]
702         [TestCase("1.123s", null)]
703         [TestCase("1.12300s", "1.123s")]
704         [TestCase("1.12345s", "1.123450s")]
705         [TestCase("1s", null)]
706         [TestCase("-1.123456789s", null)]
707         [TestCase("-1.123456s", null)]
708         [TestCase("-1.123s", null)]
709         [TestCase("-1s", null)]
710         [TestCase("0.123s", null)]
711         [TestCase("-0.123s", null)]
712         [TestCase("123456.123s", null)]
713         [TestCase("-123456.123s", null)]
714         // Upper and lower bounds
715         [TestCase("315576000000s", null)]
716         [TestCase("-315576000000s", null)]
Duration_Valid(string jsonValue, string expectedFormatted)717         public void Duration_Valid(string jsonValue, string expectedFormatted)
718         {
719             expectedFormatted = expectedFormatted ?? jsonValue;
720             string json = WrapInQuotes(jsonValue);
721             var parsed = Duration.Parser.ParseJson(json);
722             Assert.AreEqual(WrapInQuotes(expectedFormatted), parsed.ToString());
723         }
724 
725         // The simplest way of testing that the value has parsed correctly is to reformat it,
726         // as we trust the formatting. In many cases that will give the same result as the input,
727         // so in those cases we accept an expectedFormatted value of null. Sometimes the results
728         // will be different though, due to a different number of digits being provided.
729         [Test]
730         [TestCase("1.1234567890s", Description = "Too many digits")]
731         [TestCase("1.123456789", Description = "No suffix")]
732         [TestCase("1.123456789ss", Description = "Too much suffix")]
733         [TestCase("1.123456789S", Description = "Upper case suffix")]
734         [TestCase("+1.123456789s", Description = "Leading +")]
735         [TestCase(".123456789s", Description = "No integer before the fraction")]
736         [TestCase("1,123456789s", Description = "Comma as decimal separator")]
737         [TestCase("1x1.123456789s", Description = "Non-digit in integer part")]
738         [TestCase("1.1x3456789s", Description = "Non-digit in fractional part")]
739         [TestCase(" 1.123456789s", Description = "Whitespace before fraction")]
740         [TestCase("1.123456789s ", Description = "Whitespace after value")]
741         [TestCase("01.123456789s", Description = "Leading zero (positive)")]
742         [TestCase("-01.123456789s", Description = "Leading zero (negative)")]
743         [TestCase("--0.123456789s", Description = "Double minus sign")]
744         // Violate upper/lower bounds in various ways
745         [TestCase("315576000001s", Description = "Integer part too large")]
746         [TestCase("3155760000000s", Description = "Integer part too long (positive)")]
747         [TestCase("-3155760000000s", Description = "Integer part too long (negative)")]
Duration_Invalid(string jsonValue)748         public void Duration_Invalid(string jsonValue)
749         {
750             string json = WrapInQuotes(jsonValue);
751             Assert.Throws<InvalidProtocolBufferException>(() => Duration.Parser.ParseJson(json));
752         }
753 
754         // Not as many tests for field masks as I'd like; more to be added when we have more
755         // detailed specifications.
756 
757         [Test]
758         [TestCase("")]
759         [TestCase("foo", "foo")]
760         [TestCase("foo,bar", "foo", "bar")]
761         [TestCase("foo.bar", "foo.bar")]
762         [TestCase("fooBar", "foo_bar")]
763         [TestCase("fooBar.bazQux", "foo_bar.baz_qux")]
FieldMask_Valid(string jsonValue, params string[] expectedPaths)764         public void FieldMask_Valid(string jsonValue, params string[] expectedPaths)
765         {
766             string json = WrapInQuotes(jsonValue);
767             var parsed = FieldMask.Parser.ParseJson(json);
768             CollectionAssert.AreEqual(expectedPaths, parsed.Paths);
769         }
770 
771         [Test]
772         [TestCase("foo_bar")]
FieldMask_Invalid(string jsonValue)773         public void FieldMask_Invalid(string jsonValue)
774         {
775             string json = WrapInQuotes(jsonValue);
776             Assert.Throws<InvalidProtocolBufferException>(() => FieldMask.Parser.ParseJson(json));
777         }
778 
779         [Test]
Any_RegularMessage()780         public void Any_RegularMessage()
781         {
782             var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor);
783             var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
784             var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
785             var original = Any.Pack(message);
786             var json = formatter.Format(original); // This is tested in JsonFormatterTest
787             var parser = new JsonParser(new JsonParser.Settings(10, registry));
788             Assert.AreEqual(original, parser.Parse<Any>(json));
789             string valueFirstJson = "{ \"singleInt32\": 10, \"singleNestedMessage\": { \"bb\": 20 }, \"@type\": \"type.googleapis.com/protobuf_unittest.TestAllTypes\" }";
790             Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson));
791         }
792 
793         [Test]
Any_CustomPrefix()794         public void Any_CustomPrefix()
795         {
796             var registry = TypeRegistry.FromMessages(TestAllTypes.Descriptor);
797             var message = new TestAllTypes { SingleInt32 = 10 };
798             var original = Any.Pack(message, "custom.prefix/middle-part");
799             var parser = new JsonParser(new JsonParser.Settings(10, registry));
800             string json = "{ \"@type\": \"custom.prefix/middle-part/protobuf_unittest.TestAllTypes\", \"singleInt32\": 10 }";
801             Assert.AreEqual(original, parser.Parse<Any>(json));
802         }
803 
804         [Test]
Any_UnknownType()805         public void Any_UnknownType()
806         {
807             string json = "{ \"@type\": \"type.googleapis.com/bogus\" }";
808             Assert.Throws<InvalidOperationException>(() => Any.Parser.ParseJson(json));
809         }
810 
811         [Test]
Any_NoTypeUrl()812         public void Any_NoTypeUrl()
813         {
814             string json = "{ \"foo\": \"bar\" }";
815             Assert.Throws<InvalidProtocolBufferException>(() => Any.Parser.ParseJson(json));
816         }
817 
818         [Test]
Any_WellKnownType()819         public void Any_WellKnownType()
820         {
821             var registry = TypeRegistry.FromMessages(Timestamp.Descriptor);
822             var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
823             var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
824             var original = Any.Pack(timestamp);
825             var json = formatter.Format(original); // This is tested in JsonFormatterTest
826             var parser = new JsonParser(new JsonParser.Settings(10, registry));
827             Assert.AreEqual(original, parser.Parse<Any>(json));
828             string valueFirstJson = "{ \"value\": \"1673-06-19T12:34:56Z\", \"@type\": \"type.googleapis.com/google.protobuf.Timestamp\" }";
829             Assert.AreEqual(original, parser.Parse<Any>(valueFirstJson));
830         }
831 
832         [Test]
Any_Nested()833         public void Any_Nested()
834         {
835             var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
836             var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
837             var parser = new JsonParser(new JsonParser.Settings(10, registry));
838             var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
839             var nestedMessage = Any.Pack(doubleNestedMessage);
840             var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
841             var json = formatter.Format(message);
842             // Use the descriptor-based parser just for a change.
843             Assert.AreEqual(message, parser.Parse(json, TestWellKnownTypes.Descriptor));
844         }
845 
846         [Test]
DataAfterObject()847         public void DataAfterObject()
848         {
849             string json = "{} 10";
850             Assert.Throws<InvalidJsonException>(() => TestAllTypes.Parser.ParseJson(json));
851         }
852 
853         /// <summary>
854         /// JSON equivalent to <see cref="CodedInputStreamTest.MaliciousRecursion"/>
855         /// </summary>
856         [Test]
MaliciousRecursion()857         public void MaliciousRecursion()
858         {
859             string data64 = CodedInputStreamTest.MakeRecursiveMessage(64).ToString();
860             string data65 = CodedInputStreamTest.MakeRecursiveMessage(65).ToString();
861 
862             var parser64 = new JsonParser(new JsonParser.Settings(64));
863             CodedInputStreamTest.AssertMessageDepth(parser64.Parse<TestRecursiveMessage>(data64), 64);
864             Assert.Throws<InvalidProtocolBufferException>(() => parser64.Parse<TestRecursiveMessage>(data65));
865 
866             var parser63 = new JsonParser(new JsonParser.Settings(63));
867             Assert.Throws<InvalidProtocolBufferException>(() => parser63.Parse<TestRecursiveMessage>(data64));
868         }
869 
870         [Test]
871         [TestCase("AQI")]
872         [TestCase("_-==")]
Bytes_InvalidBase64(string badBase64)873         public void Bytes_InvalidBase64(string badBase64)
874         {
875             string json = "{ \"singleBytes\": \"" + badBase64 + "\" }";
876             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
877         }
878 
879         [Test]
880         [TestCase("\"FOREIGN_BAR\"", ForeignEnum.ForeignBar)]
881         [TestCase("5", ForeignEnum.ForeignBar)]
882         [TestCase("100", (ForeignEnum)100)]
EnumValid(string value, ForeignEnum expectedValue)883         public void EnumValid(string value, ForeignEnum expectedValue)
884         {
885             string json = "{ \"singleForeignEnum\": " + value + " }";
886             var parsed = TestAllTypes.Parser.ParseJson(json);
887             Assert.AreEqual(new TestAllTypes { SingleForeignEnum = expectedValue }, parsed);
888         }
889 
890         [Test]
891         [TestCase("\"NOT_A_VALID_VALUE\"")]
892         [TestCase("5.5")]
Enum_Invalid(string value)893         public void Enum_Invalid(string value)
894         {
895             string json = "{ \"singleForeignEnum\": " + value + " }";
896             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
897         }
898 
899         [Test]
OneofDuplicate_Invalid()900         public void OneofDuplicate_Invalid()
901         {
902             string json = "{ \"oneofString\": \"x\", \"oneofUint32\": 10 }";
903             Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.Parser.ParseJson(json));
904         }
905 
906         /// <summary>
907         /// Various tests use strings which have quotes round them for parsing or as the result
908         /// of formatting, but without those quotes being specified in the tests (for the sake of readability).
909         /// This method simply returns the input, wrapped in double quotes.
910         /// </summary>
WrapInQuotes(string text)911         internal static string WrapInQuotes(string text)
912         {
913             return '"' + text + '"';
914         }
915     }
916 }