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