JsonFormatterTest.cs 26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
36
using UnitTest.Issues.TestProtos;
37
using Google.Protobuf.WellKnownTypes;
Jon Skeet's avatar
Jon Skeet committed
38
using Google.Protobuf.Reflection;
39

40
using static Google.Protobuf.JsonParserTest; // For WrapInQuotes
41 42
using System.IO;
using Google.Protobuf.Collections;
43

44 45
namespace Google.Protobuf
{
46 47 48 49
    /// <summary>
    /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes
    /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details.
    /// </summary>
50 51 52 53 54 55 56
    public class JsonFormatterTest
    {
        [Test]
        public void DefaultValues_WhenOmitted()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: false));

57 58 59
            AssertJson("{ }", formatter.Format(new ForeignMessage()));
            AssertJson("{ }", formatter.Format(new TestAllTypes()));
            AssertJson("{ }", formatter.Format(new TestMap()));
60 61 62 63 64 65
        }

        [Test]
        public void DefaultValues_WhenIncluded()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: true));
66
            AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage()));
67 68 69 70 71 72 73 74 75 76 77 78 79
        }

        [Test]
        public void AllSingleFields()
        {
            var message = new TestAllTypes
            {
                SingleBool = true,
                SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
                SingleDouble = 23.5,
                SingleFixed32 = 23,
                SingleFixed64 = 1234567890123,
                SingleFloat = 12.25f,
80
                SingleForeignEnum = ForeignEnum.ForeignBar,
81
                SingleForeignMessage = new ForeignMessage { C = 10 },
82
                SingleImportEnum = ImportEnum.ImportBaz,
83 84 85
                SingleImportMessage = new ImportMessage { D = 20 },
                SingleInt32 = 100,
                SingleInt64 = 3210987654321,
86
                SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
87 88 89 90 91 92 93 94 95 96 97 98
                SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
                SinglePublicImportMessage = new PublicImportMessage { E = 54 },
                SingleSfixed32 = -123,
                SingleSfixed64 = -12345678901234,
                SingleSint32 = -456,
                SingleSint64 = -12345678901235,
                SingleString = "test\twith\ttabs",
                SingleUint32 = uint.MaxValue,
                SingleUint64 = ulong.MaxValue,
            };
            var actualText = JsonFormatter.Default.Format(message);

99
            // Fields in numeric order
100
            var expectedText = "{ " +
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                "'singleInt32': 100, " +
                "'singleInt64': '3210987654321', " +
                "'singleUint32': 4294967295, " +
                "'singleUint64': '18446744073709551615', " +
                "'singleSint32': -456, " +
                "'singleSint64': '-12345678901235', " +
                "'singleFixed32': 23, " +
                "'singleFixed64': '1234567890123', " +
                "'singleSfixed32': -123, " +
                "'singleSfixed64': '-12345678901234', " +
                "'singleFloat': 12.25, " +
                "'singleDouble': 23.5, " +
                "'singleBool': true, " +
                "'singleString': 'test\\twith\\ttabs', " +
                "'singleBytes': 'AQIDBA==', " +
                "'singleNestedMessage': { 'bb': 35 }, " +
                "'singleForeignMessage': { 'c': 10 }, " +
                "'singleImportMessage': { 'd': 20 }, " +
                "'singleNestedEnum': 'FOO', " +
                "'singleForeignEnum': 'FOREIGN_BAR', " +
                "'singleImportEnum': 'IMPORT_BAZ', " +
                "'singlePublicImportMessage': { 'e': 54 }" +
123
                " }";
124
            AssertJson(expectedText, actualText);
125 126 127 128 129
        }

        [Test]
        public void RepeatedField()
        {
130
            AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }",
131 132 133 134 135 136
                JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } }));
        }

        [Test]
        public void MapField_StringString()
        {
137
            AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }",
138 139 140 141 142 143 144
                JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }));
        }

        [Test]
        public void MapField_Int32Int32()
        {
            // The keys are quoted, but the values aren't.
145
            AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }",
146 147 148 149 150 151 152
                JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }));
        }

        [Test]
        public void MapField_BoolBool()
        {
            // The keys are quoted, but the values aren't.
153
            AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }",
154 155 156 157
                JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } }));
        }

        [TestCase(1.0, "1")]
158 159 160
        [TestCase(double.NaN, "'NaN'")]
        [TestCase(double.PositiveInfinity, "'Infinity'")]
        [TestCase(double.NegativeInfinity, "'-Infinity'")]
161 162 163 164
        public void DoubleRepresentations(double value, string expectedValueText)
        {
            var message = new TestAllTypes { SingleDouble = value };
            string actualText = JsonFormatter.Default.Format(message);
165 166
            string expectedText = "{ 'singleDouble': " + expectedValueText + " }";
            AssertJson(expectedText, actualText);
167 168 169
        }

        [Test]
