JsonFormatterTest.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. using Google.Protobuf.Reflection;
  38. using static Google.Protobuf.JsonParserTest; // For WrapInQuotes
  39. using System.IO;
  40. using Google.Protobuf.Collections;
  41. using ProtobufUnittest;
  42. namespace Google.Protobuf
  43. {
  44. /// <summary>
  45. /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes
  46. /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details.
  47. /// </summary>
  48. public class JsonFormatterTest
  49. {
  50. [Test]
  51. public void DefaultValues_WhenOmitted()
  52. {
  53. var formatter = JsonFormatter.Default;
  54. AssertJson("{ }", formatter.Format(new ForeignMessage()));
  55. AssertJson("{ }", formatter.Format(new TestAllTypes()));
  56. AssertJson("{ }", formatter.Format(new TestMap()));
  57. }
  58. [Test]
  59. public void DefaultValues_WhenIncluded()
  60. {
  61. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  62. AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage()));
  63. }
  64. [Test]
  65. public void EnumAllowAlias()
  66. {
  67. var message = new TestEnumAllowAlias
  68. {
  69. Value = TestEnumWithDupValue.Foo2,
  70. };
  71. var actualText = JsonFormatter.Default.Format(message);
  72. var expectedText = "{ 'value': 'FOO1' }";
  73. AssertJson(expectedText, actualText);
  74. }
  75. [Test]
  76. public void EnumAsInt()
  77. {
  78. var message = new TestAllTypes
  79. {
  80. SingleForeignEnum = ForeignEnum.ForeignBar,
  81. RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo }
  82. };
  83. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatEnumsAsIntegers(true));
  84. var actualText = formatter.Format(message);
  85. var expectedText = "{ " +
  86. "'singleForeignEnum': 5, " +
  87. "'repeatedForeignEnum': [ 6, 100, 4 ]" +
  88. " }";
  89. AssertJson(expectedText, actualText);
  90. }
  91. [Test]
  92. public void AllSingleFields()
  93. {
  94. var message = new TestAllTypes
  95. {
  96. SingleBool = true,
  97. SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
  98. SingleDouble = 23.5,
  99. SingleFixed32 = 23,
  100. SingleFixed64 = 1234567890123,
  101. SingleFloat = 12.25f,
  102. SingleForeignEnum = ForeignEnum.ForeignBar,
  103. SingleForeignMessage = new ForeignMessage { C = 10 },
  104. SingleImportEnum = ImportEnum.ImportBaz,
  105. SingleImportMessage = new ImportMessage { D = 20 },
  106. SingleInt32 = 100,
  107. SingleInt64 = 3210987654321,
  108. SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
  109. SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
  110. SinglePublicImportMessage = new PublicImportMessage { E = 54 },
  111. SingleSfixed32 = -123,
  112. SingleSfixed64 = -12345678901234,
  113. SingleSint32 = -456,
  114. SingleSint64 = -12345678901235,
  115. SingleString = "test\twith\ttabs",
  116. SingleUint32 = uint.MaxValue,
  117. SingleUint64 = ulong.MaxValue,
  118. };
  119. var actualText = JsonFormatter.Default.Format(message);
  120. // Fields in numeric order
  121. var expectedText = "{ " +
  122. "'singleInt32': 100, " +
  123. "'singleInt64': '3210987654321', " +
  124. "'singleUint32': 4294967295, " +
  125. "'singleUint64': '18446744073709551615', " +
  126. "'singleSint32': -456, " +
  127. "'singleSint64': '-12345678901235', " +
  128. "'singleFixed32': 23, " +
  129. "'singleFixed64': '1234567890123', " +
  130. "'singleSfixed32': -123, " +
  131. "'singleSfixed64': '-12345678901234', " +
  132. "'singleFloat': 12.25, " +
  133. "'singleDouble': 23.5, " +
  134. "'singleBool': true, " +
  135. "'singleString': 'test\\twith\\ttabs', " +
  136. "'singleBytes': 'AQIDBA==', " +
  137. "'singleNestedMessage': { 'bb': 35 }, " +
  138. "'singleForeignMessage': { 'c': 10 }, " +
  139. "'singleImportMessage': { 'd': 20 }, " +
  140. "'singleNestedEnum': 'FOO', " +
  141. "'singleForeignEnum': 'FOREIGN_BAR', " +
  142. "'singleImportEnum': 'IMPORT_BAZ', " +
  143. "'singlePublicImportMessage': { 'e': 54 }" +
  144. " }";
  145. AssertJson(expectedText, actualText);
  146. }
  147. [Test]
  148. public void WithFormatDefaultValues_DoesNotAffectMessageFields()
  149. {
  150. var message = new TestAllTypes();
  151. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  152. var json = formatter.Format(message);
  153. Assert.IsFalse(json.Contains("\"singleNestedMessage\""));
  154. Assert.IsFalse(json.Contains("\"singleForeignMessage\""));
  155. Assert.IsFalse(json.Contains("\"singleImportMessage\""));
  156. }
  157. [Test]
  158. public void WithFormatDefaultValues_DoesNotAffectProto3OptionalFields()
  159. {
  160. var message = new TestProto3Optional();
  161. message.OptionalInt32 = 0;
  162. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  163. var json = formatter.Format(message);
  164. // The non-optional proto3 fields are formatted, as is the optional-but-specified field.
  165. AssertJson("{ 'optionalInt32': 0, 'singularInt32': 0, 'singularInt64': '0' }", json);
  166. }
  167. [Test]
  168. public void WithFormatDefaultValues_DoesNotAffectProto2Fields()
  169. {
  170. var message = new TestProtos.Proto2.ForeignMessage();
  171. message.C = 0;
  172. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  173. var json = formatter.Format(message);
  174. // The specified field is formatted, but the non-specified field (d) is not.
  175. AssertJson("{ 'c': 0 }", json);
  176. }
  177. [Test]
  178. public void WithFormatDefaultValues_DoesNotAffectOneofFields()
  179. {
  180. var message = new TestOneof();
  181. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  182. var json = formatter.Format(message);
  183. AssertJson("{ }", json);
  184. }
  185. [Test]
  186. public void RepeatedField()
  187. {
  188. AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }",
  189. JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } }));
  190. }
  191. [Test]
  192. public void MapField_StringString()
  193. {
  194. AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }",
  195. JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }));
  196. }
  197. [Test]
  198. public void MapField_Int32Int32()
  199. {
  200. // The keys are quoted, but the values aren't.
  201. AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }",
  202. JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }));
  203. }
  204. [Test]
  205. public void MapField_BoolBool()
  206. {
  207. // The keys are quoted, but the values aren't.
  208. AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }",
  209. JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } }));
  210. }
  211. [Test]
  212. public void NullValueOutsideStruct()
  213. {
  214. var message = new NullValueOutsideStruct { NullValue = NullValue.NullValue };
  215. AssertJson("{ 'nullValue': null }", JsonFormatter.Default.Format(message));
  216. }
  217. [Test]
  218. public void NullValueNotInOneof()
  219. {
  220. var message = new NullValueNotInOneof();
  221. AssertJson("{ }", JsonFormatter.Default.Format(message));
  222. }
  223. [Test]
  224. public void NullValueNotInOneof_FormatDefaults()
  225. {
  226. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  227. var message = new NullValueNotInOneof();
  228. AssertJson("{ 'nullValue': null }", formatter.Format(message));
  229. }
  230. [TestCase(1.0, "1")]
  231. [TestCase(double.NaN, "'NaN'")]
  232. [TestCase(double.PositiveInfinity, "'Infinity'")]
  233. [TestCase(double.NegativeInfinity, "'-Infinity'")]
  234. public void DoubleRepresentations(double value, string expectedValueText)
  235. {
  236. var message = new TestAllTypes { SingleDouble = value };
  237. string actualText = JsonFormatter.Default.Format(message);
  238. string expectedText = "{ 'singleDouble': " + expectedValueText + " }";
  239. AssertJson(expectedText, actualText);
  240. }
  241. [Test]
  242. public void UnknownEnumValueNumeric_SingleField()
  243. {
  244. var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 };
  245. AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message));
  246. }
  247. [Test]
  248. public void UnknownEnumValueNumeric_RepeatedField()
  249. {
  250. var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } };
  251. AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message));
  252. }
  253. [Test]
  254. public void UnknownEnumValueNumeric_MapField()
  255. {
  256. var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } };
  257. AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message));
  258. }
  259. [Test]
  260. public void UnknownEnumValue_RepeatedField_AllEntriesUnknown()
  261. {
  262. var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } };
  263. AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message));
  264. }
  265. [Test]
  266. [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit
  267. [TestCase("a\u0601b", "a\\u0601b")] // Ranged
  268. [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...)
  269. public void SimpleNonAscii(string text, string encoded)
  270. {
  271. var message = new TestAllTypes { SingleString = text };
  272. AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message));
  273. }
  274. [Test]
  275. public void SurrogatePairEscaping()
  276. {
  277. var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" };
  278. AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message));
  279. }
  280. [Test]
  281. public void InvalidSurrogatePairsFail()
  282. {
  283. // Note: don't use TestCase for these, as the strings can't be reliably represented
  284. // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/
  285. // Lone low surrogate
  286. var message = new TestAllTypes { SingleString = "a\uDC01b" };
  287. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  288. // Lone high surrogate
  289. message = new TestAllTypes { SingleString = "a\uD801b" };
  290. Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
  291. }
  292. [Test]
  293. [TestCase("foo_bar", "fooBar")]
  294. [TestCase("bananaBanana", "bananaBanana")]
  295. [TestCase("BANANABanana", "BANANABanana")]
  296. [TestCase("simple", "simple")]
  297. [TestCase("ACTION_AND_ADVENTURE", "ACTIONANDADVENTURE")]
  298. [TestCase("action_and_adventure", "actionAndAdventure")]
  299. [TestCase("kFoo", "kFoo")]
  300. [TestCase("HTTPServer", "HTTPServer")]
  301. [TestCase("CLIENT", "CLIENT")]
  302. public void ToJsonName(string original, string expected)
  303. {
  304. Assert.AreEqual(expected, JsonFormatter.ToJsonName(original));
  305. }
  306. [Test]
  307. [TestCase(null, "{ }")]
  308. [TestCase("x", "{ 'fooString': 'x' }")]
  309. [TestCase("", "{ 'fooString': '' }")]
  310. public void Oneof(string fooStringValue, string expectedJson)
  311. {
  312. var message = new TestOneof();
  313. if (fooStringValue != null)
  314. {
  315. message.FooString = fooStringValue;
  316. }
  317. // We should get the same result both with and without "format default values".
  318. var formatter = JsonFormatter.Default;
  319. AssertJson(expectedJson, formatter.Format(message));
  320. formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  321. AssertJson(expectedJson, formatter.Format(message));
  322. }
  323. [Test]
  324. public void WrapperFormatting_Single()
  325. {
  326. // Just a few examples, handling both classes and value types, and
  327. // default vs non-default values
  328. var message = new TestWellKnownTypes
  329. {
  330. Int64Field = 10,
  331. Int32Field = 0,
  332. BytesField = ByteString.FromBase64("ABCD"),
  333. StringField = ""
  334. };
  335. var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }";
  336. AssertJson(expectedJson, JsonFormatter.Default.Format(message));
  337. }
  338. [Test]
  339. public void WrapperFormatting_Message()
  340. {
  341. Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue()));
  342. Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value()));
  343. }
  344. [Test]
  345. public void WrapperFormatting_FormatDefaultValuesDoesNotFormatNull()
  346. {
  347. // The actual JSON here is very large because there are lots of fields. Just test a couple of them.
  348. var message = new TestWellKnownTypes { Int32Field = 10 };
  349. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  350. var actualJson = formatter.Format(message);
  351. // This *used* to include "int64Field": null, but that was a bug.
  352. // WithDefaultValues should not affect message fields, including wrapper types.
  353. Assert.IsFalse(actualJson.Contains("\"int64Field\": null"));
  354. Assert.IsTrue(actualJson.Contains("\"int32Field\": 10"));
  355. }
  356. [Test]
  357. public void OutputIsInNumericFieldOrder_NoDefaults()
  358. {
  359. var formatter = JsonFormatter.Default;
  360. var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 };
  361. AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message));
  362. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  363. AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
  364. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  365. AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
  366. }
  367. [Test]
  368. public void OutputIsInNumericFieldOrder_WithDefaults()
  369. {
  370. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithFormatDefaultValues(true));
  371. var message = new TestJsonFieldOrdering();
  372. AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message));
  373. message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
  374. AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
  375. message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
  376. AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
  377. }
  378. [Test]
  379. [TestCase("1970-01-01T00:00:00Z", 0)]
  380. [TestCase("1970-01-01T00:00:00.000000001Z", 1)]
  381. [TestCase("1970-01-01T00:00:00.000000010Z", 10)]
  382. [TestCase("1970-01-01T00:00:00.000000100Z", 100)]
  383. [TestCase("1970-01-01T00:00:00.000001Z", 1000)]
  384. [TestCase("1970-01-01T00:00:00.000010Z", 10000)]
  385. [TestCase("1970-01-01T00:00:00.000100Z", 100000)]
  386. [TestCase("1970-01-01T00:00:00.001Z", 1000000)]
  387. [TestCase("1970-01-01T00:00:00.010Z", 10000000)]
  388. [TestCase("1970-01-01T00:00:00.100Z", 100000000)]
  389. [TestCase("1970-01-01T00:00:00.120Z", 120000000)]
  390. [TestCase("1970-01-01T00:00:00.123Z", 123000000)]
  391. [TestCase("1970-01-01T00:00:00.123400Z", 123400000)]
  392. [TestCase("1970-01-01T00:00:00.123450Z", 123450000)]
  393. [TestCase("1970-01-01T00:00:00.123456Z", 123456000)]
  394. [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)]
  395. [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)]
  396. [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)]
  397. public void TimestampStandalone(string expected, int nanos)
  398. {
  399. Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString());
  400. }
  401. [Test]
  402. public void TimestampStandalone_FromDateTime()
  403. {
  404. // One before and one after the Unix epoch, more easily represented via DateTime.
  405. Assert.AreEqual("\"1673-06-19T12:34:56Z\"",
  406. new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString());
  407. Assert.AreEqual("\"2015-07-31T10:29:34Z\"",
  408. new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString());
  409. }
  410. [Test]
  411. [TestCase(-1, -1)] // Would be valid as duration
  412. [TestCase(1, Timestamp.MaxNanos + 1)]
  413. [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)]
  414. [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)]
  415. public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds)
  416. {
  417. var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds };
  418. Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp));
  419. }
  420. [Test]
  421. public void TimestampField()
  422. {
  423. var message = new TestWellKnownTypes { TimestampField = new Timestamp() };
  424. AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message));
  425. }
  426. [Test]
  427. [TestCase(0, 0, "0s")]
  428. [TestCase(1, 0, "1s")]
  429. [TestCase(-1, 0, "-1s")]
  430. [TestCase(0, 1, "0.000000001s")]
  431. [TestCase(0, 10, "0.000000010s")]
  432. [TestCase(0, 100, "0.000000100s")]
  433. [TestCase(0, 1000, "0.000001s")]
  434. [TestCase(0, 10000, "0.000010s")]
  435. [TestCase(0, 100000, "0.000100s")]
  436. [TestCase(0, 1000000, "0.001s")]
  437. [TestCase(0, 10000000, "0.010s")]
  438. [TestCase(0, 100000000, "0.100s")]
  439. [TestCase(0, 120000000, "0.120s")]
  440. [TestCase(0, 123000000, "0.123s")]
  441. [TestCase(0, 123400000, "0.123400s")]
  442. [TestCase(0, 123450000, "0.123450s")]
  443. [TestCase(0, 123456000, "0.123456s")]
  444. [TestCase(0, 123456700, "0.123456700s")]
  445. [TestCase(0, 123456780, "0.123456780s")]
  446. [TestCase(0, 123456789, "0.123456789s")]
  447. [TestCase(0, -100000000, "-0.100s")]
  448. [TestCase(1, 100000000, "1.100s")]
  449. [TestCase(-1, -100000000, "-1.100s")]
  450. public void DurationStandalone(long seconds, int nanoseconds, string expected)
  451. {
  452. var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds });
  453. Assert.AreEqual(WrapInQuotes(expected), json);
  454. }
  455. [Test]
  456. [TestCase(1, 2123456789)]
  457. [TestCase(1, -100000000)]
  458. public void DurationStandalone_NonNormalized(long seconds, int nanoseconds)
  459. {
  460. var duration = new Duration { Seconds = seconds, Nanos = nanoseconds };
  461. Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration));
  462. }
  463. [Test]
  464. public void DurationField()
  465. {
  466. var message = new TestWellKnownTypes { DurationField = new Duration() };
  467. AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message));
  468. }
  469. [Test]
  470. public void StructSample()
  471. {
  472. var message = new Struct
  473. {
  474. Fields =
  475. {
  476. { "a", Value.ForNull() },
  477. { "b", Value.ForBool(false) },
  478. { "c", Value.ForNumber(10.5) },
  479. { "d", Value.ForString("text") },
  480. { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) },
  481. { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) }
  482. }
  483. };
  484. AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString());
  485. }
  486. [Test]
  487. [TestCase("foo__bar")]
  488. [TestCase("foo_3_ar")]
  489. [TestCase("fooBar")]
  490. public void FieldMaskInvalid(string input)
  491. {
  492. var mask = new FieldMask { Paths = { input } };
  493. Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask));
  494. }
  495. [Test]
  496. public void FieldMaskStandalone()
  497. {
  498. var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } };
  499. Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString());
  500. // Invalid, but we shouldn't create broken JSON...
  501. fieldMask = new FieldMask { Paths = { "x\\y" } };
  502. Assert.AreEqual(@"""x\\y""", fieldMask.ToString());
  503. }
  504. [Test]
  505. public void FieldMaskField()
  506. {
  507. var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } };
  508. AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message));
  509. }
  510. // SourceContext is an example of a well-known type with no special JSON handling
  511. [Test]
  512. public void SourceContextStandalone()
  513. {
  514. var message = new SourceContext { FileName = "foo.proto" };
  515. AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message));
  516. }
  517. [Test]
  518. public void AnyWellKnownType()
  519. {
  520. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(Timestamp.Descriptor)));
  521. var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
  522. var any = Any.Pack(timestamp);
  523. AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any));
  524. }
  525. [Test]
  526. public void AnyMessageType()
  527. {
  528. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
  529. var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
  530. var any = Any.Pack(message);
  531. AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
  532. }
  533. [Test]
  534. public void AnyMessageType_CustomPrefix()
  535. {
  536. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
  537. var message = new TestAllTypes { SingleInt32 = 10 };
  538. var any = Any.Pack(message, "foo.bar/baz");
  539. AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest3.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any));
  540. }
  541. [Test]
  542. public void AnyNested()
  543. {
  544. var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
  545. var formatter = new JsonFormatter(JsonFormatter.Settings.Default.WithTypeRegistry(registry));
  546. // Nest an Any as the value of an Any.
  547. var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
  548. var nestedMessage = Any.Pack(doubleNestedMessage);
  549. var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
  550. AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest3.TestAllTypes', 'singleInt32': 20 } } }",
  551. formatter.Format(message));
  552. }
  553. [Test]
  554. public void AnyUnknownType()
  555. {
  556. // The default type registry doesn't have any types in it.
  557. var message = new TestAllTypes();
  558. var any = Any.Pack(message);
  559. Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any));
  560. }
  561. [Test]
  562. [TestCase(typeof(BoolValue), true, "true")]
  563. [TestCase(typeof(Int32Value), 32, "32")]
  564. [TestCase(typeof(Int64Value), 32L, "\"32\"")]
  565. [TestCase(typeof(UInt32Value), 32U, "32")]
  566. [TestCase(typeof(UInt64Value), 32UL, "\"32\"")]
  567. [TestCase(typeof(StringValue), "foo", "\"foo\"")]
  568. [TestCase(typeof(FloatValue), 1.5f, "1.5")]
  569. [TestCase(typeof(DoubleValue), 1.5d, "1.5")]
  570. public void Wrappers_Standalone(System.Type wrapperType, object value, string expectedJson)
  571. {
  572. IMessage populated = (IMessage)Activator.CreateInstance(wrapperType);
  573. populated.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(populated, value);
  574. Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(populated));
  575. }
  576. // Sanity tests for WriteValue. Not particularly comprehensive, as it's all covered above already,
  577. // as FormatMessage uses WriteValue.
  578. [TestCase(null, "null")]
  579. [TestCase(1, "1")]
  580. [TestCase(1L, "'1'")]
  581. [TestCase(0.5f, "0.5")]
  582. [TestCase(0.5d, "0.5")]
  583. [TestCase("text", "'text'")]
  584. [TestCase("x\ny", @"'x\ny'")]
  585. [TestCase(ForeignEnum.ForeignBar, "'FOREIGN_BAR'")]
  586. public void WriteValue_Constant(object value, string expectedJson)
  587. {
  588. AssertWriteValue(value, expectedJson);
  589. }
  590. [Test]
  591. public void WriteValue_Timestamp()
  592. {
  593. var value = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
  594. AssertWriteValue(value, "'1673-06-19T12:34:56Z'");
  595. }
  596. [Test]
  597. public void WriteValue_Message()
  598. {
  599. var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L };
  600. AssertWriteValue(value, "{ 'singleInt32': 100, 'singleInt64': '3210987654321' }");
  601. }
  602. [Test]
  603. public void WriteValue_List()
  604. {
  605. var value = new RepeatedField<int> { 1, 2, 3 };
  606. AssertWriteValue(value, "[ 1, 2, 3 ]");
  607. }
  608. [Test]
  609. public void Proto2_DefaultValuesWritten()
  610. {
  611. var value = new ProtobufTestMessages.Proto2.TestAllTypesProto2() { FieldName13 = 0 };
  612. AssertWriteValue(value, "{ 'FieldName13': 0 }");
  613. }
  614. private static void AssertWriteValue(object value, string expectedJson)
  615. {
  616. var writer = new StringWriter();
  617. JsonFormatter.Default.WriteValue(writer, value);
  618. string actual = writer.ToString();
  619. AssertJson(expectedJson, actual);
  620. }
  621. /// <summary>
  622. /// Checks that the actual JSON is the same as the expected JSON - but after replacing
  623. /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier
  624. /// to read.
  625. /// </summary>
  626. private static void AssertJson(string expectedJsonWithApostrophes, string actualJson)
  627. {
  628. var expectedJson = expectedJsonWithApostrophes.Replace("'", "\"");
  629. Assert.AreEqual(expectedJson, actualJson);
  630. }
  631. }
  632. }