blob: 0b6cd7e6e6a93e3a8f555cb089e09023e32d73a7 [file] [log] [blame]
Jon Skeetf8c151f2015-07-03 11:56:29 +01001#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;
Jon Skeetf8c151f2015-07-03 11:56:29 +010034using Google.Protobuf.TestProtos;
35using NUnit.Framework;
Jon Skeet4fed0b52015-07-31 10:33:31 +010036using UnitTest.Issues.TestProtos;
Jon Skeet16e272e2015-07-31 13:22:15 +010037using Google.Protobuf.WellKnownTypes;
Jon Skeet567579b2015-11-23 12:43:54 +000038using Google.Protobuf.Reflection;
Jon Skeetf8c151f2015-07-03 11:56:29 +010039
Jon Skeetb4a58172016-01-06 12:05:31 +000040using static Google.Protobuf.JsonParserTest; // For WrapInQuotes
41
Jon Skeetf8c151f2015-07-03 11:56:29 +010042namespace Google.Protobuf
43{
Jon Skeet6cf5f662015-07-31 10:44:59 +010044 /// <summary>
45 /// Tests for the JSON formatter. Note that in these tests, double quotes are replaced with apostrophes
46 /// for the sake of readability (embedding \" everywhere is painful). See the AssertJson method for details.
47 /// </summary>
Jon Skeetf8c151f2015-07-03 11:56:29 +010048 public class JsonFormatterTest
49 {
50 [Test]
51 public void DefaultValues_WhenOmitted()
52 {
53 var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: false));
54
Jon Skeet6cf5f662015-07-31 10:44:59 +010055 AssertJson("{ }", formatter.Format(new ForeignMessage()));
56 AssertJson("{ }", formatter.Format(new TestAllTypes()));
57 AssertJson("{ }", formatter.Format(new TestMap()));
Jon Skeetf8c151f2015-07-03 11:56:29 +010058 }
59
60 [Test]
61 public void DefaultValues_WhenIncluded()
62 {
63 var formatter = new JsonFormatter(new JsonFormatter.Settings(formatDefaultValues: true));
Jon Skeet6cf5f662015-07-31 10:44:59 +010064 AssertJson("{ 'c': 0 }", formatter.Format(new ForeignMessage()));
Jon Skeetf8c151f2015-07-03 11:56:29 +010065 }
66
67 [Test]
68 public void AllSingleFields()
69 {
70 var message = new TestAllTypes
71 {
72 SingleBool = true,
73 SingleBytes = ByteString.CopyFrom(1, 2, 3, 4),
74 SingleDouble = 23.5,
75 SingleFixed32 = 23,
76 SingleFixed64 = 1234567890123,
77 SingleFloat = 12.25f,
Jon Skeet84ea2c72016-04-08 12:33:09 +010078 SingleForeignEnum = ForeignEnum.ForeignBar,
Jon Skeetf8c151f2015-07-03 11:56:29 +010079 SingleForeignMessage = new ForeignMessage { C = 10 },
Jon Skeet84ea2c72016-04-08 12:33:09 +010080 SingleImportEnum = ImportEnum.ImportBaz,
Jon Skeetf8c151f2015-07-03 11:56:29 +010081 SingleImportMessage = new ImportMessage { D = 20 },
82 SingleInt32 = 100,
83 SingleInt64 = 3210987654321,
Jon Skeet84ea2c72016-04-08 12:33:09 +010084 SingleNestedEnum = TestAllTypes.Types.NestedEnum.Foo,
Jon Skeetf8c151f2015-07-03 11:56:29 +010085 SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
86 SinglePublicImportMessage = new PublicImportMessage { E = 54 },
87 SingleSfixed32 = -123,
88 SingleSfixed64 = -12345678901234,
89 SingleSint32 = -456,
90 SingleSint64 = -12345678901235,
91 SingleString = "test\twith\ttabs",
92 SingleUint32 = uint.MaxValue,
93 SingleUint64 = ulong.MaxValue,
94 };
95 var actualText = JsonFormatter.Default.Format(message);
96
Jon Skeet6cf5f662015-07-31 10:44:59 +010097 // Fields in numeric order
Jon Skeetf8c151f2015-07-03 11:56:29 +010098 var expectedText = "{ " +
Jon Skeet6cf5f662015-07-31 10:44:59 +010099 "'singleInt32': 100, " +
100 "'singleInt64': '3210987654321', " +
101 "'singleUint32': 4294967295, " +
102 "'singleUint64': '18446744073709551615', " +
103 "'singleSint32': -456, " +
104 "'singleSint64': '-12345678901235', " +
105 "'singleFixed32': 23, " +
106 "'singleFixed64': '1234567890123', " +
107 "'singleSfixed32': -123, " +
108 "'singleSfixed64': '-12345678901234', " +
109 "'singleFloat': 12.25, " +
110 "'singleDouble': 23.5, " +
111 "'singleBool': true, " +
112 "'singleString': 'test\\twith\\ttabs', " +
113 "'singleBytes': 'AQIDBA==', " +
114 "'singleNestedMessage': { 'bb': 35 }, " +
115 "'singleForeignMessage': { 'c': 10 }, " +
116 "'singleImportMessage': { 'd': 20 }, " +
117 "'singleNestedEnum': 'FOO', " +
118 "'singleForeignEnum': 'FOREIGN_BAR', " +
119 "'singleImportEnum': 'IMPORT_BAZ', " +
120 "'singlePublicImportMessage': { 'e': 54 }" +
Jon Skeetf8c151f2015-07-03 11:56:29 +0100121 " }";
Jon Skeet6cf5f662015-07-31 10:44:59 +0100122 AssertJson(expectedText, actualText);
Jon Skeetf8c151f2015-07-03 11:56:29 +0100123 }
124
125 [Test]
126 public void RepeatedField()
127 {
Jon Skeet6cf5f662015-07-31 10:44:59 +0100128 AssertJson("{ 'repeatedInt32': [ 1, 2, 3, 4, 5 ] }",
Jon Skeetf8c151f2015-07-03 11:56:29 +0100129 JsonFormatter.Default.Format(new TestAllTypes { RepeatedInt32 = { 1, 2, 3, 4, 5 } }));
130 }
131
132 [Test]
133 public void MapField_StringString()
134 {
Jon Skeet6cf5f662015-07-31 10:44:59 +0100135 AssertJson("{ 'mapStringString': { 'with spaces': 'bar', 'a': 'b' } }",
Jon Skeetf8c151f2015-07-03 11:56:29 +0100136 JsonFormatter.Default.Format(new TestMap { MapStringString = { { "with spaces", "bar" }, { "a", "b" } } }));
137 }
138
139 [Test]
140 public void MapField_Int32Int32()
141 {
142 // The keys are quoted, but the values aren't.
Jon Skeet6cf5f662015-07-31 10:44:59 +0100143 AssertJson("{ 'mapInt32Int32': { '0': 1, '2': 3 } }",
Jon Skeetf8c151f2015-07-03 11:56:29 +0100144 JsonFormatter.Default.Format(new TestMap { MapInt32Int32 = { { 0, 1 }, { 2, 3 } } }));
145 }
146
147 [Test]
148 public void MapField_BoolBool()
149 {
150 // The keys are quoted, but the values aren't.
Jon Skeet6cf5f662015-07-31 10:44:59 +0100151 AssertJson("{ 'mapBoolBool': { 'false': true, 'true': false } }",
Jon Skeetf8c151f2015-07-03 11:56:29 +0100152 JsonFormatter.Default.Format(new TestMap { MapBoolBool = { { false, true }, { true, false } } }));
153 }
154
155 [TestCase(1.0, "1")]
Jon Skeet6cf5f662015-07-31 10:44:59 +0100156 [TestCase(double.NaN, "'NaN'")]
157 [TestCase(double.PositiveInfinity, "'Infinity'")]
158 [TestCase(double.NegativeInfinity, "'-Infinity'")]
Jon Skeetf8c151f2015-07-03 11:56:29 +0100159 public void DoubleRepresentations(double value, string expectedValueText)
160 {
161 var message = new TestAllTypes { SingleDouble = value };
162 string actualText = JsonFormatter.Default.Format(message);
Jon Skeet6cf5f662015-07-31 10:44:59 +0100163 string expectedText = "{ 'singleDouble': " + expectedValueText + " }";
164 AssertJson(expectedText, actualText);
Jon Skeetf8c151f2015-07-03 11:56:29 +0100165 }
166
167 [Test]
Jon Skeet52db5132016-01-15 13:45:53 +0000168 public void UnknownEnumValueNumeric_SingleField()
Jon Skeetf8c151f2015-07-03 11:56:29 +0100169 {
170 var message = new TestAllTypes { SingleForeignEnum = (ForeignEnum) 100 };
Jon Skeet52db5132016-01-15 13:45:53 +0000171 AssertJson("{ 'singleForeignEnum': 100 }", JsonFormatter.Default.Format(message));
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100172 }
173
174 [Test]
Jon Skeet52db5132016-01-15 13:45:53 +0000175 public void UnknownEnumValueNumeric_RepeatedField()
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100176 {
Jon Skeet84ea2c72016-04-08 12:33:09 +0100177 var message = new TestAllTypes { RepeatedForeignEnum = { ForeignEnum.ForeignBaz, (ForeignEnum) 100, ForeignEnum.ForeignFoo } };
Jon Skeet52db5132016-01-15 13:45:53 +0000178 AssertJson("{ 'repeatedForeignEnum': [ 'FOREIGN_BAZ', 100, 'FOREIGN_FOO' ] }", JsonFormatter.Default.Format(message));
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100179 }
180
181 [Test]
Jon Skeet52db5132016-01-15 13:45:53 +0000182 public void UnknownEnumValueNumeric_MapField()
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100183 {
Jon Skeet84ea2c72016-04-08 12:33:09 +0100184 var message = new TestMap { MapInt32Enum = { { 1, MapEnum.Foo }, { 2, (MapEnum) 100 }, { 3, MapEnum.Bar } } };
Jon Skeet52db5132016-01-15 13:45:53 +0000185 AssertJson("{ 'mapInt32Enum': { '1': 'MAP_ENUM_FOO', '2': 100, '3': 'MAP_ENUM_BAR' } }", JsonFormatter.Default.Format(message));
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100186 }
187
188 [Test]
Jon Skeet52db5132016-01-15 13:45:53 +0000189 public void UnknownEnumValue_RepeatedField_AllEntriesUnknown()
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100190 {
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100191 var message = new TestAllTypes { RepeatedForeignEnum = { (ForeignEnum) 200, (ForeignEnum) 100 } };
Jon Skeet52db5132016-01-15 13:45:53 +0000192 AssertJson("{ 'repeatedForeignEnum': [ 200, 100 ] }", JsonFormatter.Default.Format(message));
Jon Skeetf8c151f2015-07-03 11:56:29 +0100193 }
194
195 [Test]
Jon Skeetf8c151f2015-07-03 11:56:29 +0100196 [TestCase("a\u17b4b", "a\\u17b4b")] // Explicit
197 [TestCase("a\u0601b", "a\\u0601b")] // Ranged
198 [TestCase("a\u0605b", "a\u0605b")] // Passthrough (note lack of double backslash...)
199 public void SimpleNonAscii(string text, string encoded)
200 {
201 var message = new TestAllTypes { SingleString = text };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100202 AssertJson("{ 'singleString': '" + encoded + "' }", JsonFormatter.Default.Format(message));
Jon Skeetf8c151f2015-07-03 11:56:29 +0100203 }
204
205 [Test]
206 public void SurrogatePairEscaping()
207 {
208 var message = new TestAllTypes { SingleString = "a\uD801\uDC01b" };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100209 AssertJson("{ 'singleString': 'a\\ud801\\udc01b' }", JsonFormatter.Default.Format(message));
Jon Skeetf8c151f2015-07-03 11:56:29 +0100210 }
211
212 [Test]
213 public void InvalidSurrogatePairsFail()
214 {
215 // Note: don't use TestCase for these, as the strings can't be reliably represented
216 // See http://codeblog.jonskeet.uk/2014/11/07/when-is-a-string-not-a-string/
217
218 // Lone low surrogate
219 var message = new TestAllTypes { SingleString = "a\uDC01b" };
220 Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
221
222 // Lone high surrogate
223 message = new TestAllTypes { SingleString = "a\uD801b" };
224 Assert.Throws<ArgumentException>(() => JsonFormatter.Default.Format(message));
225 }
226
227 [Test]
228 [TestCase("foo_bar", "fooBar")]
229 [TestCase("bananaBanana", "bananaBanana")]
230 [TestCase("BANANABanana", "bananaBanana")]
231 public void ToCamelCase(string original, string expected)
232 {
233 Assert.AreEqual(expected, JsonFormatter.ToCamelCase(original));
234 }
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100235
236 [Test]
237 [TestCase(null, "{ }")]
Jon Skeet6cf5f662015-07-31 10:44:59 +0100238 [TestCase("x", "{ 'fooString': 'x' }")]
239 [TestCase("", "{ 'fooString': '' }")]
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100240 public void Oneof(string fooStringValue, string expectedJson)
241 {
242 var message = new TestOneof();
243 if (fooStringValue != null)
244 {
245 message.FooString = fooStringValue;
246 }
247
248 // We should get the same result both with and without "format default values".
249 var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
Jon Skeet6cf5f662015-07-31 10:44:59 +0100250 AssertJson(expectedJson, formatter.Format(message));
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100251 formatter = new JsonFormatter(new JsonFormatter.Settings(true));
Jon Skeet6cf5f662015-07-31 10:44:59 +0100252 AssertJson(expectedJson, formatter.Format(message));
Jon Skeet6ea9bc72015-07-10 14:05:52 +0100253 }
Jon Skeetc9fd53a2015-07-20 11:48:24 +0100254
255 [Test]
256 public void WrapperFormatting_Single()
257 {
258 // Just a few examples, handling both classes and value types, and
259 // default vs non-default values
260 var message = new TestWellKnownTypes
261 {
262 Int64Field = 10,
263 Int32Field = 0,
264 BytesField = ByteString.FromBase64("ABCD"),
265 StringField = ""
266 };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100267 var expectedJson = "{ 'int64Field': '10', 'int32Field': 0, 'stringField': '', 'bytesField': 'ABCD' }";
268 AssertJson(expectedJson, JsonFormatter.Default.Format(message));
Jon Skeetc9fd53a2015-07-20 11:48:24 +0100269 }
270
271 [Test]
Jon Skeetfb248822015-09-04 12:41:14 +0100272 public void WrapperFormatting_Message()
273 {
274 Assert.AreEqual("\"\"", JsonFormatter.Default.Format(new StringValue()));
275 Assert.AreEqual("0", JsonFormatter.Default.Format(new Int32Value()));
276 }
277
278 [Test]
Jon Skeetc9fd53a2015-07-20 11:48:24 +0100279 public void WrapperFormatting_IncludeNull()
280 {
281 // The actual JSON here is very large because there are lots of fields. Just test a couple of them.
282 var message = new TestWellKnownTypes { Int32Field = 10 };
283 var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
284 var actualJson = formatter.Format(message);
285 Assert.IsTrue(actualJson.Contains("\"int64Field\": null"));
286 Assert.IsFalse(actualJson.Contains("\"int32Field\": null"));
287 }
Jon Skeet4fed0b52015-07-31 10:33:31 +0100288
289 [Test]
290 public void OutputIsInNumericFieldOrder_NoDefaults()
291 {
292 var formatter = new JsonFormatter(new JsonFormatter.Settings(false));
293 var message = new TestJsonFieldOrdering { PlainString = "p1", PlainInt32 = 2 };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100294 AssertJson("{ 'plainString': 'p1', 'plainInt32': 2 }", formatter.Format(message));
Jon Skeet4fed0b52015-07-31 10:33:31 +0100295 message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100296 AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
Jon Skeet4fed0b52015-07-31 10:33:31 +0100297 message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100298 AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
Jon Skeet4fed0b52015-07-31 10:33:31 +0100299 }
300
301 [Test]
302 public void OutputIsInNumericFieldOrder_WithDefaults()
303 {
304 var formatter = new JsonFormatter(new JsonFormatter.Settings(true));
305 var message = new TestJsonFieldOrdering();
Jon Skeet6cf5f662015-07-31 10:44:59 +0100306 AssertJson("{ 'plainString': '', 'plainInt32': 0 }", formatter.Format(message));
Jon Skeet4fed0b52015-07-31 10:33:31 +0100307 message = new TestJsonFieldOrdering { O1Int32 = 5, O2String = "o2", PlainInt32 = 10, PlainString = "plain" };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100308 AssertJson("{ 'plainString': 'plain', 'o2String': 'o2', 'plainInt32': 10, 'o1Int32': 5 }", formatter.Format(message));
Jon Skeet4fed0b52015-07-31 10:33:31 +0100309 message = new TestJsonFieldOrdering { O1String = "", O2Int32 = 0, PlainInt32 = 10, PlainString = "plain" };
Jon Skeet6cf5f662015-07-31 10:44:59 +0100310 AssertJson("{ 'plainString': 'plain', 'o1String': '', 'plainInt32': 10, 'o2Int32': 0 }", formatter.Format(message));
311 }
312
Jon Skeet16e272e2015-07-31 13:22:15 +0100313 [Test]
Jon Skeetb4a58172016-01-06 12:05:31 +0000314 [TestCase("1970-01-01T00:00:00Z", 0)]
Jon Skeet1fc48592016-01-15 11:39:27 +0000315 [TestCase("1970-01-01T00:00:00.000000001Z", 1)]
316 [TestCase("1970-01-01T00:00:00.000000010Z", 10)]
317 [TestCase("1970-01-01T00:00:00.000000100Z", 100)]
318 [TestCase("1970-01-01T00:00:00.000001Z", 1000)]
319 [TestCase("1970-01-01T00:00:00.000010Z", 10000)]
320 [TestCase("1970-01-01T00:00:00.000100Z", 100000)]
321 [TestCase("1970-01-01T00:00:00.001Z", 1000000)]
322 [TestCase("1970-01-01T00:00:00.010Z", 10000000)]
323 [TestCase("1970-01-01T00:00:00.100Z", 100000000)]
Jon Skeetb4a58172016-01-06 12:05:31 +0000324 [TestCase("1970-01-01T00:00:00.120Z", 120000000)]
325 [TestCase("1970-01-01T00:00:00.123Z", 123000000)]
326 [TestCase("1970-01-01T00:00:00.123400Z", 123400000)]
327 [TestCase("1970-01-01T00:00:00.123450Z", 123450000)]
328 [TestCase("1970-01-01T00:00:00.123456Z", 123456000)]
329 [TestCase("1970-01-01T00:00:00.123456700Z", 123456700)]
330 [TestCase("1970-01-01T00:00:00.123456780Z", 123456780)]
331 [TestCase("1970-01-01T00:00:00.123456789Z", 123456789)]
332 public void TimestampStandalone(string expected, int nanos)
Jon Skeet16e272e2015-07-31 13:22:15 +0100333 {
Jon Skeetb4a58172016-01-06 12:05:31 +0000334 Assert.AreEqual(WrapInQuotes(expected), new Timestamp { Nanos = nanos }.ToString());
335 }
Jon Skeet16e272e2015-07-31 13:22:15 +0100336
Jon Skeetb4a58172016-01-06 12:05:31 +0000337 [Test]
338 public void TimestampStandalone_FromDateTime()
339 {
340 // One before and one after the Unix epoch, more easily represented via DateTime.
341 Assert.AreEqual("\"1673-06-19T12:34:56Z\"",
Jon Skeet16e272e2015-07-31 13:22:15 +0100342 new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp().ToString());
Jon Skeetb4a58172016-01-06 12:05:31 +0000343 Assert.AreEqual("\"2015-07-31T10:29:34Z\"",
Jon Skeet16e272e2015-07-31 13:22:15 +0100344 new DateTime(2015, 7, 31, 10, 29, 34, DateTimeKind.Utc).ToTimestamp().ToString());
345 }
346
347 [Test]
Jon Skeetdd43dcc2016-01-20 18:43:00 +0000348 [TestCase(-1, -1)] // Would be valid as duration
349 [TestCase(1, Timestamp.MaxNanos + 1)]
350 [TestCase(Timestamp.UnixSecondsAtBclMaxValue + 1, 0)]
351 [TestCase(Timestamp.UnixSecondsAtBclMinValue - 1, 0)]
352 public void TimestampStandalone_NonNormalized(long seconds, int nanoseconds)
353 {
354 var timestamp = new Timestamp { Seconds = seconds, Nanos = nanoseconds };
355 Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(timestamp));
356 }
357
358 [Test]
Jon Skeet16e272e2015-07-31 13:22:15 +0100359 public void TimestampField()
360 {
361 var message = new TestWellKnownTypes { TimestampField = new Timestamp() };
362 AssertJson("{ 'timestampField': '1970-01-01T00:00:00Z' }", JsonFormatter.Default.Format(message));
363 }
364
365 [Test]
366 [TestCase(0, 0, "0s")]
367 [TestCase(1, 0, "1s")]
368 [TestCase(-1, 0, "-1s")]
Jon Skeet1fc48592016-01-15 11:39:27 +0000369 [TestCase(0, 1, "0.000000001s")]
370 [TestCase(0, 10, "0.000000010s")]
371 [TestCase(0, 100, "0.000000100s")]
372 [TestCase(0, 1000, "0.000001s")]
373 [TestCase(0, 10000, "0.000010s")]
374 [TestCase(0, 100000, "0.000100s")]
375 [TestCase(0, 1000000, "0.001s")]
376 [TestCase(0, 10000000, "0.010s")]
Jon Skeet16e272e2015-07-31 13:22:15 +0100377 [TestCase(0, 100000000, "0.100s")]
378 [TestCase(0, 120000000, "0.120s")]
379 [TestCase(0, 123000000, "0.123s")]
380 [TestCase(0, 123400000, "0.123400s")]
381 [TestCase(0, 123450000, "0.123450s")]
382 [TestCase(0, 123456000, "0.123456s")]
383 [TestCase(0, 123456700, "0.123456700s")]
384 [TestCase(0, 123456780, "0.123456780s")]
385 [TestCase(0, 123456789, "0.123456789s")]
386 [TestCase(0, -100000000, "-0.100s")]
387 [TestCase(1, 100000000, "1.100s")]
388 [TestCase(-1, -100000000, "-1.100s")]
Jon Skeet16e272e2015-07-31 13:22:15 +0100389 public void DurationStandalone(long seconds, int nanoseconds, string expected)
390 {
Jon Skeetdd43dcc2016-01-20 18:43:00 +0000391 var json = JsonFormatter.Default.Format(new Duration { Seconds = seconds, Nanos = nanoseconds });
392 Assert.AreEqual(WrapInQuotes(expected), json);
Jon Skeet16e272e2015-07-31 13:22:15 +0100393 }
394
395 [Test]
Jon Skeet1fc48592016-01-15 11:39:27 +0000396 [TestCase(1, 2123456789)]
397 [TestCase(1, -100000000)]
Jon Skeet030c2682016-01-15 17:34:10 +0000398 public void DurationStandalone_NonNormalized(long seconds, int nanoseconds)
Jon Skeet1fc48592016-01-15 11:39:27 +0000399 {
Jon Skeetdd43dcc2016-01-20 18:43:00 +0000400 var duration = new Duration { Seconds = seconds, Nanos = nanoseconds };
401 Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(duration));
Jon Skeet1fc48592016-01-15 11:39:27 +0000402 }
403
404 [Test]
Jon Skeet16e272e2015-07-31 13:22:15 +0100405 public void DurationField()
406 {
407 var message = new TestWellKnownTypes { DurationField = new Duration() };
408 AssertJson("{ 'durationField': '0s' }", JsonFormatter.Default.Format(message));
Jon Skeete7caf152015-07-31 15:07:50 +0100409 }
Jon Skeet16e272e2015-07-31 13:22:15 +0100410
Jon Skeete7caf152015-07-31 15:07:50 +0100411 [Test]
412 public void StructSample()
413 {
414 var message = new Struct
415 {
416 Fields =
417 {
Jon Skeetfb248822015-09-04 12:41:14 +0100418 { "a", Value.ForNull() },
419 { "b", Value.ForBool(false) },
420 { "c", Value.ForNumber(10.5) },
421 { "d", Value.ForString("text") },
422 { "e", Value.ForList(Value.ForString("t1"), Value.ForNumber(5)) },
423 { "f", Value.ForStruct(new Struct { Fields = { { "nested", Value.ForString("value") } } }) }
Jon Skeete7caf152015-07-31 15:07:50 +0100424 }
425 };
426 AssertJson("{ 'a': null, 'b': false, 'c': 10.5, 'd': 'text', 'e': [ 't1', 5 ], 'f': { 'nested': 'value' } }", message.ToString());
Jon Skeet16e272e2015-07-31 13:22:15 +0100427 }
428
Jon Skeet0e30de32015-08-03 11:43:07 +0100429 [Test]
Jon Skeetf437b672016-01-15 12:02:07 +0000430 [TestCase("foo__bar")]
431 [TestCase("foo_3_ar")]
432 [TestCase("fooBar")]
433 public void FieldMaskInvalid(string input)
434 {
435 var mask = new FieldMask { Paths = { input } };
436 Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(mask));
437 }
438
439 [Test]
Jon Skeet0e30de32015-08-03 11:43:07 +0100440 public void FieldMaskStandalone()
441 {
442 var fieldMask = new FieldMask { Paths = { "", "single", "with_underscore", "nested.field.name", "nested..double_dot" } };
Jon Skeetb4a58172016-01-06 12:05:31 +0000443 Assert.AreEqual("\",single,withUnderscore,nested.field.name,nested..doubleDot\"", fieldMask.ToString());
Jon Skeet0e30de32015-08-03 11:43:07 +0100444
445 // Invalid, but we shouldn't create broken JSON...
446 fieldMask = new FieldMask { Paths = { "x\\y" } };
Jon Skeetb4a58172016-01-06 12:05:31 +0000447 Assert.AreEqual(@"""x\\y""", fieldMask.ToString());
Jon Skeet0e30de32015-08-03 11:43:07 +0100448 }
449
450 [Test]
451 public void FieldMaskField()
452 {
453 var message = new TestWellKnownTypes { FieldMaskField = new FieldMask { Paths = { "user.display_name", "photo" } } };
454 AssertJson("{ 'fieldMaskField': 'user.displayName,photo' }", JsonFormatter.Default.Format(message));
455 }
456
Jon Skeetfb248822015-09-04 12:41:14 +0100457 // SourceContext is an example of a well-known type with no special JSON handling
458 [Test]
459 public void SourceContextStandalone()
460 {
461 var message = new SourceContext { FileName = "foo.proto" };
462 AssertJson("{ 'fileName': 'foo.proto' }", JsonFormatter.Default.Format(message));
463 }
464
Jon Skeet567579b2015-11-23 12:43:54 +0000465 [Test]
466 public void AnyWellKnownType()
467 {
468 var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(Timestamp.Descriptor)));
469 var timestamp = new DateTime(1673, 6, 19, 12, 34, 56, DateTimeKind.Utc).ToTimestamp();
470 var any = Any.Pack(timestamp);
471 AssertJson("{ '@type': 'type.googleapis.com/google.protobuf.Timestamp', 'value': '1673-06-19T12:34:56Z' }", formatter.Format(any));
472 }
473
474 [Test]
475 public void AnyMessageType()
476 {
477 var formatter = new JsonFormatter(new JsonFormatter.Settings(false, TypeRegistry.FromMessages(TestAllTypes.Descriptor)));
478 var message = new TestAllTypes { SingleInt32 = 10, SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } };
479 var any = Any.Pack(message);
480 AssertJson("{ '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 10, 'singleNestedMessage': { 'bb': 20 } }", formatter.Format(any));
481 }
482
483 [Test]
484 public void AnyNested()
485 {
486 var registry = TypeRegistry.FromMessages(TestWellKnownTypes.Descriptor, TestAllTypes.Descriptor);
487 var formatter = new JsonFormatter(new JsonFormatter.Settings(false, registry));
488
489 // Nest an Any as the value of an Any.
490 var doubleNestedMessage = new TestAllTypes { SingleInt32 = 20 };
491 var nestedMessage = Any.Pack(doubleNestedMessage);
492 var message = new TestWellKnownTypes { AnyField = Any.Pack(nestedMessage) };
493 AssertJson("{ 'anyField': { '@type': 'type.googleapis.com/google.protobuf.Any', 'value': { '@type': 'type.googleapis.com/protobuf_unittest.TestAllTypes', 'singleInt32': 20 } } }",
494 formatter.Format(message));
495 }
496
497 [Test]
498 public void AnyUnknownType()
499 {
500 // The default type registry doesn't have any types in it.
501 var message = new TestAllTypes();
502 var any = Any.Pack(message);
503 Assert.Throws<InvalidOperationException>(() => JsonFormatter.Default.Format(any));
504 }
505
Jon Skeet6cf5f662015-07-31 10:44:59 +0100506 /// <summary>
507 /// Checks that the actual JSON is the same as the expected JSON - but after replacing
508 /// all apostrophes in the expected JSON with double quotes. This basically makes the tests easier
509 /// to read.
510 /// </summary>
511 private static void AssertJson(string expectedJsonWithApostrophes, string actualJson)
512 {
513 var expectedJson = expectedJsonWithApostrophes.Replace("'", "\"");
514 Assert.AreEqual(expectedJson, actualJson);
Jon Skeet4fed0b52015-07-31 10:33:31 +0100515 }
Jon Skeetf8c151f2015-07-03 11:56:29 +0100516 }
517}