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