JsonTokenizerTest.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. [TestCase("-1.7977e308")]
  192. [TestCase("1.7977e308")]
  193. public void InvalidNumberValue(string json)
  194. {
  195. AssertThrowsAfter(json);
  196. }
  197. [Test]
  198. [TestCase("nul")]
  199. [TestCase("nothing")]
  200. [TestCase("truth")]
  201. [TestCase("fALSEhood")]
  202. public void InvalidLiterals(string json)
  203. {
  204. AssertThrowsAfter(json);
  205. }
  206. [Test]
  207. public void NullValue()
  208. {
  209. AssertTokens("null", JsonToken.Null);
  210. }
  211. [Test]
  212. public void TrueValue()
  213. {
  214. AssertTokens("true", JsonToken.True);
  215. }
  216. [Test]
  217. public void FalseValue()
  218. {
  219. AssertTokens("false", JsonToken.False);
  220. }
  221. [Test]
  222. public void SimpleObject()
  223. {
  224. AssertTokens("{'x': 'y'}",
  225. JsonToken.StartObject, JsonToken.Name("x"), JsonToken.Value("y"), JsonToken.EndObject);
  226. }
  227. [Test]
  228. [TestCase("[10, 20", 3)]
  229. [TestCase("[10,", 2)]
  230. [TestCase("[10:20]", 2)]
  231. [TestCase("[", 1)]
  232. [TestCase("[,", 1)]
  233. [TestCase("{", 1)]
  234. [TestCase("{,", 1)]
  235. [TestCase("{[", 1)]
  236. [TestCase("{{", 1)]
  237. [TestCase("{0", 1)]
  238. [TestCase("{null", 1)]
  239. [TestCase("{false", 1)]
  240. [TestCase("{true", 1)]
  241. [TestCase("}", 0)]
  242. [TestCase("]", 0)]
  243. [TestCase(",", 0)]
  244. [TestCase("'foo' 'bar'", 1)]
  245. [TestCase(":", 0)]
  246. [TestCase("'foo", 0)] // Incomplete string
  247. [TestCase("{ 'foo' }", 2)]
  248. [TestCase("{ x:1", 1)] // Property names must be quoted
  249. [TestCase("{]", 1)]
  250. [TestCase("[}", 1)]
  251. [TestCase("[1,", 2)]
  252. [TestCase("{'x':0]", 3)]
  253. [TestCase("{ 'foo': }", 2)]
  254. [TestCase("{ 'foo':'bar', }", 3)]
  255. public void InvalidStructure(string json, int expectedValidTokens)
  256. {
  257. // Note: we don't test that the earlier tokens are exactly as expected,
  258. // partly because that's hard to parameterize.
  259. var reader = new StringReader(json.Replace('\'', '"'));
  260. var tokenizer = JsonTokenizer.FromTextReader(reader);
  261. for (int i = 0; i < expectedValidTokens; i++)
  262. {
  263. Assert.IsNotNull(tokenizer.Next());
  264. }
  265. Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
  266. }
  267. [Test]
  268. public void ArrayMixedType()
  269. {
  270. AssertTokens("[1, 'foo', null, false, true, [2], {'x':'y' }]",
  271. JsonToken.StartArray,
  272. JsonToken.Value(1),
  273. JsonToken.Value("foo"),
  274. JsonToken.Null,
  275. JsonToken.False,
  276. JsonToken.True,
  277. JsonToken.StartArray,
  278. JsonToken.Value(2),
  279. JsonToken.EndArray,
  280. JsonToken.StartObject,
  281. JsonToken.Name("x"),
  282. JsonToken.Value("y"),
  283. JsonToken.EndObject,
  284. JsonToken.EndArray);
  285. }
  286. [Test]
  287. public void ObjectMixedType()
  288. {
  289. AssertTokens(@"{'a': 1, 'b': 'bar', 'c': null, 'd': false, 'e': true,
  290. 'f': [2], 'g': {'x':'y' }}",
  291. JsonToken.StartObject,
  292. JsonToken.Name("a"),
  293. JsonToken.Value(1),
  294. JsonToken.Name("b"),
  295. JsonToken.Value("bar"),
  296. JsonToken.Name("c"),
  297. JsonToken.Null,
  298. JsonToken.Name("d"),
  299. JsonToken.False,
  300. JsonToken.Name("e"),
  301. JsonToken.True,
  302. JsonToken.Name("f"),
  303. JsonToken.StartArray,
  304. JsonToken.Value(2),
  305. JsonToken.EndArray,
  306. JsonToken.Name("g"),
  307. JsonToken.StartObject,
  308. JsonToken.Name("x"),
  309. JsonToken.Value("y"),
  310. JsonToken.EndObject,
  311. JsonToken.EndObject);
  312. }
  313. [Test]
  314. public void NextAfterEndDocumentThrows()
  315. {
  316. var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
  317. Assert.AreEqual(JsonToken.Null, tokenizer.Next());
  318. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  319. Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
  320. }
  321. [Test]
  322. public void CanPushBackEndDocument()
  323. {
  324. var tokenizer = JsonTokenizer.FromTextReader(new StringReader("null"));
  325. Assert.AreEqual(JsonToken.Null, tokenizer.Next());
  326. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  327. tokenizer.PushBack(JsonToken.EndDocument);
  328. Assert.AreEqual(JsonToken.EndDocument, tokenizer.Next());
  329. Assert.Throws<InvalidOperationException>(() => tokenizer.Next());
  330. }
  331. [Test]
  332. [TestCase("{ 'skip': 0, 'next': 1")]
  333. [TestCase("{ 'skip': [0, 1, 2], 'next': 1")]
  334. [TestCase("{ 'skip': 'x', 'next': 1")]
  335. [TestCase("{ 'skip': ['x', 'y'], 'next': 1")]
  336. [TestCase("{ 'skip': {'a': 0}, 'next': 1")]
  337. [TestCase("{ 'skip': {'a': [0, {'b':[]}]}, 'next': 1")]
  338. public void SkipValue(string json)
  339. {
  340. var tokenizer = JsonTokenizer.FromTextReader(new StringReader(json.Replace('\'', '"')));
  341. Assert.AreEqual(JsonToken.StartObject, tokenizer.Next());
  342. Assert.AreEqual("skip", tokenizer.Next().StringValue);
  343. tokenizer.SkipValue();
  344. Assert.AreEqual("next", tokenizer.Next().StringValue);
  345. }
  346. /// <summary>
  347. /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
  348. /// All apostrophes are first converted to double quotes, allowing any tests
  349. /// that don't need to check actual apostrophe handling to use apostrophes in the JSON, avoiding
  350. /// messy string literal escaping. The "end document" token is not specified in the list of
  351. /// expected tokens, but is implicit.
  352. /// </summary>
  353. private static void AssertTokens(string json, params JsonToken[] expectedTokens)
  354. {
  355. AssertTokensNoReplacement(json.Replace('\'', '"'), expectedTokens);
  356. }
  357. /// <summary>
  358. /// Asserts that the specified JSON is tokenized into the given sequence of tokens.
  359. /// Unlike <see cref="AssertTokens(string, JsonToken[])"/>, this does not perform any character
  360. /// replacement on the specified JSON, and should be used when the text contains apostrophes which
  361. /// are expected to be used *as* apostrophes. The "end document" token is not specified in the list of
  362. /// expected tokens, but is implicit.
  363. /// </summary>
  364. private static void AssertTokensNoReplacement(string json, params JsonToken[] expectedTokens)
  365. {
  366. var reader = new StringReader(json);
  367. var tokenizer = JsonTokenizer.FromTextReader(reader);
  368. for (int i = 0; i < expectedTokens.Length; i++)
  369. {
  370. var actualToken = tokenizer.Next();
  371. if (actualToken == JsonToken.EndDocument)
  372. {
  373. Assert.Fail("Expected {0} but reached end of token stream", expectedTokens[i]);
  374. }
  375. Assert.AreEqual(expectedTokens[i], actualToken);
  376. }
  377. var finalToken = tokenizer.Next();
  378. if (finalToken != JsonToken.EndDocument)
  379. {
  380. Assert.Fail("Expected token stream to be exhausted; received {0}", finalToken);
  381. }
  382. }
  383. private static void AssertThrowsAfter(string json, params JsonToken[] expectedTokens)
  384. {
  385. var reader = new StringReader(json);
  386. var tokenizer = JsonTokenizer.FromTextReader(reader);
  387. for (int i = 0; i < expectedTokens.Length; i++)
  388. {
  389. var actualToken = tokenizer.Next();
  390. if (actualToken == JsonToken.EndDocument)
  391. {
  392. Assert.Fail("Expected {0} but reached end of document", expectedTokens[i]);
  393. }
  394. Assert.AreEqual(expectedTokens[i], actualToken);
  395. }
  396. Assert.Throws<InvalidJsonException>(() => tokenizer.Next());
  397. }
  398. }
  399. }