170
        public void UnknownEnumValueNumeric_SingleField()
171 172
        {
            var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 };
173
            AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message));
Jon Skeet's avatar
Jon Skeet committed
174 175 176
        }

        [Test]
177
        public void UnknownEnumValueNumeric_RepeatedField()
Jon Skeet's avatar
Jon Skeet committed
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));
Jon Skeet's avatar
Jon Skeet committed
181 182 183
        }

        [Test]
184
        public void UnknownEnumValueNumeric_MapField()
Jon Skeet's avatar
Jon Skeet committed
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));
Jon Skeet's avatar
Jon Skeet committed
188 189 190
        }

        [Test]
191
        public void UnknownEnumValue_RepeatedField_AllEntriesUnknown()
Jon Skeet's avatar
Jon Skeet committed
192 193
        {
            var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } };
194
            AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message));
195 196 197 198 199 200 201 202 203
        }

        [Test]
        [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit
        [TestCase("a\u0601b", "a\\u0601b")] // Ranged
        [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...)
        public void SimpleNonAscii(string text, string encoded)
        {
            var message = new TestAllTypes { SingleString = text };
204
            AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message));
205 206 207 208 209 210
        }

        [Test]
        public void SurrogatePairEscaping()
        {
            var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" };
211
            AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message));
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        }

        [Test]
        public void InvalidSurrogatePairsFail()
        {
            // Note: don't use TestCase for these, as the strings can't be reliably represented 
            // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/

            // Lone low surrogate
            var message = new TestAllTypes { SingleString = "a\uDC01b" };
            Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));

            // Lone high surrogate
            message = new TestAllTypes { SingleString = "a\uD801b" };
            Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
        }

        [Test]
        [TestCase("foo_bar", "fooBar")]
        [TestCase("bananaBanana", "bananaBanana")]
        [TestCase("BANANABanana", "bananaBanana")]
        public void ToCamelCase(string original, string expected)
        {
            Assert.AreEqual(expected, JsonFormatter.ToCamelCase(original));
        }
Jon Skeet's avatar
Jon Skeet committed
237 238 239

        [Test]
        [TestCase(null, "{ }")]
240 241
        [TestCase("x", "{ 'fooString': 'x' }")]
        [TestCase("", "{ 'fooString': '' }")]
Jon Skeet's avatar
Jon Skeet committed
242 243 244 245 246 247 248 249 250 251
        public void Oneof(string fooStringValue, string expectedJson)
        {
            var message = new TestOneof();
            if (fooStringValue != null)
            {
                message.FooString = fooStringValue;
            }

            // We should get the same result both with and without "format default values".
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
252
            AssertJson(expectedJson, formatter.Format(message));
Jon Skeet's avatar
Jon Skeet committed
253
            formatter = new JsonFormatter(new JsonFormatter.Settings(true));
254
            AssertJson(expectedJson, formatter.Format(message));
Jon Skeet's avatar
Jon Skeet committed
255
        }
256 257 258 259 260 261 262 263 264 265 266 267 268

        [Test]
        public void WrapperFormatting_Single()
        {
            // Just a few examples, handling both classes and value types, and
            // default vs non-default values
            var message = new TestWellKnownTypes
            {
                Int64Field = 10,
                Int32Field = 0,
                BytesField = ByteString.FromBase64("ABCD"),
                StringField = ""
            };
269 270
            var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }";
            AssertJson(expectedJson, JsonFormatter.Default.Format(message));
271 272
        }

273 274 275 276 277 278 279
        [Test]
        public void WrapperFormatting_Message()
        {
            Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue()));
            Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value()));
        }

280 281 282 283 284 285 286 287 288 289
        [Test]
        public void WrapperFormatting_IncludeNull()
        {
            // The actual JSON here is very large because there are lots of fields. Just test a couple of them.
            var message = new TestWellKnownTypes { Int32Field = 10 };
            var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
            var actualJson = formatter.Format(message);
            Assert.IsTrue(actualJson.Contains("\"int64Field\": null"));
            Assert.IsFalse(actualJson.Contains("\"int32Field\": null"));
        }
290 291 292 293 294 295

        [Test]
        public void OutputIsInNumericFieldOrder_NoDefaults()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
            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 304 305 306 307
        }

        [Test]
        public void OutputIsInNumericFieldOrder_WithDefaults()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
            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 313 314
            AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
        }

315
        [Test]
316
        [TestCase("1970-01-01T00:00:00Z", 0)]
