JsonParserTest.cs 42 KB

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