JsonFormatterTest.cs 23 KB

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