317 318 319 320 321 322 323 324 325
        [TestCase("1970-01-01T00:00:00.000000001Z", 1)]
        [TestCase("1970-01-01T00:00:00.000000010Z", 10)]
        [TestCase("1970-01-01T00:00:00.000000100Z", 100)]
        [TestCase("1970-01-01T00:00:00.000001Z", 1000)]
        [TestCase("1970-01-01T00:00:00.000010Z", 10000)]
        [TestCase("1970-01-01T00:00:00.000100Z", 100000)]
        [TestCase("1970-01-01T00:00:00.001Z", 1000000)]
        [TestCase("1970-01-01T00:00:00.010Z", 10000000)]
        [TestCase("1970-01-01T00:00:00.100Z", 100000000)]
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        [TestCase("1970-01-01T00:00:00.120Z", 120000000)]
        [TestCase("1970-01-01T00:00:00.123Z", 123000000)]
        [TestCase("1970-01-01T00:00:00.123400Z", 123400000)]
        [TestCase("1970-01-01T00:00:00.123450Z", 123450000)]
        [TestCase("1970-01-01T00:00:00.123456Z", 123456000)]
        [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)]
        [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)]
        [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)]
        public void TimestampStandalone(string expected, int nanos)
        {
            Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString());
        }

        [Test]
        public void TimestampStandalone_FromDateTime()
341
        {
342 343
            // One before and one after the Unix epoch, more easily represented via DateTime.
            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 347 348
                new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString());
        }

349 350 351 352 353 354 355 356 357 358 359
        [Test]
        [TestCase(-1, -1)] // Would be valid as duration
        [TestCase(1, Timestamp.MaxNanos + 1)]
        [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)]
        [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)]
        public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds)
        {
            var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds };
            Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp));
        }

360 361 362 363 364 365 366 367 368 369 370
        [Test]
        public void TimestampField()
        {
            var message = new TestWellKnownTypes { TimestampField = new Timestamp() };
            AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message));
        }

        [Test]
        [TestCase(0, 0, "0s")]
        [TestCase(1, 0, "1s")]
        [TestCase(-1, 0, "-1s")]
371 372 373 374 375 376 377 378
        [TestCase(0, 1, "0.000000001s")]
        [TestCase(0, 10, "0.000000010s")]
        [TestCase(0, 100, "0.000000100s")]
        [TestCase(0, 1000, "0.000001s")]
        [TestCase(0, 10000, "0.000010s")]
        [TestCase(0, 100000, "0.000100s")]
        [TestCase(0, 1000000, "0.001s")]
        [TestCase(0, 10000000, "0.010s")]
379 380 381 382 383 384 385 386 387 388 389 390 391 392
        [TestCase(0, 100000000, "0.100s")]
        [TestCase(0, 120000000, "0.120s")]
        [TestCase(0, 123000000, "0.123s")]
        [TestCase(0, 123400000, "0.123400s")]
        [TestCase(0, 123450000, "0.123450s")]
        [TestCase(0, 123456000, "0.123456s")]
        [TestCase(0, 123456700, "0.123456700s")]
        [TestCase(0, 123456780, "0.123456780s")]
        [TestCase(0, 123456789, "0.123456789s")]
        [TestCase(0, -100000000, "-0.100s")]
        [TestCase(1, 100000000, "1.100s")]
        [TestCase(-1, -100000000, "-1.100s")]
        public void DurationStandalone(long seconds, int nanoseconds, string expected)
        {
393 394
            var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds });
            Assert.AreEqual(WrapInQuotes(expected), json);
395 396
        }

397 398 399
        [Test]
        [TestCase(1, 2123456789)]
        [TestCase(1, -100000000)]
Jon Skeet's avatar
Jon Skeet committed
400
        public void DurationStandalone_NonNormalized(long seconds, int nanoseconds)
401
        {
402 403
            var duration = new Duration { Seconds = seconds, Nanos = nanoseconds };
            Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration));
404 405
        }

406 407 408 409 410
        [Test]
        public void DurationField()
        {
            var message = new TestWellKnownTypes { DurationField = new Duration() };
            AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message));
411
        }
412

413 414 415 416 417 418 419
        [Test]
        public void StructSample()
        {
            var message = new Struct
            {
                Fields =
                {
420 421 422 423 424 425
                    { "a", Value.ForNull() },
                    { "b", Value.ForBool(false) },
                    { "c", Value.ForNumber(10.5) },
                    { "d", Value.ForString("text") },
                    { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) },
                    { "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 432 433 434 435 436 437 438 439 440
        [Test]
        [TestCase("foo__bar")]
        [TestCase("foo_3_ar")]
        [TestCase("fooBar")]
        public void FieldMaskInvalid(string input)
        {
            var mask = new FieldMask { Paths = { input } };
            Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask));
        }

441 442 443 444
        [Test]
        public void FieldMaskStandalone()
        {
            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 448

            // Invalid, but we shouldn't create broken JSON...
            fieldMask = new FieldMask { Paths = { "x\\y" } };
449
            Assert.AreEqual(@"""x\\y""", fieldMask.ToString());
450 451 452 453 454 455 456 457 458
        }

        [Test]
        public void FieldMaskField()
        {
            var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } };
            AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message));
        }

