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