JsonTokenizerTest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 NUnit.Framework;
  33. using System;
  34. using System.IO;
  35. namespace Google.Protobuf
  36. {
  37. public class JsonTokenizerTest
  38. {
  39. [Test]
  40. public void EmptyObjectValue()
  41. {
  42. AssertTokens("{}", JsonToken.StartObject, JsonToken.EndObject);
  43. }
  44. [Test]
  45. public void EmptyArrayValue()
  46. {
  47. AssertTokens("[]", JsonToken.StartArray, JsonToken.EndArray);
  48. }
  49. [Test]
  50. [TestCase("foo", "foo")]
  51. [TestCase("tab\\t", "tab\t")]
  52. [TestCase("line\\nfeed", "line\nfeed")]
  53. [TestCase("carriage\\rreturn", "carriage\rreturn")]
  54. [TestCase("back\\bspace", "back\bspace")]
  55. [TestCase("form\\ffeed", "form\ffeed")]
  56. [TestCase("escaped\\/slash", "escaped/slash")]
  57. [TestCase("escaped\\\\backslash", "escaped\\backslash")]
  58. [TestCase("escaped\\\"quote", "escaped\"quote")]
  59. [TestCase("foo {}[] bar", "foo {}[] bar")]
  60. [TestCase("foo\\u09aFbar", "foo\u09afbar")] // Digits, upper hex, lower hex
  61. [TestCase("ab\ud800\udc00cd", "ab\ud800\udc00cd")]
  62. [TestCase("ab\\ud800\\udc00cd", "ab\ud800\udc00cd")]
  63. public void StringValue(string json, string expectedValue)
  64. {
  65. AssertTokensNoReplacement("\"" + json + "\"", JsonToken.Value(expectedValue));
  66. }
  67. // Valid surrogate pairs, with mixed escaping. These test cases can't be expressed
  68. // using TestCase as they have no valid UTF-8 representation.
  69. // It's unclear exactly how we should handle a mixture of escaped or not: that can't
  70. // come from UTF-8 text, but could come from a .NET string. For the moment,
  71. // treat it as valid in the obvious way.
  72. [Test]
  73. public void MixedSurrogatePairs()
  74. {
  75. string expected = "\ud800\udc00";
  76. AssertTokens("'\\ud800\udc00'", JsonToken.Value(expected));
  77. AssertTokens("'\ud800\\udc00'", JsonToken.Value(expected));
  78. }
  79. [Test]
  80. public void ObjectDepth()
  81. {
  82. string json = "{ \"foo\": { \"x\": 1, \"y\": [ 0 ] } }";
  83. var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
  84. // If we had more tests like this, I'd introduce a helper method... but for one test, it's not worth it.
  85. Assert.AreEqual(0, tokenizer.ObjectDepth);
  86. Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
  87. Assert.AreEqual(1, tokenizer.ObjectDepth);
  88. Assert.AreEqual(JsonToken.Name("foo"), tokenizer.Next());
  89. Assert.AreEqual(1, tokenizer.ObjectDepth);
  90. Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
  91. Assert.AreEqual(2, tokenizer.ObjectDepth);
  92. Assert.AreEqual(JsonToken.Name("x"), tokenizer.Next());
  93. Assert.AreEqual(2, tokenizer.ObjectDepth);
  94. Assert.AreEqual(JsonToken.Value(1), tokenizer.Next());
  95. Assert.AreEqual(2, tokenizer.ObjectDepth);
  96. Assert.AreEqual(JsonToken.Name("y"), tokenizer.Next());
  97. Assert.AreEqual(2, tokenizer.ObjectDepth);
  98. Assert.AreEqual(JsonToken.StartArray, tokenizer.Next());
  99. Assert.AreEqual(2, tokenizer.ObjectDepth); // Depth hasn't changed in array
  100. Assert.AreEqual(JsonToken.Value(0), tokenizer.Next());
  101. Assert.AreEqual(2, tokenizer.ObjectDepth);
  102. Assert.AreEqual(JsonToken.EndArray, tokenizer.Next());
  103. Assert.AreEqual(2, tokenizer.ObjectDepth);
  104. Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
  105. Assert.AreEqual(1, tokenizer.ObjectDepth);
  106. Assert.AreEqual(JsonToken.EndObject, tokenizer.Next());
  107. Assert.AreEqual(0, tokenizer.ObjectDepth);
  108. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  109. Assert.AreEqual(0, tokenizer.ObjectDepth);
  110. }
  111. [Test]
  112. public void ObjectDepth_WithPushBack()
  113. {
  114. string json = "{}";
  115. var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json));
  116. Assert.AreEqual(0, tokenizer.ObjectDepth);
  117. var token = tokenizer.Next();
  118. Assert.AreEqual(1, tokenizer.ObjectDepth);
  119. // When we push back a "start object", we should effectively be back to the previous depth.
  120. tokenizer.PushBack(token);
  121. Assert.AreEqual(0, tokenizer.ObjectDepth);
  122. // Read the same token again, and get back to depth 1
  123. token = tokenizer.Next();
  124. Assert.AreEqual(1, tokenizer.ObjectDepth);
  125. // Now the same in reverse, with EndObject
  126. token = tokenizer.Next();
  127. Assert.AreEqual(0, tokenizer.ObjectDepth);
  128. tokenizer.PushBack(token);
  129. Assert.AreEqual(1, tokenizer.ObjectDepth);
  130. tokenizer.Next();
  131. Assert.AreEqual(0, tokenizer.ObjectDepth);
  132. }
  133. [Test]
  134. [TestCase("embedded tab\t")]
  135. [TestCase("embedded CR\r")]
  136. [TestCase("embedded LF\n")]
  137. [TestCase("embedded bell\u0007")]
  138. [TestCase("bad escape\\a")]
  139. [TestCase("incomplete escape\\")]
  140. [TestCase("incomplete Unicode escape\\u000")]
  141. [TestCase("invalid Unicode escape\\u000H")]
  142. // Surrogate pair handling, both in raw .NET strings and escaped. We only need
  143. // to detect this in strings, as non-ASCII characters anywhere other than in strings
  144. // will already lead to parsing errors.
  145. [TestCase("\\ud800")]
  146. [TestCase("\\udc00")]
  147. [TestCase("\\ud800x")]
  148. [TestCase("\\udc00x")]
  149. [TestCase("\\udc00\\ud800y")]
  150. public void InvalidStringValue(string json)
  151. {
  152. AssertThrowsAfter("\"" + json + "\"");
  153. }
  154. // Tests for invalid strings that can't be expressed in attributes,
  155. // as the constants can't be expressed as UTF-8 strings.
  156. [Test]
  157. public void InvalidSurrogatePairs()
  158. {
  159. AssertThrowsAfter("\"\ud800x\"");
  160. AssertThrowsAfter("\"\udc00y\"");
  161. AssertThrowsAfter("\"\udc00\ud800y\"");
  162. }
  163. [Test]
  164. [TestCase("0", 0)]
  165. [TestCase("-0", 0)] // We don't distinguish between positive and negative 0
  166. [TestCase("1", 1)]
  167. [TestCase("-1", -1)]
  168. // From here on, assume leading sign is okay...
  169. [TestCase("1.125", 1.125)]
  170. [TestCase("1.0", 1)]
  171. [TestCase("1e5", 100000)]
  172. [TestCase("1e000000", 1)] // Weird, but not prohibited by the spec
  173. [TestCase("1E5", 100000)]
  174. [TestCase("1e+5", 100000)]
  175. [TestCase("1E-5", 0.00001)]
  176. [TestCase("123E-2", 1.23)]
  177. [TestCase("123.45E3", 123450)]
  178. [TestCase(" 1 ", 1)]
  179. public void NumberValue(string json, double expectedValue)
  180. {
  181. AssertTokens(json, JsonToken.Value(expectedValue));
  182. }
  183. [Test]
  184. [TestCase("00")]
  185. [TestCase(".5")]
  186. [TestCase("1.")]
  187. [TestCase("1e")]
  188. [TestCase("1e-")]
  189. [TestCase("--")]
  190. [TestCase("--1")]
  191. // Skip these test cases in .NET 5 because floating point parsing supports bigger values.
  192. // These big values won't throw an error in the test.
  193. #if !NET5_0
  194. [TestCase("-1.7977e308")]
  195. [TestCase("1.7977e308")]
  196. #endif
  197. public void InvalidNumberValue(string json)
  198. {
  199. AssertThrowsAfter(json);
  200. }
  201. [Test]
  202. [TestCase("nul")]
  203. [TestCase("nothing")]
  204. [TestCase("truth")]
  205. [TestCase("fALSEhood")]
  206. public void InvalidLiterals(string json)
  207. {
  208. AssertThrowsAfter(json);
  209. }
  210. [Test]
  211. public void NullValue()
  212. {
  213. AssertTokens("null", JsonToken.Null);
  214. }
  215. [Test]
  216. public void TrueValue()
  217. {
  218. AssertTokens("true", JsonToken.True);
  219. }
  220. [Test]
  221. public void FalseValue()
  222. {
  223. AssertTokens("false", JsonToken.False);
  224. }
  225. [Test]
  226. public void SimpleObject()
  227. {
  228. AssertTokens("{'x': 'y'}",
  229. JsonToken.StartObject, JsonToken.Name("x"), JsonToken.Value("y"), JsonToken.EndObject);
  230. }
  231. [Test]
  232. [TestCase("[10, 20", 3)]
  233. [TestCase("[10,", 2)]
  234. [TestCase("[10:20]", 2)]
  235. [TestCase("[", 1)]
  236. [TestCase("[,", 1)]
  237. [TestCase("{", 1)]
  238. [TestCase("{,", 1)]
  239. [TestCase("{[", 1)]
  240. [TestCase("{{", 1)]
  241. [TestCase("{0", 1)]
  242. [TestCase("{null", 1)]
  243. [TestCase("{false", 1)]
  244. [TestCase("{true", 1)]
  245. [TestCase("}", 0)]
  246. [TestCase("]", 0)]
  247. [TestCase(",", 0)]
  248. [TestCase("'foo' 'bar'", 1)]
  249. [TestCase(":", 0)]
  250. [TestCase("'foo", 0)] // Incomplete string
  251. [TestCase("{ 'foo' }", 2)]
  252. [TestCase("{ x:1", 1)] // Property names must be quoted
  253. [TestCase("{]", 1)]
  254. [TestCase("[}", 1)]
  255. [TestCase("[1,", 2)]
  256. [TestCase("{'x':0]", 3)]
  257. [TestCase("{ 'foo': }", 2)]
  258. [TestCase("{ 'foo':'bar', }", 3)]
  259. public void InvalidStructure(string json, int expectedValidTokens)
  260. {
  261. // Note: we don't test that the earlier tokens are exactly as expected,
  262. // partly because that's hard to parameterize.
  263. var reader = new StringReader(json.Replace('\'', '"'));
  264. var tokenizer = JsonTokenizer.FromTextReader(reader);
  265. for (int i = 0; i < expectedValidTokens; i++)
  266. {
  267. Assert.IsNotNull(tokenizer.Next());
  268. }
  269. Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
  270. }
  271. [Test]
  272. public void ArrayMixedType()
  273. {
  274. AssertTokens("[1, 'foo', null, false, true, [2], {'x':'y' }]",
  275. JsonToken.StartArray,
  276. JsonToken.Value(1),
  277. JsonToken.Value("foo"),
  278. JsonToken.Null,
  279. JsonToken.False,
  280. JsonToken.True,
  281. JsonToken.StartArray,
  282. JsonToken.Value(2),
  283. JsonToken.EndArray,
  284. JsonToken.StartObject,
  285. JsonToken.Name("x"),
  286. JsonToken.Value("y"),
  287. JsonToken.EndObject,
  288. JsonToken.EndArray);
  289. }
  290. [Test]
  291. public void ObjectMixedType()
  292. {
  293. AssertTokens(@"{'a': 1, 'b': 'bar', 'c': null, 'd': false, 'e': true,
  294. 'f': [2], 'g': {'x':'y' }}",
  295. JsonToken.StartObject,
  296. JsonToken.Name("a"),
  297. JsonToken.Value(1),
  298. JsonToken.Name("b"),
  299. JsonToken.Value("bar"),
  300. JsonToken.Name("c"),
  301. JsonToken.Null,
  302. JsonToken.Name("d"),
  303. JsonToken.False,
  304. JsonToken.Name("e"),
  305. JsonToken.True,
  306. JsonToken.Name("f"),
  307. JsonToken.StartArray,
  308. JsonToken.Value(2),
  309. JsonToken.EndArray,
  310. JsonToken.Name("g"),
  311. JsonToken.StartObject,
  312. JsonToken.Name("x"),
  313. JsonToken.Value("y"),
  314. JsonToken.EndObject,
  315. JsonToken.EndObject);
  316. }
  317. [Test]
  318. public void NextAfterEndDocumentThrows()
  319. {
  320. var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
  321. Assert.AreEqual(JsonToken.Null, tokenizer.Next());
  322. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  323. Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
  324. }
  325. [Test]
  326. public void CanPushBackEndDocument()
  327. {
  328. var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
  329. Assert.AreEqual(JsonToken.Null, tokenizer.Next());
  330. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  331. tokenizer.PushBack(JsonToken.EndDocument);
  332. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  333. Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
  334. }
  335. [Test]
  336. [TestCase("{ 'skip': 0, 'next': 1")]
  337. [TestCase("{ 'skip': [0, 1, 2], 'next': 1")]
  338. [TestCase("{ 'skip': 'x', 'next': 1")]
  339. [TestCase("{ 'skip': ['x', 'y'], 'next': 1")]
  340. [TestCase("{ 'skip': {'a': 0}, 'next': 1")]
  341. [TestCase("{ 'skip': {'a': [0, {'b':[]}]}, 'next': 1")]
  342. public void SkipValue(string json)
  343. {
  344. var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json.Replace('\'', '"')));
  345. Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
  346. Assert.AreEqual("skip", tokenizer.Next().StringValue);
  347. tokenizer.SkipValue();
  348. Assert.AreEqual("next", tokenizer.Next().StringValue);
  349. }
  350. /// <summary>
  351. /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
  352. /// All apostrophes are first converted to double quotes, allowing any tests
  353. /// that don't need to check actual apostrophe handling to use apostrophes in the JSON, avoiding
  354. /// messy string literal escaping. The "end document" token is not specified in the list of
  355. /// expected tokens, but is implicit.
  356. /// </summary>
  357. private static void AssertTokens(string json, params JsonToken[] expectedTokens)
  358. {
  359. AssertTokensNoReplacement(json.Replace('\'', '"'), expectedTokens);
  360. }
  361. /// <summary>
  362. /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
  363. /// Unlike <see cref="AssertTokens(string, JsonToken[])"/>, this does not perform any character
  364. /// replacement on the specified JSON, and should be used when the text contains apostrophes which
  365. /// are expected to be used *as* apostrophes. The "end document" token is not specified in the list of
  366. /// expected tokens, but is implicit.
  367. /// </summary>
  368. private static void AssertTokensNoReplacement(string json, params JsonToken[] expectedTokens)
  369. {
  370. var reader = new StringReader(json);
  371. var tokenizer = JsonTokenizer.FromTextReader(reader);
  372. for (int i = 0; i < expectedTokens.Length; i++)
  373. {
  374. var actualToken = tokenizer.Next();
  375. if (actualToken == JsonToken.EndDocument)
  376. {
  377. Assert.Fail("Expected {0} but reached end of token stream", expectedTokens[i]);
  378. }
  379. Assert.AreEqual(expectedTokens[i], actualToken);
  380. }
  381. var finalToken = tokenizer.Next();
  382. if (finalToken != JsonToken.EndDocument)
  383. {
  384. Assert.Fail("Expected token stream to be exhausted; received {0}", finalToken);
  385. }
  386. }
  387. private static void AssertThrowsAfter(string json, params JsonToken[] expectedTokens)
  388. {
  389. var reader = new StringReader(json);
  390. var tokenizer = JsonTokenizer.FromTextReader(reader);
  391. for (int i = 0; i < expectedTokens.Length; i++)
  392. {
  393. var actualToken = tokenizer.Next();
  394. if (actualToken == JsonToken.EndDocument)
  395. {
  396. Assert.Fail("Expected {0} but reached end of document", expectedTokens[i]);
  397. }
  398. Assert.AreEqual(expectedTokens[i], actualToken);
  399. }
  400. Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
  401. }
  402. }
  403. }