459 460 461 462 463 464 465 466
        // SourceContext is an example of a well-known type with no special JSON handling
        [Test]
        public void SourceContextStandalone()
        {
            var message = new SourceContext { FileName = "foo.proto" };
            AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message));
        }

Jon Skeet's avatar
Jon Skeet committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        [Test]
        public void AnyWellKnownType()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(Timestamp.Descriptor)));
            var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
            var any = Any.Pack(timestamp);
            AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any));
        }

        [Test]
        public void AnyMessageType()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
            var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
            var any = Any.Pack(message);
            AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
        }

485 486 487 488 489 490 491 492 493
        [Test]
        public void AnyMessageType_CustomPrefix()
        {
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
            var message = new TestAllTypes { SingleInt32 = 10 };
            var any = Any.Pack(message, "foo.bar/baz");
            AssertJson("{ '@type': 'foo.bar/baz/protobuf_unittest.TestAllTypes', 'singleInt32': 10 }", formatter.Format(any));
        }

Jon Skeet's avatar
Jon Skeet committed
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        [Test]
        public void AnyNested()
        {
            var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
            var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));

            // Nest an Any as the value of an Any.
            var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
            var nestedMessage = Any.Pack(doubleNestedMessage);
            var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
            AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 20 } } }",
                formatter.Format(message));
        }

        [Test]
        public void AnyUnknownType()
        {
            // The default type registry doesn't have any types in it.
            var message = new TestAllTypes();
            var any = Any.Pack(message);
            Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any));
        }

517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
        [Test]
        [TestCase(typeof(BoolValue), true, "true")]
        [TestCase(typeof(Int32Value), 32, "32")]
        [TestCase(typeof(Int64Value), 32L, "\"32\"")]
        [TestCase(typeof(UInt32Value), 32U, "32")]
        [TestCase(typeof(UInt64Value), 32UL, "\"32\"")]
        [TestCase(typeof(StringValue), "foo", "\"foo\"")]
        [TestCase(typeof(FloatValue), 1.5f, "1.5")]
        [TestCase(typeof(DoubleValue), 1.5d, "1.5")]
        public void Wrappers_Standalone(System.Type wrapperType, object value, string expectedJson)
        {
            IMessage populated = (IMessage)Activator.CreateInstance(wrapperType);
            populated.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.SetValue(populated, value);
            Assert.AreEqual(expectedJson, JsonFormatter.Default.Format(populated));
        }

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
        // Sanity tests for WriteValue. Not particularly comprehensive, as it's all covered above already,
        // as FormatMessage uses WriteValue.

        [TestCase(null, "null")]
        [TestCase(1, "1")]
        [TestCase(1L, "'1'")]
        [TestCase(0.5f, "0.5")]
        [TestCase(0.5d, "0.5")]
        [TestCase("text", "'text'")]
        [TestCase("x\ny", @"'x\ny'")]
        [TestCase(ForeignEnum.ForeignBar, "'FOREIGN_BAR'")]
        public void WriteValue_Constant(object value, string expectedJson)
        {
            AssertWriteValue(value, expectedJson);
        }

        [Test]
        public void WriteValue_Timestamp()
        {
            var value = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
            AssertWriteValue(value, "'1673-06-19T12:34:56Z'");
        }

        [Test]
        public void WriteValue_Message()
        {
            var value = new TestAllTypes { SingleInt32 = 100, SingleInt64 = 3210987654321L };
            AssertWriteValue(value, "{ 'singleInt32': 100, 'singleInt64': '3210987654321' }");
        }

        [Test]
        public void WriteValue_List()
        {
            var value = new RepeatedField<int> { 1, 2, 3 };
            AssertWriteValue(value, "[ 1, 2, 3 ]");
        }

        private static void AssertWriteValue(object value, string expectedJson)
        {
            var writer = new StringWriter();
            JsonFormatter.Default.WriteValue(writer, value);
            string actual = writer.ToString();
            AssertJson(expectedJson, actual);
        }

578 579 580 581 582 583 584 585 586
        /// <summary>
        /// Checks that the actual JSON is the same as the expected JSON - but after replacing
        /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier
        /// to read.
        /// </summary>
        private static void AssertJson(string expectedJsonWithApostrophes, string actualJson)
        {
            var expectedJson = expectedJsonWithApostrophes.Replace("'", "\"");
            Assert.AreEqual(expectedJson, actualJson);
587
        }
588 589
    }
}