JsonFormatterTest.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 System;
  33. using Google.Protobuf.TestProtos;
  34. using NUnit.Framework;
  35. using UnitTest.Issues.TestProtos;
  36. using Google.Protobuf.WellKnownTypes;
  37. namespace Google.Protobuf
  38. {
  39. /// <summary>
  40. /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes
  41. /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details.
  42. /// </summary>
  43. public class JsonFormatterTest
  44. {
  45. [Test]
  46. public void DefaultValues_WhenOmitted()
  47. {
  48. var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: false));
  49. AssertJson("{ }", formatter.Format(new ForeignMessage()));
  50. AssertJson("{ }", formatter.Format(new TestAllTypes()));
  51. AssertJson("{ }", formatter.Format(new TestMap()));
  52. }
  53. [Test]
  54. public void DefaultValues_WhenIncluded()
  55. {
  56. var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: true));
  57. AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage()));
  58. }
  59. [Test]
  60. public void AllSingleFields()
  61. {
  62. var message = new TestAllTypes
  63. {
  64. SingleBool = true,
  65. SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
  66. SingleDouble = 23.5,
  67. SingleFixed32 = 23,
  68. SingleFixed64 = 1234567890123,
  69. SingleFloat = 12.25f,
  70. SingleForeignEnum = ForeignEnum.FOREIGN_BAR,
  71. SingleForeignMessage = new ForeignMessage { C = 10 },
  72. SingleImportEnum = ImportEnum.IMPORT_BAZ,
  73. SingleImportMessage = new ImportMessage { D = 20 },
  74. SingleInt32 = 100,
  75. SingleInt64 = 3210987654321,
  76. SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO,
  77. SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
  78. SinglePublicImportMessage = new PublicImportMessage { E = 54 },
  79. SingleSfixed32 = -123,
  80. SingleSfixed64 = -12345678901234,
  81. SingleSint32 = -456,
  82. SingleSint64 = -12345678901235,
  83. SingleString = "test\twith\ttabs",
  84. SingleUint32 = uint.MaxValue,
  85. SingleUint64 = ulong.MaxValue,
  86. };
  87. var actualText = JsonFormatter.Default.Format(message);
  88. // Fields in numeric order
  89. var expectedText = "{ " +
  90. "'singleInt32': 100, " +
  91. "'singleInt64': '3210987654321', " +
  92. "'singleUint32': 4294967295, " +
  93. "'singleUint64': '18446744073709551615', " +
  94. "'singleSint32': -456, " +
  95. "'singleSint64': '-12345678901235', " +
  96. "'singleFixed32': 23, " +
  97. "'singleFixed64': '1234567890123', " +
  98. "'singleSfixed32': -123, " +
  99. "'singleSfixed64': '-12345678901234', " +
  100. "'singleFloat': 12.25, " +
  101. "'singleDouble': 23.5, " +
  102. "'singleBool': true, " +
  103. "'singleString': 'test\\twith\\ttabs', " +
  104. "'singleBytes': 'AQIDBA==', " +
  105. "'singleNestedMessage': { 'bb': 35 }, " +
  106. "'singleForeignMessage': { 'c': 10 }, " +
  107. "'singleImportMessage': { 'd': 20 }, " +
  108. "'singleNestedEnum': 'FOO', " +
  109. "'singleForeignEnum': 'FOREIGN_BAR', " +
  110. "'singleImportEnum': 'IMPORT_BAZ', " +
  111. "'singlePublicImportMessage': { 'e': 54 }" +
  112. " }";
  113. AssertJson(expectedText, actualText);
  114. }
  115. [Test]
  116. public void RepeatedField()
  117. {
  118. AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }",
  119. JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } }));
  120. }
  121. [Test]
  122. public void MapField_StringString()
  123. {
  124. AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }",
  125. JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }));
  126. }
  127. [Test]
  128. public void MapField_Int32Int32()
  129. {
  130. // The keys are quoted, but the values aren't.
  131. AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }",
  132. JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }));
  133. }
  134. [Test]
  135. public void MapField_BoolBool()
  136. {
  137. // The keys are quoted, but the values aren't.
  138. AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }",
  139. JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } }));
  140. }
  141. [TestCase(1.0, "1")]
  142. [TestCase(double.NaN, "'NaN'")]
  143. [TestCase(double.PositiveInfinity, "'Infinity'")]
  144. [TestCase(double.NegativeInfinity, "'-Infinity'")]
  145. public void DoubleRepresentations(double value, string expectedValueText)
  146. {
  147. var message = new TestAllTypes { SingleDouble = value };
  148. string actualText = JsonFormatter.Default.Format(message);
  149. string expectedText = "{ 'singleDouble': " + expectedValueText + " }";
  150. AssertJson(expectedText, actualText);
  151. }
  152. [Test]
  153. public void UnknownEnumValueOmitted_SingleField()
  154. {
  155. var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 };
  156. AssertJson("{ }", JsonFormatter.Default.Format(message));
  157. }
  158. [Test]
  159. public void UnknownEnumValueOmitted_RepeatedField()
  160. {
  161. var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.FOREIGN_BAZ, (ForeignEnum) 100, ForeignEnum.FOREIGN_FOO } };
  162. AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message));
  163. }
  164. [Test]
  165. public void UnknownEnumValueOmitted_MapField()
  166. {
  167. // This matches the C++ behaviour.
  168. var message = new TestMap { MapInt32Enum = { { 1, MapEnum.MAP_ENUM_FOO }, { 2, (MapEnum) 100 }, { 3, MapEnum.MAP_ENUM_BAR } } };
  169. AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message));
  170. }
  171. [Test]
  172. public void UnknownEnumValueOmitted_RepeatedField_AllEntriesUnknown()
  173. {
  174. // *Maybe* we should hold off on writing the "[" until we find that we've got at least one value to write...
  175. // but this is what happens at the moment, and it doesn't seem too awful.
  176. var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } };
  177. AssertJson("{ 'repeatedForeignEnum': [ ] }", JsonFormatter.Default.Format(message));
  178. }
  179. [Test]
  180. public void NullValueForMessage()
  181. {
  182. var message = new TestMap { MapInt32ForeignMessage = { { 10, null } } };
  183. AssertJson("{ 'mapInt32ForeignMessage': { '10': null } }", JsonFormatter.Default.Format(message));
  184. }
  185. [Test]
  186. [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit
  187. [TestCase("a\u0601b", "a\\u0601b")] // Ranged
  188. [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...)
  189. public void SimpleNonAscii(string text, string encoded)
  190. {
  191. var message = new TestAllTypes { SingleString = text };
  192. AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message));
  193. }
  194. [Test]
  195. public void SurrogatePairEscaping()
  196. {
  197. var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" };
  198. AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message));
  199. }
  200. [Test]
  201. public void InvalidSurrogatePairsFail()
  202. {
  203. // Note: don't use TestCase for these, as the strings can't be reliably represented
  204. // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/
  205. // Lone low surrogate
  206. var message = new TestAllTypes { SingleString = "a\uDC01b" };
  207. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  208. // Lone high surrogate
  209. message = new TestAllTypes { SingleString = "a\uD801b" };
  210. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  211. }
  212. [Test]
  213. [TestCase("foo_bar", "fooBar")]
  214. [TestCase("bananaBanana", "bananaBanana")]
  215. [TestCase("BANANABanana", "bananaBanana")]
  216. public void ToCamelCase(string original, string expected)
  217. {
  218. Assert.AreEqual(expected, JsonFormatter.ToCamelCase(original));
  219. }
  220. [Test]
  221. [TestCase(null, "{ }")]
  222. [TestCase("x", "{ 'fooString': 'x' }")]
  223. [TestCase("", "{ 'fooString': '' }")]
  224. public void Oneof(string fooStringValue, string expectedJson)
  225. {
  226. var message = new TestOneof();
  227. if (fooStringValue != null)
  228. {
  229. message.FooString = fooStringValue;
  230. }
  231. // We should get the same result both with and without "format default values".
  232. var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
  233. AssertJson(expectedJson, formatter.Format(message));
  234. formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  235. AssertJson(expectedJson, formatter.Format(message));
  236. }
  237. [Test]
  238. public void WrapperFormatting_Single()
  239. {
  240. // Just a few examples, handling both classes and value types, and
  241. // default vs non-default values
  242. var message = new TestWellKnownTypes
  243. {
  244. Int64Field = 10,
  245. Int32Field = 0,
  246. BytesField = ByteString.FromBase64("ABCD"),
  247. StringField = ""
  248. };
  249. var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }";
  250. AssertJson(expectedJson, JsonFormatter.Default.Format(message));
  251. }
  252. [Test]
  253. public void WrapperFormatting_IncludeNull()
  254. {
  255. // The actual JSON here is very large because there are lots of fields. Just test a couple of them.
  256. var message = new TestWellKnownTypes { Int32Field = 10 };
  257. var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  258. var actualJson = formatter.Format(message);
  259. Assert.IsTrue(actualJson.Contains("\"int64Field\": null"));
  260. Assert.IsFalse(actualJson.Contains("\"int32Field\": null"));
  261. }
  262. [Test]
  263. public void OutputIsInNumericFieldOrder_NoDefaults()
  264. {
  265. var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
  266. var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 };
  267. AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message));
  268. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  269. AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
  270. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  271. AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
  272. }
  273. [Test]
  274. public void OutputIsInNumericFieldOrder_WithDefaults()
  275. {
  276. var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
  277. var message = new TestJsonFieldOrdering();
  278. AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message));
  279. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  280. AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
  281. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  282. AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
  283. }
  284. [Test]
  285. public void TimestampStandalone()
  286. {
  287. Assert.AreEqual("1970-01-01T00:00:00Z", new Timestamp().ToString());
  288. Assert.AreEqual("1970-01-01T00:00:00.100Z", new Timestamp { Nanos = 100000000 }.ToString());
  289. Assert.AreEqual("1970-01-01T00:00:00.120Z", new Timestamp { Nanos = 120000000 }.ToString());
  290. Assert.AreEqual("1970-01-01T00:00:00.123Z", new Timestamp { Nanos = 123000000 }.ToString());
  291. Assert.AreEqual("1970-01-01T00:00:00.123400Z", new Timestamp { Nanos = 123400000 }.ToString());
  292. Assert.AreEqual("1970-01-01T00:00:00.123450Z", new Timestamp { Nanos = 123450000 }.ToString());
  293. Assert.AreEqual("1970-01-01T00:00:00.123456Z", new Timestamp { Nanos = 123456000 }.ToString());
  294. Assert.AreEqual("1970-01-01T00:00:00.123456700Z", new Timestamp { Nanos = 123456700 }.ToString());
  295. Assert.AreEqual("1970-01-01T00:00:00.123456780Z", new Timestamp { Nanos = 123456780 }.ToString());
  296. Assert.AreEqual("1970-01-01T00:00:00.123456789Z", new Timestamp { Nanos = 123456789 }.ToString());
  297. // One before and one after the Unix epoch
  298. Assert.AreEqual("1673-06-19T12:34:56Z",
  299. new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString());
  300. Assert.AreEqual("2015-07-31T10:29:34Z",
  301. new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString());
  302. }
  303. [Test]
  304. public void TimestampField()
  305. {
  306. var message = new TestWellKnownTypes { TimestampField = new Timestamp() };
  307. AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message));
  308. }
  309. [Test]
  310. [TestCase(0, 0, "0s")]
  311. [TestCase(1, 0, "1s")]
  312. [TestCase(-1, 0, "-1s")]
  313. [TestCase(0, 100000000, "0.100s")]
  314. [TestCase(0, 120000000, "0.120s")]
  315. [TestCase(0, 123000000, "0.123s")]
  316. [TestCase(0, 123400000, "0.123400s")]
  317. [TestCase(0, 123450000, "0.123450s")]
  318. [TestCase(0, 123456000, "0.123456s")]
  319. [TestCase(0, 123456700, "0.123456700s")]
  320. [TestCase(0, 123456780, "0.123456780s")]
  321. [TestCase(0, 123456789, "0.123456789s")]
  322. [TestCase(0, -100000000, "-0.100s")]
  323. [TestCase(1, 100000000, "1.100s")]
  324. [TestCase(-1, -100000000, "-1.100s")]
  325. // Non-normalized examples
  326. [TestCase(1, 2123456789, "3.123456789s")]
  327. [TestCase(1, -100000000, "0.900s")]
  328. public void DurationStandalone(long seconds, int nanoseconds, string expected)
  329. {
  330. Assert.AreEqual(expected, new Duration { Seconds = seconds, Nanos = nanoseconds }.ToString());
  331. }
  332. [Test]
  333. public void DurationField()
  334. {
  335. var message = new TestWellKnownTypes { DurationField = new Duration() };
  336. AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message));
  337. }
  338. [Test]
  339. public void StructSample()
  340. {
  341. var message = new Struct
  342. {
  343. Fields =
  344. {
  345. { "a", new Value { NullValue = new NullValue() } },
  346. { "b", new Value { BoolValue = false } },
  347. { "c", new Value { NumberValue = 10.5 } },
  348. { "d", new Value { StringValue = "text" } },
  349. { "e", new Value { ListValue = new ListValue { Values = { new Value { StringValue = "t1" }, new Value { NumberValue = 5 } } } } },
  350. { "f", new Value { StructValue = new Struct { Fields = { { "nested", new Value { StringValue = "value" } } } } } }
  351. }
  352. };
  353. AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString());
  354. }
  355. [Test]
  356. public void FieldMaskStandalone()
  357. {
  358. var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } };
  359. Assert.AreEqual(",single,withUnderscore,nested.field.name,nested..doubleDot", fieldMask.ToString());
  360. // Invalid, but we shouldn't create broken JSON...
  361. fieldMask = new FieldMask { Paths = { "x\\y" } };
  362. Assert.AreEqual(@"x\\y", fieldMask.ToString());
  363. }
  364. [Test]
  365. public void FieldMaskField()
  366. {
  367. var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } };
  368. AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message));
  369. }
  370. /// <summary>
  371. /// Checks that the actual JSON is the same as the expected JSON - but after replacing
  372. /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier
  373. /// to read.
  374. /// </summary>
  375. private static void AssertJson(string expectedJsonWithApostrophes, string actualJson)
  376. {
  377. var expectedJson = expectedJsonWithApostrophes.Replace("'", "\"");
  378. Assert.AreEqual(expectedJson, actualJson);
  379. }
  380. }
  381. }