JsonFormatterTest.cs 27 KB

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