blob: 09bc91f7728f62ba404401df5af199cb5b4d7d26 [file] [log] [blame]
Feng Xiao6bbe1972018-08-08 17:00:41 -07001// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc. All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
Paul Yangcecba292018-12-14 16:05:03 -080031#include "binary_json_conformance_suite.h"
Feng Xiao6bbe1972018-08-08 17:00:41 -070032#include "conformance_test.h"
33#include "third_party/jsoncpp/json.h"
34
35#include <google/protobuf/test_messages_proto3.pb.h>
36#include <google/protobuf/test_messages_proto2.pb.h>
37
38#include <google/protobuf/stubs/common.h>
39#include <google/protobuf/stubs/strutil.h>
40#include <google/protobuf/text_format.h>
Paul Yangcecba292018-12-14 16:05:03 -080041#include <google/protobuf/util/json_util.h>
Feng Xiao6bbe1972018-08-08 17:00:41 -070042#include <google/protobuf/util/type_resolver_util.h>
43#include <google/protobuf/wire_format_lite.h>
44
45using conformance::ConformanceRequest;
46using conformance::ConformanceResponse;
Paul Yangcecba292018-12-14 16:05:03 -080047using conformance::WireFormat;
Feng Xiao6bbe1972018-08-08 17:00:41 -070048using google::protobuf::Descriptor;
49using google::protobuf::FieldDescriptor;
50using google::protobuf::Message;
51using google::protobuf::internal::WireFormatLite;
52using google::protobuf::TextFormat;
53using google::protobuf::util::NewTypeResolverForDescriptorPool;
54using protobuf_test_messages::proto3::TestAllTypesProto3;
55using protobuf_test_messages::proto2::TestAllTypesProto2;
56using std::string;
57
58namespace {
59
60static const char kTypeUrlPrefix[] = "type.googleapis.com";
61
62static string GetTypeUrl(const Descriptor* message) {
63 return string(kTypeUrlPrefix) + "/" + message->full_name();
64}
65
66/* Routines for building arbitrary protos *************************************/
67
68// We would use CodedOutputStream except that we want more freedom to build
69// arbitrary protos (even invalid ones).
70
71const string empty;
72
73string cat(const string& a, const string& b,
74 const string& c = empty,
75 const string& d = empty,
76 const string& e = empty,
77 const string& f = empty,
78 const string& g = empty,
79 const string& h = empty,
80 const string& i = empty,
81 const string& j = empty,
82 const string& k = empty,
83 const string& l = empty) {
84 string ret;
85 ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
86 g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
87 ret.append(a);
88 ret.append(b);
89 ret.append(c);
90 ret.append(d);
91 ret.append(e);
92 ret.append(f);
93 ret.append(g);
94 ret.append(h);
95 ret.append(i);
96 ret.append(j);
97 ret.append(k);
98 ret.append(l);
99 return ret;
100}
101
102// The maximum number of bytes that it takes to encode a 64-bit varint.
103#define VARINT_MAX_LEN 10
104
105size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) {
106 if (val == 0) { buf[0] = 0; return 1; }
107 size_t i = 0;
108 while (val) {
109 uint8_t byte = val & 0x7fU;
110 val >>= 7;
111 if (val || over_encoded_bytes) byte |= 0x80U;
112 buf[i++] = byte;
113 }
114 while (over_encoded_bytes--) {
115 assert(i < 10);
116 uint8_t byte = over_encoded_bytes ? 0x80 : 0;
117 buf[i++] = byte;
118 }
119 return i;
120}
121
122string varint(uint64_t x) {
123 char buf[VARINT_MAX_LEN];
124 size_t len = vencode64(x, 0, buf);
125 return string(buf, len);
126}
127
128// Encodes a varint that is |extra| bytes longer than it needs to be, but still
129// valid.
130string longvarint(uint64_t x, int extra) {
131 char buf[VARINT_MAX_LEN];
132 size_t len = vencode64(x, extra, buf);
133 return string(buf, len);
134}
135
136// TODO: proper byte-swapping for big-endian machines.
137string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
138string fixed64(void *data) { return string(static_cast<char*>(data), 8); }
139
140string delim(const string& buf) { return cat(varint(buf.size()), buf); }
141string u32(uint32_t u32) { return fixed32(&u32); }
142string u64(uint64_t u64) { return fixed64(&u64); }
143string flt(float f) { return fixed32(&f); }
144string dbl(double d) { return fixed64(&d); }
145string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
146string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }
147
148string tag(uint32_t fieldnum, char wire_type) {
149 return varint((fieldnum << 3) | wire_type);
150}
151
Paul Yangce942bc2019-09-03 10:47:32 -0700152string GetDefaultValue(FieldDescriptor::Type type) {
153 switch (type) {
154 case FieldDescriptor::TYPE_INT32:
155 case FieldDescriptor::TYPE_INT64:
156 case FieldDescriptor::TYPE_UINT32:
157 case FieldDescriptor::TYPE_UINT64:
158 case FieldDescriptor::TYPE_ENUM:
159 case FieldDescriptor::TYPE_BOOL:
160 return varint(0);
161 case FieldDescriptor::TYPE_SINT32:
162 return zz32(0);
163 case FieldDescriptor::TYPE_SINT64:
164 return zz64(0);
165 case FieldDescriptor::TYPE_FIXED32:
166 case FieldDescriptor::TYPE_SFIXED32:
167 return u32(0);
168 case FieldDescriptor::TYPE_FIXED64:
169 case FieldDescriptor::TYPE_SFIXED64:
170 return u64(0);
171 case FieldDescriptor::TYPE_FLOAT:
172 return flt(0);
173 case FieldDescriptor::TYPE_DOUBLE:
174 return dbl(0);
175 case FieldDescriptor::TYPE_STRING:
176 case FieldDescriptor::TYPE_BYTES:
177 case FieldDescriptor::TYPE_MESSAGE:
178 return delim("");
179 }
180 return "";
181}
182
183string GetNonDefaultValue(FieldDescriptor::Type type) {
184 switch (type) {
185 case FieldDescriptor::TYPE_INT32:
186 case FieldDescriptor::TYPE_INT64:
187 case FieldDescriptor::TYPE_UINT32:
188 case FieldDescriptor::TYPE_UINT64:
189 case FieldDescriptor::TYPE_ENUM:
190 case FieldDescriptor::TYPE_BOOL:
191 return varint(1);
192 case FieldDescriptor::TYPE_SINT32:
193 return zz32(1);
194 case FieldDescriptor::TYPE_SINT64:
195 return zz64(1);
196 case FieldDescriptor::TYPE_FIXED32:
197 case FieldDescriptor::TYPE_SFIXED32:
198 return u32(1);
199 case FieldDescriptor::TYPE_FIXED64:
200 case FieldDescriptor::TYPE_SFIXED64:
201 return u64(1);
202 case FieldDescriptor::TYPE_FLOAT:
203 return flt(1);
204 case FieldDescriptor::TYPE_DOUBLE:
205 return dbl(1);
206 case FieldDescriptor::TYPE_STRING:
207 case FieldDescriptor::TYPE_BYTES:
208 return delim("a");
209 case FieldDescriptor::TYPE_MESSAGE:
210 return delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)));
211 }
212 return "";
213}
214
Feng Xiao6bbe1972018-08-08 17:00:41 -0700215#define UNKNOWN_FIELD 666
216
Paul Yang0c4b6072019-08-02 14:35:44 -0700217enum class Packed {
218 UNSPECIFIED = 0,
219 TRUE = 1,
220 FALSE = 2,
221};
Feng Xiao6bbe1972018-08-08 17:00:41 -0700222
Rafi Kamal4f02f052019-08-22 16:14:22 -0700223const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
224 bool repeated, bool is_proto3,
225 Packed packed = Packed::UNSPECIFIED) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700226 const Descriptor* d = is_proto3 ?
227 TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
228 for (int i = 0; i < d->field_count(); i++) {
229 const FieldDescriptor* f = d->field(i);
230 if (f->type() == type && f->is_repeated() == repeated) {
Rafi Kamal4f02f052019-08-22 16:14:22 -0700231 if ((packed == Packed::TRUE && !f->is_packed()) ||
232 (packed == Packed::FALSE && f->is_packed())) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700233 continue;
234 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700235 return f;
236 }
237 }
Paul Yang0c4b6072019-08-02 14:35:44 -0700238
239 string packed_string = "";
240 const string repeated_string = repeated ? "Repeated " : "Singular ";
241 const string proto_string = is_proto3 ? "Proto3" : "Proto2";
242 if (packed == Packed::TRUE) {
243 packed_string = "Packed ";
244 }
245 if (packed == Packed::FALSE) {
246 packed_string = "Unpacked ";
247 }
248 GOOGLE_LOG(FATAL) << "Couldn't find field with type: "
Rafi Kamal4f02f052019-08-22 16:14:22 -0700249 << repeated_string.c_str() << packed_string.c_str()
250 << FieldDescriptor::TypeName(type) << " for "
Paul Yang0c4b6072019-08-02 14:35:44 -0700251 << proto_string.c_str();
Feng Xiao6bbe1972018-08-08 17:00:41 -0700252 return nullptr;
253}
254
Paul Yangce942bc2019-09-03 10:47:32 -0700255const FieldDescriptor* GetFieldForMapType(
256 FieldDescriptor::Type key_type,
257 FieldDescriptor::Type value_type,
258 bool is_proto3) {
259 const Descriptor* d = is_proto3 ?
260 TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
261 for (int i = 0; i < d->field_count(); i++) {
262 const FieldDescriptor* f = d->field(i);
263 if (f->is_map()) {
264 const Descriptor* map_entry = f->message_type();
265 const FieldDescriptor* key = map_entry->field(0);
266 const FieldDescriptor* value = map_entry->field(1);
267 if (key->type() == key_type && value->type() == value_type) {
268 return f;
269 }
270 }
271 }
272
273 const string proto_string = is_proto3 ? "Proto3" : "Proto2";
274 GOOGLE_LOG(FATAL) << "Couldn't find map field with type: "
275 << FieldDescriptor::TypeName(key_type)
276 << " and "
277 << FieldDescriptor::TypeName(key_type)
278 << " for "
279 << proto_string.c_str();
280 return nullptr;
281}
282
Feng Xiao6bbe1972018-08-08 17:00:41 -0700283string UpperCase(string str) {
284 for (int i = 0; i < str.size(); i++) {
285 str[i] = toupper(str[i]);
286 }
287 return str;
288}
289
290std::unique_ptr<Message> NewTestMessage(bool is_proto3) {
291 std::unique_ptr<Message> prototype;
292 if (is_proto3) {
293 prototype.reset(new TestAllTypesProto3());
294 } else {
295 prototype.reset(new TestAllTypesProto2());
296 }
297 return prototype;
298}
299
Paul Yang6c9d7ec2019-08-23 12:20:19 -0700300bool IsProto3Default(FieldDescriptor::Type type, const string& binary_data) {
301 switch (type) {
302 case FieldDescriptor::TYPE_DOUBLE:
303 return binary_data == dbl(0);
304 case FieldDescriptor::TYPE_FLOAT:
305 return binary_data == flt(0);
306 case FieldDescriptor::TYPE_BOOL:
307 case FieldDescriptor::TYPE_INT64:
308 case FieldDescriptor::TYPE_UINT64:
309 case FieldDescriptor::TYPE_INT32:
310 case FieldDescriptor::TYPE_UINT32:
311 case FieldDescriptor::TYPE_SINT32:
312 case FieldDescriptor::TYPE_SINT64:
313 case FieldDescriptor::TYPE_ENUM:
314 return binary_data == varint(0);
315 case FieldDescriptor::TYPE_FIXED64:
316 case FieldDescriptor::TYPE_SFIXED64:
317 return binary_data == u64(0);
318 case FieldDescriptor::TYPE_FIXED32:
319 case FieldDescriptor::TYPE_SFIXED32:
320 return binary_data == u32(0);
321 case FieldDescriptor::TYPE_STRING:
322 case FieldDescriptor::TYPE_BYTES:
323 return binary_data == delim("");
324 default:
325 return false;
326 }
327}
328
Feng Xiao6bbe1972018-08-08 17:00:41 -0700329} // anonymous namespace
330
331namespace google {
332namespace protobuf {
333
Paul Yangcecba292018-12-14 16:05:03 -0800334bool BinaryAndJsonConformanceSuite::ParseJsonResponse(
335 const ConformanceResponse& response,
336 Message* test_message) {
337 string binary_protobuf;
338 util::Status status =
339 JsonToBinaryString(type_resolver_.get(), type_url_,
340 response.json_payload(), &binary_protobuf);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700341
Paul Yangcecba292018-12-14 16:05:03 -0800342 if (!status.ok()) {
343 return false;
344 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700345
Paul Yangcecba292018-12-14 16:05:03 -0800346 if (!test_message->ParseFromString(binary_protobuf)) {
347 GOOGLE_LOG(FATAL)
348 << "INTERNAL ERROR: internal JSON->protobuf transcode "
349 << "yielded unparseable proto.";
350 return false;
351 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700352
Paul Yangcecba292018-12-14 16:05:03 -0800353 return true;
354}
355
356bool BinaryAndJsonConformanceSuite::ParseResponse(
357 const ConformanceResponse& response,
358 const ConformanceRequestSetting& setting,
359 Message* test_message) {
360 const ConformanceRequest& request = setting.GetRequest();
361 WireFormat requested_output = request.requested_output_format();
362 const string& test_name = setting.GetTestName();
363 ConformanceLevel level = setting.GetLevel();
364
365 switch (response.result_case()) {
366 case ConformanceResponse::kProtobufPayload: {
367 if (requested_output != conformance::PROTOBUF) {
368 ReportFailure(
369 test_name, level, request, response,
370 StrCat("Test was asked for ", WireFormatToString(requested_output),
371 " output but provided PROTOBUF instead.").c_str());
372 return false;
373 }
374
375 if (!test_message->ParseFromString(response.protobuf_payload())) {
376 ReportFailure(test_name, level, request, response,
377 "Protobuf output we received from test was unparseable.");
378 return false;
379 }
380
381 break;
382 }
383
384 case ConformanceResponse::kJsonPayload: {
385 if (requested_output != conformance::JSON) {
386 ReportFailure(
387 test_name, level, request, response,
388 StrCat("Test was asked for ", WireFormatToString(requested_output),
389 " output but provided JSON instead.").c_str());
390 return false;
391 }
392
393 if (!ParseJsonResponse(response, test_message)) {
394 ReportFailure(test_name, level, request, response,
395 "JSON output we received from test was unparseable.");
396 return false;
397 }
398
399 break;
400 }
401
402 default:
403 GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
404 << response.result_case();
405 }
406
407 return true;
408}
409
410void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion (
Feng Xiao6bbe1972018-08-08 17:00:41 -0700411 const string& proto, const string& test_name, ConformanceLevel level,
412 bool is_proto3) {
413 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
414 // We don't expect output, but if the program erroneously accepts the protobuf
415 // we let it send its response as this. We must not leave it unspecified.
416 ConformanceRequestSetting setting(
417 level, conformance::PROTOBUF, conformance::PROTOBUF,
418 conformance::BINARY_TEST,
419 *prototype, test_name, proto);
420
421 const ConformanceRequest& request = setting.GetRequest();
422 ConformanceResponse response;
423 string effective_test_name =
424 StrCat(setting.ConformanceLevelToString(level),
425 (is_proto3 ? ".Proto3" : ".Proto2"),
426 ".ProtobufInput.", test_name);
427
428 RunTest(effective_test_name, request, &response);
429 if (response.result_case() == ConformanceResponse::kParseError) {
430 ReportSuccess(effective_test_name);
431 } else if (response.result_case() == ConformanceResponse::kSkipped) {
432 ReportSkip(effective_test_name, request, response);
433 } else {
434 ReportFailure(effective_test_name, level, request, response,
435 "Should have failed to parse, but didn't.");
436 }
437}
438
439// Expect that this precise protobuf will cause a parse error.
Paul Yangcecba292018-12-14 16:05:03 -0800440void BinaryAndJsonConformanceSuite::ExpectParseFailureForProto(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700441 const string& proto, const string& test_name, ConformanceLevel level) {
442 ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true);
443 ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false);
444}
445
446// Expect that this protobuf will cause a parse error, even if it is followed
447// by valid protobuf data. We can try running this twice: once with this
448// data verbatim and once with this data followed by some valid data.
449//
450// TODO(haberman): implement the second of these.
Paul Yangcecba292018-12-14 16:05:03 -0800451void BinaryAndJsonConformanceSuite::ExpectHardParseFailureForProto(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700452 const string& proto, const string& test_name, ConformanceLevel level) {
453 return ExpectParseFailureForProto(proto, test_name, level);
454}
455
Paul Yangcecba292018-12-14 16:05:03 -0800456void BinaryAndJsonConformanceSuite::RunValidJsonTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700457 const string& test_name, ConformanceLevel level, const string& input_json,
458 const string& equivalent_text_format) {
459 TestAllTypesProto3 prototype;
460 ConformanceRequestSetting setting1(
461 level, conformance::JSON, conformance::PROTOBUF,
462 conformance::JSON_TEST,
463 prototype, test_name, input_json);
464 RunValidInputTest(setting1, equivalent_text_format);
465 ConformanceRequestSetting setting2(
466 level, conformance::JSON, conformance::JSON,
467 conformance::JSON_TEST,
468 prototype, test_name, input_json);
469 RunValidInputTest(setting2, equivalent_text_format);
470}
471
Paul Yangcecba292018-12-14 16:05:03 -0800472void BinaryAndJsonConformanceSuite::RunValidJsonTestWithProtobufInput(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700473 const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
474 const string& equivalent_text_format) {
475 ConformanceRequestSetting setting(
476 level, conformance::PROTOBUF, conformance::JSON,
477 conformance::JSON_TEST,
478 input, test_name, input.SerializeAsString());
479 RunValidInputTest(setting, equivalent_text_format);
480}
481
Paul Yangcecba292018-12-14 16:05:03 -0800482void BinaryAndJsonConformanceSuite::RunValidJsonIgnoreUnknownTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700483 const string& test_name, ConformanceLevel level, const string& input_json,
484 const string& equivalent_text_format) {
485 TestAllTypesProto3 prototype;
486 ConformanceRequestSetting setting(
487 level, conformance::JSON, conformance::PROTOBUF,
488 conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST,
489 prototype, test_name, input_json);
490 RunValidInputTest(setting, equivalent_text_format);
491}
492
Paul Yangcecba292018-12-14 16:05:03 -0800493void BinaryAndJsonConformanceSuite::RunValidProtobufTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700494 const string& test_name, ConformanceLevel level,
495 const string& input_protobuf, const string& equivalent_text_format,
496 bool is_proto3) {
497 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
498
499 ConformanceRequestSetting setting1(
500 level, conformance::PROTOBUF, conformance::PROTOBUF,
501 conformance::BINARY_TEST,
502 *prototype, test_name, input_protobuf);
503 RunValidInputTest(setting1, equivalent_text_format);
504
505 if (is_proto3) {
506 ConformanceRequestSetting setting2(
507 level, conformance::PROTOBUF, conformance::JSON,
508 conformance::BINARY_TEST,
509 *prototype, test_name, input_protobuf);
510 RunValidInputTest(setting2, equivalent_text_format);
511 }
512}
513
Paul Yangcecba292018-12-14 16:05:03 -0800514void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700515 const string& test_name, ConformanceLevel level,
516 const string& input_protobuf, bool is_proto3) {
Rafi Kamal4f02f052019-08-22 16:14:22 -0700517 RunValidBinaryProtobufTest(test_name, level, input_protobuf, input_protobuf,
518 is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700519}
520
521void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
522 const string& test_name, ConformanceLevel level,
Rafi Kamal4f02f052019-08-22 16:14:22 -0700523 const string& input_protobuf, const string& expected_protobuf,
Paul Yanga9bb6562019-07-26 10:05:14 -0700524 bool is_proto3) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700525 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
526 ConformanceRequestSetting setting(
527 level, conformance::PROTOBUF, conformance::PROTOBUF,
528 conformance::BINARY_TEST,
529 *prototype, test_name, input_protobuf);
Paul Yanga9bb6562019-07-26 10:05:14 -0700530 RunValidBinaryInputTest(setting, expected_protobuf, true);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700531}
532
Paul Yangcecba292018-12-14 16:05:03 -0800533void BinaryAndJsonConformanceSuite::RunValidProtobufTestWithMessage(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700534 const string& test_name, ConformanceLevel level, const Message *input,
535 const string& equivalent_text_format, bool is_proto3) {
536 RunValidProtobufTest(test_name, level, input->SerializeAsString(),
537 equivalent_text_format, is_proto3);
538}
539
540// According to proto3 JSON specification, JSON serializers follow more strict
541// rules than parsers (e.g., a serializer must serialize int32 values as JSON
542// numbers while the parser is allowed to accept them as JSON strings). This
543// method allows strict checking on a proto3 JSON serializer by inspecting
544// the JSON output directly.
Paul Yangcecba292018-12-14 16:05:03 -0800545void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700546 const string& test_name, ConformanceLevel level, const string& input_json,
547 const Validator& validator) {
548 TestAllTypesProto3 prototype;
549 ConformanceRequestSetting setting(
550 level, conformance::JSON, conformance::JSON,
551 conformance::JSON_TEST,
552 prototype, test_name, input_json);
553 const ConformanceRequest& request = setting.GetRequest();
554 ConformanceResponse response;
555 string effective_test_name =
556 StrCat(setting.ConformanceLevelToString(level),
557 ".Proto3.JsonInput.",
558 test_name, ".Validator");
559
560 RunTest(effective_test_name, request, &response);
561
562 if (response.result_case() == ConformanceResponse::kSkipped) {
563 ReportSkip(effective_test_name, request, response);
564 return;
565 }
566
567 if (response.result_case() != ConformanceResponse::kJsonPayload) {
568 ReportFailure(effective_test_name, level, request, response,
569 "Expected JSON payload but got type %d.",
570 response.result_case());
571 return;
572 }
573 Json::Reader reader;
574 Json::Value value;
575 if (!reader.parse(response.json_payload(), value)) {
576 ReportFailure(effective_test_name, level, request, response,
577 "JSON payload cannot be parsed as valid JSON: %s",
578 reader.getFormattedErrorMessages().c_str());
579 return;
580 }
581 if (!validator(value)) {
582 ReportFailure(effective_test_name, level, request, response,
583 "JSON payload validation failed.");
584 return;
585 }
586 ReportSuccess(effective_test_name);
587}
588
Paul Yangcecba292018-12-14 16:05:03 -0800589void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700590 const string& test_name, ConformanceLevel level, const string& input_json) {
591 TestAllTypesProto3 prototype;
592 // We don't expect output, but if the program erroneously accepts the protobuf
593 // we let it send its response as this. We must not leave it unspecified.
594 ConformanceRequestSetting setting(
595 level, conformance::JSON, conformance::JSON,
596 conformance::JSON_TEST,
597 prototype, test_name, input_json);
598 const ConformanceRequest& request = setting.GetRequest();
599 ConformanceResponse response;
600 string effective_test_name =
601 StrCat(setting.ConformanceLevelToString(level),
602 ".Proto3.JsonInput.", test_name);
603
604 RunTest(effective_test_name, request, &response);
605 if (response.result_case() == ConformanceResponse::kParseError) {
606 ReportSuccess(effective_test_name);
607 } else if (response.result_case() == ConformanceResponse::kSkipped) {
608 ReportSkip(effective_test_name, request, response);
609 } else {
610 ReportFailure(effective_test_name, level, request, response,
611 "Should have failed to parse, but didn't.");
612 }
613}
614
Paul Yangcecba292018-12-14 16:05:03 -0800615void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700616 const string& test_name, ConformanceLevel level, const string& text_format) {
617 TestAllTypesProto3 payload_message;
618 GOOGLE_CHECK(
619 TextFormat::ParseFromString(text_format, &payload_message))
620 << "Failed to parse: " << text_format;
621
622 TestAllTypesProto3 prototype;
623 ConformanceRequestSetting setting(
624 level, conformance::PROTOBUF, conformance::JSON,
625 conformance::JSON_TEST,
626 prototype, test_name, payload_message.SerializeAsString());
627 const ConformanceRequest& request = setting.GetRequest();
628 ConformanceResponse response;
629 string effective_test_name =
630 StrCat(setting.ConformanceLevelToString(level),
631 ".", test_name, ".JsonOutput");
632
633 RunTest(effective_test_name, request, &response);
634 if (response.result_case() == ConformanceResponse::kSerializeError) {
635 ReportSuccess(effective_test_name);
636 } else if (response.result_case() == ConformanceResponse::kSkipped) {
637 ReportSkip(effective_test_name, request, response);
638 } else {
639 ReportFailure(effective_test_name, level, request, response,
640 "Should have failed to serialize, but didn't.");
641 }
642}
643
Paul Yangcecba292018-12-14 16:05:03 -0800644void BinaryAndJsonConformanceSuite::TestPrematureEOFForType(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700645 FieldDescriptor::Type type) {
646 // Incomplete values for each wire type.
647 static const string incompletes[6] = {
648 string("\x80"), // VARINT
649 string("abcdefg"), // 64BIT
650 string("\x80"), // DELIMITED (partial length)
651 string(), // START_GROUP (no value required)
652 string(), // END_GROUP (no value required)
653 string("abc") // 32BIT
654 };
655
656 const FieldDescriptor* field = GetFieldForType(type, false, true);
657 const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
658 WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
659 static_cast<WireFormatLite::FieldType>(type));
660 const string& incomplete = incompletes[wire_type];
661 const string type_name =
662 UpperCase(string(".") + FieldDescriptor::TypeName(type));
663
664 ExpectParseFailureForProto(
665 tag(field->number(), wire_type),
666 "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
667
668 ExpectParseFailureForProto(
669 tag(rep_field->number(), wire_type),
670 "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
671
672 ExpectParseFailureForProto(
673 tag(UNKNOWN_FIELD, wire_type),
674 "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
675
676 ExpectParseFailureForProto(
677 cat( tag(field->number(), wire_type), incomplete ),
678 "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
679
680 ExpectParseFailureForProto(
681 cat( tag(rep_field->number(), wire_type), incomplete ),
682 "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
683
684 ExpectParseFailureForProto(
685 cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
686 "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
687
688 if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
689 ExpectParseFailureForProto(
690 cat( tag(field->number(), wire_type), varint(1) ),
691 "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
692 REQUIRED);
693
694 ExpectParseFailureForProto(
695 cat( tag(rep_field->number(), wire_type), varint(1) ),
696 "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
697 REQUIRED);
698
699 // EOF in the middle of delimited data for unknown value.
700 ExpectParseFailureForProto(
701 cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
702 "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
703
704 if (type == FieldDescriptor::TYPE_MESSAGE) {
705 // Submessage ends in the middle of a value.
706 string incomplete_submsg =
707 cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
708 incompletes[WireFormatLite::WIRETYPE_VARINT] );
709 ExpectHardParseFailureForProto(
710 cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
711 varint(incomplete_submsg.size()),
712 incomplete_submsg ),
713 "PrematureEofInSubmessageValue" + type_name, REQUIRED);
714 }
715 } else if (type != FieldDescriptor::TYPE_GROUP) {
716 // Non-delimited, non-group: eligible for packing.
717
718 // Packed region ends in the middle of a value.
719 ExpectHardParseFailureForProto(
720 cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
721 varint(incomplete.size()), incomplete),
722 "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
723
724 // EOF in the middle of packed region.
725 ExpectParseFailureForProto(
726 cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
727 varint(1)),
728 "PrematureEofInPackedField" + type_name, REQUIRED);
729 }
730}
731
Paul Yangcecba292018-12-14 16:05:03 -0800732void BinaryAndJsonConformanceSuite::TestValidDataForType(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700733 FieldDescriptor::Type type,
734 std::vector<std::pair<std::string, std::string>> values) {
735 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
736 const string type_name =
737 UpperCase(string(".") + FieldDescriptor::TypeName(type));
738 WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
739 static_cast<WireFormatLite::FieldType>(type));
740 const FieldDescriptor* field = GetFieldForType(type, false, is_proto3);
741 const FieldDescriptor* rep_field = GetFieldForType(type, true, is_proto3);
742
Paul Yanga9bb6562019-07-26 10:05:14 -0700743 // Test singular data for singular fields.
Paul Yang2849a792019-07-24 12:26:40 -0700744 for (size_t i = 0; i < values.size(); i++) {
Rafi Kamal4f02f052019-08-22 16:14:22 -0700745 string proto = cat(tag(field->number(), wire_type), values[i].first);
Paul Yang6c9d7ec2019-08-23 12:20:19 -0700746 // In proto3, default primitive fields should not be encoded.
Paul Yanga9bb6562019-07-26 10:05:14 -0700747 string expected_proto =
Paul Yang6c9d7ec2019-08-23 12:20:19 -0700748 is_proto3 && IsProto3Default(field->type(), values[i].second) ?
749 "" :
750 cat(tag(field->number(), wire_type), values[i].second);
Paul Yanga9bb6562019-07-26 10:05:14 -0700751 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
752 test_message->MergeFromString(expected_proto);
753 string text = test_message->DebugString();
754
Paul Yang2849a792019-07-24 12:26:40 -0700755 RunValidProtobufTest(StrCat("ValidDataScalar", type_name, "[", i, "]"),
Paul Yanga9bb6562019-07-26 10:05:14 -0700756 REQUIRED, proto, text, is_proto3);
Paul Yang6c9d7ec2019-08-23 12:20:19 -0700757 RunValidBinaryProtobufTest(
758 StrCat("ValidDataScalarBinary", type_name, "[", i, "]"),
759 RECOMMENDED,
760 proto,
761 expected_proto, is_proto3);
Paul Yang2849a792019-07-24 12:26:40 -0700762 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700763
Paul Yanga9bb6562019-07-26 10:05:14 -0700764 // Test repeated data for singular fields.
Paul Yang2849a792019-07-24 12:26:40 -0700765 // For scalar message fields, repeated values are merged, which is tested
766 // separately.
767 if (type != FieldDescriptor::TYPE_MESSAGE) {
Paul Yanga9bb6562019-07-26 10:05:14 -0700768 string proto;
769 for (size_t i = 0; i < values.size(); i++) {
770 proto += cat(tag(field->number(), wire_type), values[i].first);
771 }
772 string expected_proto =
773 cat(tag(field->number(), wire_type), values.back().second);
774 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
775 test_message->MergeFromString(expected_proto);
776 string text = test_message->DebugString();
777
Paul Yang2849a792019-07-24 12:26:40 -0700778 RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
779 proto, text, is_proto3);
780 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700781
Paul Yanga9bb6562019-07-26 10:05:14 -0700782 // Test repeated fields.
783 if (FieldDescriptor::IsTypePackable(type)) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700784 const FieldDescriptor* packed_field =
785 GetFieldForType(type, true, is_proto3, Packed::TRUE);
786 const FieldDescriptor* unpacked_field =
787 GetFieldForType(type, true, is_proto3, Packed::FALSE);
788
789 string default_proto_packed;
790 string default_proto_unpacked;
791 string default_proto_packed_expected;
792 string default_proto_unpacked_expected;
793 string packed_proto_packed;
794 string packed_proto_unpacked;
Paul Yanga9bb6562019-07-26 10:05:14 -0700795 string packed_proto_expected;
Paul Yang0c4b6072019-08-02 14:35:44 -0700796 string unpacked_proto_packed;
797 string unpacked_proto_unpacked;
Paul Yanga9bb6562019-07-26 10:05:14 -0700798 string unpacked_proto_expected;
Feng Xiao6bbe1972018-08-08 17:00:41 -0700799
Paul Yanga9bb6562019-07-26 10:05:14 -0700800 for (size_t i = 0; i < values.size(); i++) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700801 default_proto_unpacked +=
Paul Yanga9bb6562019-07-26 10:05:14 -0700802 cat(tag(rep_field->number(), wire_type), values[i].first);
Paul Yang0c4b6072019-08-02 14:35:44 -0700803 default_proto_unpacked_expected +=
Paul Yanga9bb6562019-07-26 10:05:14 -0700804 cat(tag(rep_field->number(), wire_type), values[i].second);
Paul Yang0c4b6072019-08-02 14:35:44 -0700805 default_proto_packed += values[i].first;
806 default_proto_packed_expected += values[i].second;
807 packed_proto_unpacked +=
808 cat(tag(packed_field->number(), wire_type), values[i].first);
809 packed_proto_packed += values[i].first;
Paul Yanga9bb6562019-07-26 10:05:14 -0700810 packed_proto_expected += values[i].second;
Paul Yang0c4b6072019-08-02 14:35:44 -0700811 unpacked_proto_unpacked +=
812 cat(tag(unpacked_field->number(), wire_type), values[i].first);
813 unpacked_proto_packed += values[i].first;
814 unpacked_proto_expected +=
815 cat(tag(unpacked_field->number(), wire_type), values[i].second);
Paul Yanga9bb6562019-07-26 10:05:14 -0700816 }
Rafi Kamal4f02f052019-08-22 16:14:22 -0700817 default_proto_packed = cat(
818 tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
819 delim(default_proto_packed));
820 default_proto_packed_expected = cat(
821 tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
822 delim(default_proto_packed_expected));
823 packed_proto_packed = cat(tag(packed_field->number(),
824 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
825 delim(packed_proto_packed));
Paul Yang0c4b6072019-08-02 14:35:44 -0700826 packed_proto_expected =
827 cat(tag(packed_field->number(),
828 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
Paul Yanga9bb6562019-07-26 10:05:14 -0700829 delim(packed_proto_expected));
Paul Yang0c4b6072019-08-02 14:35:44 -0700830 unpacked_proto_packed =
831 cat(tag(unpacked_field->number(),
832 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
833 delim(unpacked_proto_packed));
834
Paul Yanga9bb6562019-07-26 10:05:14 -0700835 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
Paul Yang0c4b6072019-08-02 14:35:44 -0700836 test_message->MergeFromString(default_proto_packed_expected);
Paul Yanga9bb6562019-07-26 10:05:14 -0700837 string text = test_message->DebugString();
838
839 // Ensures both packed and unpacked data can be parsed.
840 RunValidProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700841 StrCat("ValidDataRepeated", type_name, ".UnpackedInput"), REQUIRED,
842 default_proto_unpacked, text, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700843 RunValidProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700844 StrCat("ValidDataRepeated", type_name, ".PackedInput"), REQUIRED,
845 default_proto_packed, text, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700846
847 // proto2 should encode as unpacked by default and proto3 should encode as
848 // packed by default.
Rafi Kamal4f02f052019-08-22 16:14:22 -0700849 string expected_proto = rep_field->is_packed()
850 ? default_proto_packed_expected
851 : default_proto_unpacked_expected;
852 RunValidBinaryProtobufTest(StrCat("ValidDataRepeated", type_name,
853 ".UnpackedInput.DefaultOutput"),
854 RECOMMENDED, default_proto_unpacked,
855 expected_proto, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700856 RunValidBinaryProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700857 StrCat("ValidDataRepeated", type_name, ".PackedInput.DefaultOutput"),
858 RECOMMENDED, default_proto_packed, expected_proto, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700859 RunValidBinaryProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700860 StrCat("ValidDataRepeated", type_name, ".UnpackedInput.PackedOutput"),
861 RECOMMENDED, packed_proto_unpacked, packed_proto_expected, is_proto3);
Paul Yang0c4b6072019-08-02 14:35:44 -0700862 RunValidBinaryProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700863 StrCat("ValidDataRepeated", type_name, ".PackedInput.PackedOutput"),
864 RECOMMENDED, packed_proto_packed, packed_proto_expected, is_proto3);
865 RunValidBinaryProtobufTest(StrCat("ValidDataRepeated", type_name,
866 ".UnpackedInput.UnpackedOutput"),
867 RECOMMENDED, unpacked_proto_unpacked,
868 unpacked_proto_expected, is_proto3);
Paul Yang0c4b6072019-08-02 14:35:44 -0700869 RunValidBinaryProtobufTest(
Rafi Kamal4f02f052019-08-22 16:14:22 -0700870 StrCat("ValidDataRepeated", type_name, ".PackedInput.UnpackedOutput"),
871 RECOMMENDED, unpacked_proto_packed, unpacked_proto_expected,
872 is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700873 } else {
874 string proto;
875 string expected_proto;
876 for (size_t i = 0; i < values.size(); i++) {
877 proto += cat(tag(rep_field->number(), wire_type), values[i].first);
878 expected_proto +=
879 cat(tag(rep_field->number(), wire_type), values[i].second);
880 }
881 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
882 test_message->MergeFromString(expected_proto);
883 string text = test_message->DebugString();
884
Rafi Kamal4f02f052019-08-22 16:14:22 -0700885 RunValidProtobufTest(StrCat("ValidDataRepeated", type_name), REQUIRED,
886 proto, text, is_proto3);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700887 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700888 }
889}
890
Paul Yang2849a792019-07-24 12:26:40 -0700891void BinaryAndJsonConformanceSuite::TestValidDataForRepeatedScalarMessage() {
892 std::vector<std::string> values = {
Rafi Kamal4f02f052019-08-22 16:14:22 -0700893 delim(cat(
894 tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
895 delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234),
Paul Yang2849a792019-07-24 12:26:40 -0700896 tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1234),
Rafi Kamal4f02f052019-08-22 16:14:22 -0700897 tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1234))))),
898 delim(cat(
899 tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
900 delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(4321),
Paul Yang2849a792019-07-24 12:26:40 -0700901 tag(3, WireFormatLite::WIRETYPE_VARINT), varint(4321),
Rafi Kamal4f02f052019-08-22 16:14:22 -0700902 tag(31, WireFormatLite::WIRETYPE_VARINT), varint(4321))))),
Paul Yang2849a792019-07-24 12:26:40 -0700903 };
904
905 const std::string expected =
906 R"({
907 corecursive: {
908 optional_int32: 4321,
909 optional_int64: 1234,
910 optional_uint32: 4321,
911 repeated_int32: [1234, 4321],
912 }
913 })";
914
915 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
916 string proto;
917 const FieldDescriptor* field =
918 GetFieldForType(FieldDescriptor::TYPE_MESSAGE, false, is_proto3);
919 for (size_t i = 0; i < values.size(); i++) {
920 proto +=
921 cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
922 values[i]);
923 }
924
Rafi Kamal4f02f052019-08-22 16:14:22 -0700925 RunValidProtobufTest("RepeatedScalarMessageMerge", REQUIRED, proto,
926 field->name() + ": " + expected, is_proto3);
Paul Yang2849a792019-07-24 12:26:40 -0700927 }
928}
929
Paul Yangce942bc2019-09-03 10:47:32 -0700930void BinaryAndJsonConformanceSuite::TestValidDataForMapType(
931 FieldDescriptor::Type key_type,
932 FieldDescriptor::Type value_type) {
933 const string key_type_name =
934 UpperCase(string(".") + FieldDescriptor::TypeName(key_type));
935 const string value_type_name =
936 UpperCase(string(".") + FieldDescriptor::TypeName(value_type));
937 WireFormatLite::WireType key_wire_type =
938 WireFormatLite::WireTypeForFieldType(
939 static_cast<WireFormatLite::FieldType>(key_type));
940 WireFormatLite::WireType value_wire_type =
941 WireFormatLite::WireTypeForFieldType(
942 static_cast<WireFormatLite::FieldType>(value_type));
943
944 string key1_data =
945 cat(tag(1, key_wire_type), GetDefaultValue(key_type));
946 string value1_data =
947 cat(tag(2, value_wire_type), GetDefaultValue(value_type));
948 string key2_data =
949 cat(tag(1, key_wire_type), GetNonDefaultValue(key_type));
950 string value2_data =
951 cat(tag(2, value_wire_type), GetNonDefaultValue(value_type));
952
953 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
954 const FieldDescriptor* field =
955 GetFieldForMapType(key_type, value_type, is_proto3);
956
957 {
958 // Tests map with default key and value.
959 string proto = cat(tag(field->number(),
960 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
961 delim(cat(key1_data, value1_data)));
962 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
963 test_message->MergeFromString(proto);
964 string text = test_message->DebugString();
965 RunValidProtobufTest(
966 StrCat("ValidDataMap",
967 key_type_name,
968 value_type_name,
969 ".Default"),
970 REQUIRED, proto, text, is_proto3);
971 }
972
973 {
974 // Tests map with missing default key and value.
975 string proto = cat(tag(field->number(),
976 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
977 delim(""));
978 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
979 test_message->MergeFromString(proto);
980 string text = test_message->DebugString();
981 RunValidProtobufTest(
982 StrCat("ValidDataMap",
983 key_type_name,
984 value_type_name,
985 ".MissingDefault"),
986 REQUIRED, proto, text, is_proto3);
987 }
988
989 {
990 // Tests map with non-default key and value.
991 string proto = cat(tag(field->number(),
992 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
993 delim(cat(key2_data, value2_data)));
994 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
995 test_message->MergeFromString(proto);
996 string text = test_message->DebugString();
997 RunValidProtobufTest(
998 StrCat("ValidDataMap",
999 key_type_name,
1000 value_type_name,
1001 ".NonDefault"),
1002 REQUIRED, proto, text, is_proto3);
1003 }
1004
1005 {
1006 // Tests map with unordered key and value.
1007 string proto = cat(tag(field->number(),
1008 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1009 delim(cat(value2_data, key2_data)));
1010 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
1011 test_message->MergeFromString(proto);
1012 string text = test_message->DebugString();
1013 RunValidProtobufTest(
1014 StrCat("ValidDataMap",
1015 key_type_name,
1016 value_type_name,
1017 ".Unordered"),
1018 REQUIRED, proto, text, is_proto3);
1019 }
1020
1021 {
1022 // Tests map with duplicate key.
1023 string proto1 = cat(tag(field->number(),
1024 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1025 delim(cat(key2_data, value1_data)));
1026 string proto2 = cat(tag(field->number(),
1027 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1028 delim(cat(key2_data, value2_data)));
1029 string proto = cat(proto1, proto2);
1030 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
1031 test_message->MergeFromString(proto2);
1032 string text = test_message->DebugString();
1033 RunValidProtobufTest(
1034 StrCat("ValidDataMap",
1035 key_type_name,
1036 value_type_name,
1037 ".DuplicateKey"),
1038 REQUIRED, proto, text, is_proto3);
1039 }
1040
1041 {
1042 // Tests map with duplicate key in map entry.
1043 string proto = cat(tag(field->number(),
1044 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1045 delim(cat(key1_data, key2_data, value2_data)));
1046 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
1047 test_message->MergeFromString(proto);
1048 string text = test_message->DebugString();
1049 RunValidProtobufTest(
1050 StrCat("ValidDataMap",
1051 key_type_name,
1052 value_type_name,
1053 ".DuplicateKeyInMapEntry"),
1054 REQUIRED, proto, text, is_proto3);
1055 }
1056
1057 {
1058 // Tests map with duplicate value in map entry.
1059 string proto = cat(tag(field->number(),
1060 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1061 delim(cat(key2_data, value1_data, value2_data)));
1062 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
1063 test_message->MergeFromString(proto);
1064 string text = test_message->DebugString();
1065 RunValidProtobufTest(
1066 StrCat("ValidDataMap",
1067 key_type_name,
1068 value_type_name,
1069 ".DuplicateValueInMapEntry"),
1070 REQUIRED, proto, text, is_proto3);
1071 }
1072 }
1073}
1074
1075void BinaryAndJsonConformanceSuite::TestOverwriteMessageValueMap() {
1076 string key_data =
1077 cat(tag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(""));
1078 string field1_data = cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1));
1079 string field2_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1));
1080 string field31_data = cat(tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1));
1081 string submsg1_data = delim(cat(field1_data, field31_data));
1082 string submsg2_data = delim(cat(field2_data, field31_data));
1083 string value1_data =
1084 cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1085 delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1086 submsg1_data)));
1087 string value2_data =
1088 cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1089 delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1090 submsg2_data)));
1091
1092 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
1093 const FieldDescriptor* field =
1094 GetFieldForMapType(
1095 FieldDescriptor::TYPE_STRING,
1096 FieldDescriptor::TYPE_MESSAGE, is_proto3);
1097
1098 string proto1 = cat(tag(field->number(),
1099 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1100 delim(cat(key_data, value1_data)));
1101 string proto2 = cat(tag(field->number(),
1102 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
1103 delim(cat(key_data, value2_data)));
1104 string proto = cat(proto1, proto2);
1105 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
1106 test_message->MergeFromString(proto2);
1107 string text = test_message->DebugString();
1108 RunValidProtobufTest(
1109 "ValidDataMap.STRING.MESSAGE.MergeValue",
1110 REQUIRED, proto, text, is_proto3);
1111 }
1112}
1113
Paul Yangcecba292018-12-14 16:05:03 -08001114void BinaryAndJsonConformanceSuite::TestIllegalTags() {
Feng Xiao6bbe1972018-08-08 17:00:41 -07001115 // field num 0 is illegal
1116 string nullfield[] = {
1117 "\1DEADBEEF",
1118 "\2\1\1",
1119 "\3\4",
1120 "\5DEAD"
1121 };
1122 for (int i = 0; i < 4; i++) {
1123 string name = "IllegalZeroFieldNum_Case_0";
1124 name.back() += i;
1125 ExpectParseFailureForProto(nullfield[i], name, REQUIRED);
1126 }
1127}
1128template <class MessageType>
Paul Yangcecba292018-12-14 16:05:03 -08001129void BinaryAndJsonConformanceSuite::TestOneofMessage (
Feng Xiao6bbe1972018-08-08 17:00:41 -07001130 MessageType &message, bool is_proto3) {
1131 message.set_oneof_uint32(0);
1132 RunValidProtobufTestWithMessage(
1133 "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3);
1134 message.mutable_oneof_nested_message()->set_a(0);
1135 RunValidProtobufTestWithMessage(
1136 "OneofZeroMessage", RECOMMENDED, &message,
1137 is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
1138 is_proto3);
1139 message.mutable_oneof_nested_message()->set_a(1);
1140 RunValidProtobufTestWithMessage(
1141 "OneofZeroMessageSetTwice", RECOMMENDED, &message,
1142 "oneof_nested_message: {a: 1}",
1143 is_proto3);
1144 message.set_oneof_string("");
1145 RunValidProtobufTestWithMessage(
1146 "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3);
1147 message.set_oneof_bytes("");
1148 RunValidProtobufTestWithMessage(
1149 "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3);
1150 message.set_oneof_bool(false);
1151 RunValidProtobufTestWithMessage(
1152 "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3);
1153 message.set_oneof_uint64(0);
1154 RunValidProtobufTestWithMessage(
1155 "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3);
1156 message.set_oneof_float(0.0f);
1157 RunValidProtobufTestWithMessage(
1158 "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3);
1159 message.set_oneof_double(0.0);
1160 RunValidProtobufTestWithMessage(
1161 "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3);
1162 message.set_oneof_enum(MessageType::FOO);
1163 RunValidProtobufTestWithMessage(
1164 "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3);
1165}
1166
1167template <class MessageType>
Paul Yangcecba292018-12-14 16:05:03 -08001168void BinaryAndJsonConformanceSuite::TestUnknownMessage(
Feng Xiao6bbe1972018-08-08 17:00:41 -07001169 MessageType& message, bool is_proto3) {
1170 message.ParseFromString("\xA8\x1F\x01");
1171 RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
1172 message.SerializeAsString(), is_proto3);
1173}
1174
Paul Yangcecba292018-12-14 16:05:03 -08001175void BinaryAndJsonConformanceSuite::RunSuiteImpl() {
Yilun Chongd8c25012019-02-22 18:13:33 +08001176 // Hack to get the list of test failures based on whether
1177 // GOOGLE3_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER is enabled or not.
1178 conformance::FailureSet failure_set;
1179 ConformanceRequest req;
1180 ConformanceResponse res;
1181 req.set_message_type(failure_set.GetTypeName());
1182 req.set_protobuf_payload("");
1183 req.set_requested_output_format(conformance::WireFormat::PROTOBUF);
1184 RunTest("FindFailures", req, &res);
1185 GOOGLE_CHECK(failure_set.MergeFromString(res.protobuf_payload()));
1186 for (const string& failure : failure_set.failure()) {
1187 AddExpectedFailedTest(failure);
1188 }
1189
Feng Xiao6bbe1972018-08-08 17:00:41 -07001190 type_resolver_.reset(NewTypeResolverForDescriptorPool(
1191 kTypeUrlPrefix, DescriptorPool::generated_pool()));
1192 type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
1193
1194 for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
1195 if (i == FieldDescriptor::TYPE_GROUP) continue;
1196 TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
1197 }
1198
1199 TestIllegalTags();
1200
1201 int64 kInt64Min = -9223372036854775808ULL;
1202 int64 kInt64Max = 9223372036854775807ULL;
1203 uint64 kUint64Max = 18446744073709551615ULL;
1204 int32 kInt32Max = 2147483647;
1205 int32 kInt32Min = -2147483648;
1206 uint32 kUint32Max = 4294967295UL;
1207
Paul Yang6c9d7ec2019-08-23 12:20:19 -07001208 TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
1209 {dbl(0), dbl(0)},
1210 {dbl(0.1), dbl(0.1)},
1211 {dbl(1.7976931348623157e+308), dbl(1.7976931348623157e+308)},
1212 {dbl(2.22507385850720138309e-308), dbl(2.22507385850720138309e-308)},
1213 });
1214 TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
1215 {flt(0), flt(0)},
1216 {flt(0.1), flt(0.1)},
1217 {flt(1.00000075e-36), flt(1.00000075e-36)},
1218 {flt(3.402823e+38), flt(3.402823e+38)}, // 3.40282347e+38
1219 {flt(1.17549435e-38f), flt(1.17549435e-38)},
1220 });
1221 TestValidDataForType(FieldDescriptor::TYPE_INT64, {
1222 {varint(0), varint(0)},
1223 {varint(12345), varint(12345)},
1224 {varint(kInt64Max), varint(kInt64Max)},
1225 {varint(kInt64Min), varint(kInt64Min)},
1226 });
1227 TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
1228 {varint(0), varint(0)},
1229 {varint(12345), varint(12345)},
1230 {varint(kUint64Max), varint(kUint64Max)},
1231 });
1232 TestValidDataForType(FieldDescriptor::TYPE_INT32, {
1233 {varint(0), varint(0)},
1234 {varint(12345), varint(12345)},
1235 {longvarint(12345, 2), varint(12345)},
1236 {longvarint(12345, 7), varint(12345)},
1237 {varint(kInt32Max), varint(kInt32Max)},
1238 {varint(kInt32Min), varint(kInt32Min)},
1239 {varint(1LL << 33), varint(0)},
1240 {varint((1LL << 33) - 1), varint(-1)},
1241 });
1242 TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
1243 {varint(0), varint(0)},
1244 {varint(12345), varint(12345)},
1245 {longvarint(12345, 2), varint(12345)},
1246 {longvarint(12345, 7), varint(12345)},
1247 {varint(kUint32Max), varint(kUint32Max)}, // UINT32_MAX
1248 {varint(1LL << 33), varint(0)},
1249 {varint((1LL << 33) - 1), varint((1LL << 32) - 1)},
1250 });
1251 TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
1252 {u64(0), u64(0)},
1253 {u64(12345), u64(12345)},
1254 {u64(kUint64Max), u64(kUint64Max)},
1255 });
1256 TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
1257 {u32(0), u32(0)},
1258 {u32(12345), u32(12345)},
1259 {u32(kUint32Max), u32(kUint32Max)}, // UINT32_MAX
1260 });
1261 TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
1262 {u64(0), u64(0)},
1263 {u64(12345), u64(12345)},
1264 {u64(kInt64Max), u64(kInt64Max)},
1265 {u64(kInt64Min), u64(kInt64Min)},
1266 });
1267 TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
1268 {u32(0), u32(0)},
1269 {u32(12345), u32(12345)},
1270 {u32(kInt32Max), u32(kInt32Max)},
1271 {u32(kInt32Min), u32(kInt32Min)},
1272 });
1273 TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
1274 {varint(0), varint(0)},
1275 {varint(1), varint(1)},
1276 {varint(12345678), varint(1)},
1277 });
1278 TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
1279 {zz32(0), zz32(0)},
1280 {zz32(12345), zz32(12345)},
1281 {zz32(kInt32Max), zz32(kInt32Max)},
1282 {zz32(kInt32Min), zz32(kInt32Min)},
1283 });
1284 TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
1285 {zz64(0), zz64(0)},
1286 {zz64(12345), zz64(12345)},
1287 {zz64(kInt64Max), zz64(kInt64Max)},
1288 {zz64(kInt64Min), zz64(kInt64Min)},
1289 });
1290 TestValidDataForType(FieldDescriptor::TYPE_STRING, {
1291 {delim(""), delim("")},
1292 {delim("Hello world!"), delim("Hello world!")},
1293 {delim("\'\"\?\\\a\b\f\n\r\t\v"),
1294 delim("\'\"\?\\\a\b\f\n\r\t\v")}, // escape
1295 {delim("谷歌"), delim("谷歌")}, // Google in Chinese
1296 {delim("\u8C37\u6B4C"), delim("谷歌")}, // unicode escape
1297 {delim("\u8c37\u6b4c"), delim("谷歌")}, // lowercase unicode
1298 {delim("\xF0\x9F\x98\x81"), delim("\xF0\x9F\x98\x81")}, // emoji: 😁
1299 });
1300 TestValidDataForType(FieldDescriptor::TYPE_BYTES, {
1301 {delim(""), delim("")},
1302 {delim("\x01\x02"), delim("\x01\x02")},
1303 {delim("\xfb"), delim("\xfb")},
1304 });
Paul Yang455440f2019-07-23 15:07:26 -07001305 TestValidDataForType(FieldDescriptor::TYPE_ENUM, {
Rafi Kamal4f02f052019-08-22 16:14:22 -07001306 {varint(0), varint(0)},
1307 {varint(1), varint(1)},
1308 {varint(2), varint(2)},
1309 {varint(-1), varint(-1)},
1310 });
Paul Yang2849a792019-07-24 12:26:40 -07001311 TestValidDataForRepeatedScalarMessage();
Paul Yang6c9d7ec2019-08-23 12:20:19 -07001312 TestValidDataForType(FieldDescriptor::TYPE_MESSAGE, {
1313 {delim(""), delim("")},
1314 {delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))),
1315 delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)))},
1316 });
Feng Xiao6bbe1972018-08-08 17:00:41 -07001317
Paul Yangce942bc2019-09-03 10:47:32 -07001318 TestValidDataForMapType(
1319 FieldDescriptor::TYPE_INT32,
1320 FieldDescriptor::TYPE_INT32);
1321 TestValidDataForMapType(
1322 FieldDescriptor::TYPE_INT64,
1323 FieldDescriptor::TYPE_INT64);
1324 TestValidDataForMapType(
1325 FieldDescriptor::TYPE_UINT32,
1326 FieldDescriptor::TYPE_UINT32);
1327 TestValidDataForMapType(
1328 FieldDescriptor::TYPE_UINT64,
1329 FieldDescriptor::TYPE_UINT64);
1330 TestValidDataForMapType(
1331 FieldDescriptor::TYPE_SINT32,
1332 FieldDescriptor::TYPE_SINT32);
1333 TestValidDataForMapType(
1334 FieldDescriptor::TYPE_SINT64,
1335 FieldDescriptor::TYPE_SINT64);
1336 TestValidDataForMapType(
1337 FieldDescriptor::TYPE_FIXED32,
1338 FieldDescriptor::TYPE_FIXED32);
1339 TestValidDataForMapType(
1340 FieldDescriptor::TYPE_FIXED64,
1341 FieldDescriptor::TYPE_FIXED64);
1342 TestValidDataForMapType(
1343 FieldDescriptor::TYPE_SFIXED32,
1344 FieldDescriptor::TYPE_SFIXED32);
1345 TestValidDataForMapType(
1346 FieldDescriptor::TYPE_SFIXED64,
1347 FieldDescriptor::TYPE_SFIXED64);
1348 TestValidDataForMapType(
1349 FieldDescriptor::TYPE_INT32,
1350 FieldDescriptor::TYPE_FLOAT);
1351 TestValidDataForMapType(
1352 FieldDescriptor::TYPE_INT32,
1353 FieldDescriptor::TYPE_DOUBLE);
1354 TestValidDataForMapType(
1355 FieldDescriptor::TYPE_BOOL,
1356 FieldDescriptor::TYPE_BOOL);
1357 TestValidDataForMapType(
1358 FieldDescriptor::TYPE_STRING,
1359 FieldDescriptor::TYPE_STRING);
1360 TestValidDataForMapType(
1361 FieldDescriptor::TYPE_STRING,
1362 FieldDescriptor::TYPE_BYTES);
1363 TestValidDataForMapType(
1364 FieldDescriptor::TYPE_STRING,
1365 FieldDescriptor::TYPE_ENUM);
1366 TestValidDataForMapType(
1367 FieldDescriptor::TYPE_STRING,
1368 FieldDescriptor::TYPE_MESSAGE);
1369 // Additional test to check overwriting message value map.
1370 TestOverwriteMessageValueMap();
1371
Feng Xiao6bbe1972018-08-08 17:00:41 -07001372 // TODO(haberman):
Feng Xiao6bbe1972018-08-08 17:00:41 -07001373 // TestValidDataForType(FieldDescriptor::TYPE_GROUP
Feng Xiao6bbe1972018-08-08 17:00:41 -07001374
1375 RunValidJsonTest("HelloWorld", REQUIRED,
1376 "{\"optionalString\":\"Hello, World!\"}",
1377 "optional_string: 'Hello, World!'");
1378
1379 // NOTE: The spec for JSON support is still being sorted out, these may not
1380 // all be correct.
1381 // Test field name conventions.
1382 RunValidJsonTest(
1383 "FieldNameInSnakeCase", REQUIRED,
1384 R"({
1385 "fieldname1": 1,
1386 "fieldName2": 2,
1387 "FieldName3": 3,
1388 "fieldName4": 4
1389 })",
1390 R"(
1391 fieldname1: 1
1392 field_name2: 2
1393 _field_name3: 3
1394 field__name4_: 4
1395 )");
1396 RunValidJsonTest(
1397 "FieldNameWithNumbers", REQUIRED,
1398 R"({
1399 "field0name5": 5,
1400 "field0Name6": 6
1401 })",
1402 R"(
1403 field0name5: 5
1404 field_0_name6: 6
1405 )");
1406 RunValidJsonTest(
1407 "FieldNameWithMixedCases", REQUIRED,
1408 R"({
1409 "fieldName7": 7,
1410 "FieldName8": 8,
1411 "fieldName9": 9,
1412 "FieldName10": 10,
1413 "FIELDNAME11": 11,
1414 "FIELDName12": 12
1415 })",
1416 R"(
1417 fieldName7: 7
1418 FieldName8: 8
1419 field_Name9: 9
1420 Field_Name10: 10
1421 FIELD_NAME11: 11
1422 FIELD_name12: 12
1423 )");
1424 RunValidJsonTest(
1425 "FieldNameWithDoubleUnderscores", RECOMMENDED,
1426 R"({
1427 "FieldName13": 13,
1428 "FieldName14": 14,
1429 "fieldName15": 15,
1430 "fieldName16": 16,
1431 "fieldName17": 17,
1432 "FieldName18": 18
1433 })",
1434 R"(
1435 __field_name13: 13
1436 __Field_name14: 14
1437 field__name15: 15
1438 field__Name16: 16
1439 field_name17__: 17
1440 Field_name18__: 18
1441 )");
1442 // Using the original proto field name in JSON is also allowed.
1443 RunValidJsonTest(
1444 "OriginalProtoFieldName", REQUIRED,
1445 R"({
1446 "fieldname1": 1,
1447 "field_name2": 2,
1448 "_field_name3": 3,
1449 "field__name4_": 4,
1450 "field0name5": 5,
1451 "field_0_name6": 6,
1452 "fieldName7": 7,
1453 "FieldName8": 8,
1454 "field_Name9": 9,
1455 "Field_Name10": 10,
1456 "FIELD_NAME11": 11,
1457 "FIELD_name12": 12,
1458 "__field_name13": 13,
1459 "__Field_name14": 14,
1460 "field__name15": 15,
1461 "field__Name16": 16,
1462 "field_name17__": 17,
1463 "Field_name18__": 18
1464 })",
1465 R"(
1466 fieldname1: 1
1467 field_name2: 2
1468 _field_name3: 3
1469 field__name4_: 4
1470 field0name5: 5
1471 field_0_name6: 6
1472 fieldName7: 7
1473 FieldName8: 8
1474 field_Name9: 9
1475 Field_Name10: 10
1476 FIELD_NAME11: 11
1477 FIELD_name12: 12
1478 __field_name13: 13
1479 __Field_name14: 14
1480 field__name15: 15
1481 field__Name16: 16
1482 field_name17__: 17
1483 Field_name18__: 18
1484 )");
1485 // Field names can be escaped.
1486 RunValidJsonTest(
1487 "FieldNameEscaped", REQUIRED,
1488 R"({"fieldn\u0061me1": 1})",
1489 "fieldname1: 1");
1490 // String ends with escape character.
1491 ExpectParseFailureForJson(
1492 "StringEndsWithEscapeChar", RECOMMENDED,
1493 "{\"optionalString\": \"abc\\");
1494 // Field names must be quoted (or it's not valid JSON).
1495 ExpectParseFailureForJson(
1496 "FieldNameNotQuoted", RECOMMENDED,
1497 "{fieldname1: 1}");
1498 // Trailing comma is not allowed (not valid JSON).
1499 ExpectParseFailureForJson(
1500 "TrailingCommaInAnObject", RECOMMENDED,
1501 R"({"fieldname1":1,})");
1502 ExpectParseFailureForJson(
1503 "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
1504 R"({"fieldname1":1 ,})");
1505 ExpectParseFailureForJson(
1506 "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
1507 R"({"fieldname1":1 , })");
1508 ExpectParseFailureForJson(
1509 "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
1510 R"({
1511 "fieldname1":1,
1512 })");
1513 // JSON doesn't support comments.
1514 ExpectParseFailureForJson(
1515 "JsonWithComments", RECOMMENDED,
1516 R"({
1517 // This is a comment.
1518 "fieldname1": 1
1519 })");
1520 // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
1521 RunValidJsonTest(
1522 "OneLineNoSpaces", RECOMMENDED,
1523 "{\"optionalInt32\":1,\"optionalInt64\":2}",
1524 R"(
1525 optional_int32: 1
1526 optional_int64: 2
1527 )");
1528 RunValidJsonTest(
1529 "OneLineWithSpaces", RECOMMENDED,
1530 "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
1531 R"(
1532 optional_int32: 1
1533 optional_int64: 2
1534 )");
1535 RunValidJsonTest(
1536 "MultilineNoSpaces", RECOMMENDED,
1537 "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
1538 R"(
1539 optional_int32: 1
1540 optional_int64: 2
1541 )");
1542 RunValidJsonTest(
1543 "MultilineWithSpaces", RECOMMENDED,
1544 "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
1545 R"(
1546 optional_int32: 1
1547 optional_int64: 2
1548 )");
1549 // Missing comma between key/value pairs.
1550 ExpectParseFailureForJson(
1551 "MissingCommaOneLine", RECOMMENDED,
1552 "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
1553 ExpectParseFailureForJson(
1554 "MissingCommaMultiline", RECOMMENDED,
1555 "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
1556 // Duplicated field names are not allowed.
1557 ExpectParseFailureForJson(
1558 "FieldNameDuplicate", RECOMMENDED,
1559 R"({
1560 "optionalNestedMessage": {a: 1},
1561 "optionalNestedMessage": {}
1562 })");
1563 ExpectParseFailureForJson(
1564 "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
1565 R"({
1566 "optional_nested_message": {a: 1},
1567 "optionalNestedMessage": {}
1568 })");
1569 ExpectParseFailureForJson(
1570 "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
1571 R"({
1572 "optionalNestedMessage": {a: 1},
1573 "optional_nested_message": {}
1574 })");
1575 // Serializers should use lowerCamelCase by default.
1576 RunValidJsonTestWithValidator(
1577 "FieldNameInLowerCamelCase", REQUIRED,
1578 R"({
1579 "fieldname1": 1,
1580 "fieldName2": 2,
1581 "FieldName3": 3,
1582 "fieldName4": 4
1583 })",
1584 [](const Json::Value& value) {
1585 return value.isMember("fieldname1") &&
1586 value.isMember("fieldName2") &&
1587 value.isMember("FieldName3") &&
1588 value.isMember("fieldName4");
1589 });
1590 RunValidJsonTestWithValidator(
1591 "FieldNameWithNumbers", REQUIRED,
1592 R"({
1593 "field0name5": 5,
1594 "field0Name6": 6
1595 })",
1596 [](const Json::Value& value) {
1597 return value.isMember("field0name5") &&
1598 value.isMember("field0Name6");
1599 });
1600 RunValidJsonTestWithValidator(
1601 "FieldNameWithMixedCases", REQUIRED,
1602 R"({
1603 "fieldName7": 7,
1604 "FieldName8": 8,
1605 "fieldName9": 9,
1606 "FieldName10": 10,
1607 "FIELDNAME11": 11,
1608 "FIELDName12": 12
1609 })",
1610 [](const Json::Value& value) {
1611 return value.isMember("fieldName7") &&
1612 value.isMember("FieldName8") &&
1613 value.isMember("fieldName9") &&
1614 value.isMember("FieldName10") &&
1615 value.isMember("FIELDNAME11") &&
1616 value.isMember("FIELDName12");
1617 });
1618 RunValidJsonTestWithValidator(
1619 "FieldNameWithDoubleUnderscores", RECOMMENDED,
1620 R"({
1621 "FieldName13": 13,
1622 "FieldName14": 14,
1623 "fieldName15": 15,
1624 "fieldName16": 16,
1625 "fieldName17": 17,
1626 "FieldName18": 18
1627 })",
1628 [](const Json::Value& value) {
1629 return value.isMember("FieldName13") &&
1630 value.isMember("FieldName14") &&
1631 value.isMember("fieldName15") &&
1632 value.isMember("fieldName16") &&
1633 value.isMember("fieldName17") &&
1634 value.isMember("FieldName18");
1635 });
1636
1637 // Integer fields.
1638 RunValidJsonTest(
1639 "Int32FieldMaxValue", REQUIRED,
1640 R"({"optionalInt32": 2147483647})",
1641 "optional_int32: 2147483647");
1642 RunValidJsonTest(
1643 "Int32FieldMinValue", REQUIRED,
1644 R"({"optionalInt32": -2147483648})",
1645 "optional_int32: -2147483648");
1646 RunValidJsonTest(
1647 "Uint32FieldMaxValue", REQUIRED,
1648 R"({"optionalUint32": 4294967295})",
1649 "optional_uint32: 4294967295");
1650 RunValidJsonTest(
1651 "Int64FieldMaxValue", REQUIRED,
1652 R"({"optionalInt64": "9223372036854775807"})",
1653 "optional_int64: 9223372036854775807");
1654 RunValidJsonTest(
1655 "Int64FieldMinValue", REQUIRED,
1656 R"({"optionalInt64": "-9223372036854775808"})",
1657 "optional_int64: -9223372036854775808");
1658 RunValidJsonTest(
1659 "Uint64FieldMaxValue", REQUIRED,
1660 R"({"optionalUint64": "18446744073709551615"})",
1661 "optional_uint64: 18446744073709551615");
1662 // While not the largest Int64, this is the largest
1663 // Int64 which can be exactly represented within an
1664 // IEEE-754 64-bit float, which is the expected level
1665 // of interoperability guarantee. Larger values may
1666 // work in some implementations, but should not be
1667 // relied upon.
1668 RunValidJsonTest(
1669 "Int64FieldMaxValueNotQuoted", REQUIRED,
1670 R"({"optionalInt64": 9223372036854774784})",
1671 "optional_int64: 9223372036854774784");
1672 RunValidJsonTest(
1673 "Int64FieldMinValueNotQuoted", REQUIRED,
1674 R"({"optionalInt64": -9223372036854775808})",
1675 "optional_int64: -9223372036854775808");
1676 // Largest interoperable Uint64; see comment above
1677 // for Int64FieldMaxValueNotQuoted.
1678 RunValidJsonTest(
1679 "Uint64FieldMaxValueNotQuoted", REQUIRED,
1680 R"({"optionalUint64": 18446744073709549568})",
1681 "optional_uint64: 18446744073709549568");
1682 // Values can be represented as JSON strings.
1683 RunValidJsonTest(
1684 "Int32FieldStringValue", REQUIRED,
1685 R"({"optionalInt32": "2147483647"})",
1686 "optional_int32: 2147483647");
1687 RunValidJsonTest(
1688 "Int32FieldStringValueEscaped", REQUIRED,
1689 R"({"optionalInt32": "2\u003147483647"})",
1690 "optional_int32: 2147483647");
1691
1692 // Parsers reject out-of-bound integer values.
1693 ExpectParseFailureForJson(
1694 "Int32FieldTooLarge", REQUIRED,
1695 R"({"optionalInt32": 2147483648})");
1696 ExpectParseFailureForJson(
1697 "Int32FieldTooSmall", REQUIRED,
1698 R"({"optionalInt32": -2147483649})");
1699 ExpectParseFailureForJson(
1700 "Uint32FieldTooLarge", REQUIRED,
1701 R"({"optionalUint32": 4294967296})");
1702 ExpectParseFailureForJson(
1703 "Int64FieldTooLarge", REQUIRED,
1704 R"({"optionalInt64": "9223372036854775808"})");
1705 ExpectParseFailureForJson(
1706 "Int64FieldTooSmall", REQUIRED,
1707 R"({"optionalInt64": "-9223372036854775809"})");
1708 ExpectParseFailureForJson(
1709 "Uint64FieldTooLarge", REQUIRED,
1710 R"({"optionalUint64": "18446744073709551616"})");
1711 // Parser reject non-integer numeric values as well.
1712 ExpectParseFailureForJson(
1713 "Int32FieldNotInteger", REQUIRED,
1714 R"({"optionalInt32": 0.5})");
1715 ExpectParseFailureForJson(
1716 "Uint32FieldNotInteger", REQUIRED,
1717 R"({"optionalUint32": 0.5})");
1718 ExpectParseFailureForJson(
1719 "Int64FieldNotInteger", REQUIRED,
1720 R"({"optionalInt64": "0.5"})");
1721 ExpectParseFailureForJson(
1722 "Uint64FieldNotInteger", REQUIRED,
1723 R"({"optionalUint64": "0.5"})");
1724
1725 // Integers but represented as float values are accepted.
1726 RunValidJsonTest(
1727 "Int32FieldFloatTrailingZero", REQUIRED,
1728 R"({"optionalInt32": 100000.000})",
1729 "optional_int32: 100000");
1730 RunValidJsonTest(
1731 "Int32FieldExponentialFormat", REQUIRED,
1732 R"({"optionalInt32": 1e5})",
1733 "optional_int32: 100000");
1734 RunValidJsonTest(
1735 "Int32FieldMaxFloatValue", REQUIRED,
1736 R"({"optionalInt32": 2.147483647e9})",
1737 "optional_int32: 2147483647");
1738 RunValidJsonTest(
1739 "Int32FieldMinFloatValue", REQUIRED,
1740 R"({"optionalInt32": -2.147483648e9})",
1741 "optional_int32: -2147483648");
1742 RunValidJsonTest(
1743 "Uint32FieldMaxFloatValue", REQUIRED,
1744 R"({"optionalUint32": 4.294967295e9})",
1745 "optional_uint32: 4294967295");
1746
1747 // Parser reject non-numeric values.
1748 ExpectParseFailureForJson(
1749 "Int32FieldNotNumber", REQUIRED,
1750 R"({"optionalInt32": "3x3"})");
1751 ExpectParseFailureForJson(
1752 "Uint32FieldNotNumber", REQUIRED,
1753 R"({"optionalUint32": "3x3"})");
1754 ExpectParseFailureForJson(
1755 "Int64FieldNotNumber", REQUIRED,
1756 R"({"optionalInt64": "3x3"})");
1757 ExpectParseFailureForJson(
1758 "Uint64FieldNotNumber", REQUIRED,
1759 R"({"optionalUint64": "3x3"})");
1760 // JSON does not allow "+" on numric values.
1761 ExpectParseFailureForJson(
1762 "Int32FieldPlusSign", REQUIRED,
1763 R"({"optionalInt32": +1})");
1764 // JSON doesn't allow leading 0s.
1765 ExpectParseFailureForJson(
1766 "Int32FieldLeadingZero", REQUIRED,
1767 R"({"optionalInt32": 01})");
1768 ExpectParseFailureForJson(
1769 "Int32FieldNegativeWithLeadingZero", REQUIRED,
1770 R"({"optionalInt32": -01})");
1771 // String values must follow the same syntax rule. Specifically leading
1772 // or trailing spaces are not allowed.
1773 ExpectParseFailureForJson(
1774 "Int32FieldLeadingSpace", REQUIRED,
1775 R"({"optionalInt32": " 1"})");
1776 ExpectParseFailureForJson(
1777 "Int32FieldTrailingSpace", REQUIRED,
1778 R"({"optionalInt32": "1 "})");
1779
1780 // 64-bit values are serialized as strings.
1781 RunValidJsonTestWithValidator(
1782 "Int64FieldBeString", RECOMMENDED,
1783 R"({"optionalInt64": 1})",
1784 [](const Json::Value& value) {
1785 return value["optionalInt64"].type() == Json::stringValue &&
1786 value["optionalInt64"].asString() == "1";
1787 });
1788 RunValidJsonTestWithValidator(
1789 "Uint64FieldBeString", RECOMMENDED,
1790 R"({"optionalUint64": 1})",
1791 [](const Json::Value& value) {
1792 return value["optionalUint64"].type() == Json::stringValue &&
1793 value["optionalUint64"].asString() == "1";
1794 });
1795
1796 // Bool fields.
1797 RunValidJsonTest(
1798 "BoolFieldTrue", REQUIRED,
1799 R"({"optionalBool":true})",
1800 "optional_bool: true");
1801 RunValidJsonTest(
1802 "BoolFieldFalse", REQUIRED,
1803 R"({"optionalBool":false})",
1804 "optional_bool: false");
1805
1806 // Other forms are not allowed.
1807 ExpectParseFailureForJson(
1808 "BoolFieldIntegerZero", RECOMMENDED,
1809 R"({"optionalBool":0})");
1810 ExpectParseFailureForJson(
1811 "BoolFieldIntegerOne", RECOMMENDED,
1812 R"({"optionalBool":1})");
1813 ExpectParseFailureForJson(
1814 "BoolFieldCamelCaseTrue", RECOMMENDED,
1815 R"({"optionalBool":True})");
1816 ExpectParseFailureForJson(
1817 "BoolFieldCamelCaseFalse", RECOMMENDED,
1818 R"({"optionalBool":False})");
1819 ExpectParseFailureForJson(
1820 "BoolFieldAllCapitalTrue", RECOMMENDED,
1821 R"({"optionalBool":TRUE})");
1822 ExpectParseFailureForJson(
1823 "BoolFieldAllCapitalFalse", RECOMMENDED,
1824 R"({"optionalBool":FALSE})");
1825 ExpectParseFailureForJson(
1826 "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1827 R"({"optionalBool":"true"})");
1828 ExpectParseFailureForJson(
1829 "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1830 R"({"optionalBool":"false"})");
1831
1832 // Float fields.
1833 RunValidJsonTest(
1834 "FloatFieldMinPositiveValue", REQUIRED,
1835 R"({"optionalFloat": 1.175494e-38})",
1836 "optional_float: 1.175494e-38");
1837 RunValidJsonTest(
1838 "FloatFieldMaxNegativeValue", REQUIRED,
1839 R"({"optionalFloat": -1.175494e-38})",
1840 "optional_float: -1.175494e-38");
1841 RunValidJsonTest(
1842 "FloatFieldMaxPositiveValue", REQUIRED,
1843 R"({"optionalFloat": 3.402823e+38})",
1844 "optional_float: 3.402823e+38");
1845 RunValidJsonTest(
1846 "FloatFieldMinNegativeValue", REQUIRED,
1847 R"({"optionalFloat": 3.402823e+38})",
1848 "optional_float: 3.402823e+38");
1849 // Values can be quoted.
1850 RunValidJsonTest(
1851 "FloatFieldQuotedValue", REQUIRED,
1852 R"({"optionalFloat": "1"})",
1853 "optional_float: 1");
1854 // Special values.
1855 RunValidJsonTest(
1856 "FloatFieldNan", REQUIRED,
1857 R"({"optionalFloat": "NaN"})",
1858 "optional_float: nan");
1859 RunValidJsonTest(
1860 "FloatFieldInfinity", REQUIRED,
1861 R"({"optionalFloat": "Infinity"})",
1862 "optional_float: inf");
1863 RunValidJsonTest(
1864 "FloatFieldNegativeInfinity", REQUIRED,
1865 R"({"optionalFloat": "-Infinity"})",
1866 "optional_float: -inf");
1867 // Non-cannonical Nan will be correctly normalized.
1868 {
1869 TestAllTypesProto3 message;
1870 // IEEE floating-point standard 32-bit quiet NaN:
1871 // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
1872 message.set_optional_float(
1873 WireFormatLite::DecodeFloat(0x7FA12345));
1874 RunValidJsonTestWithProtobufInput(
1875 "FloatFieldNormalizeQuietNan", REQUIRED, message,
1876 "optional_float: nan");
1877 // IEEE floating-point standard 64-bit signaling NaN:
1878 // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
1879 message.set_optional_float(
1880 WireFormatLite::DecodeFloat(0xFFB54321));
1881 RunValidJsonTestWithProtobufInput(
1882 "FloatFieldNormalizeSignalingNan", REQUIRED, message,
1883 "optional_float: nan");
1884 }
1885
1886 // Special values must be quoted.
1887 ExpectParseFailureForJson(
1888 "FloatFieldNanNotQuoted", RECOMMENDED,
1889 R"({"optionalFloat": NaN})");
1890 ExpectParseFailureForJson(
1891 "FloatFieldInfinityNotQuoted", RECOMMENDED,
1892 R"({"optionalFloat": Infinity})");
1893 ExpectParseFailureForJson(
1894 "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1895 R"({"optionalFloat": -Infinity})");
1896 // Parsers should reject out-of-bound values.
1897 ExpectParseFailureForJson(
1898 "FloatFieldTooSmall", REQUIRED,
1899 R"({"optionalFloat": -3.502823e+38})");
1900 ExpectParseFailureForJson(
1901 "FloatFieldTooLarge", REQUIRED,
1902 R"({"optionalFloat": 3.502823e+38})");
1903
1904 // Double fields.
1905 RunValidJsonTest(
1906 "DoubleFieldMinPositiveValue", REQUIRED,
1907 R"({"optionalDouble": 2.22507e-308})",
1908 "optional_double: 2.22507e-308");
1909 RunValidJsonTest(
1910 "DoubleFieldMaxNegativeValue", REQUIRED,
1911 R"({"optionalDouble": -2.22507e-308})",
1912 "optional_double: -2.22507e-308");
1913 RunValidJsonTest(
1914 "DoubleFieldMaxPositiveValue", REQUIRED,
1915 R"({"optionalDouble": 1.79769e+308})",
1916 "optional_double: 1.79769e+308");
1917 RunValidJsonTest(
1918 "DoubleFieldMinNegativeValue", REQUIRED,
1919 R"({"optionalDouble": -1.79769e+308})",
1920 "optional_double: -1.79769e+308");
1921 // Values can be quoted.
1922 RunValidJsonTest(
1923 "DoubleFieldQuotedValue", REQUIRED,
1924 R"({"optionalDouble": "1"})",
1925 "optional_double: 1");
1926 // Speical values.
1927 RunValidJsonTest(
1928 "DoubleFieldNan", REQUIRED,
1929 R"({"optionalDouble": "NaN"})",
1930 "optional_double: nan");
1931 RunValidJsonTest(
1932 "DoubleFieldInfinity", REQUIRED,
1933 R"({"optionalDouble": "Infinity"})",
1934 "optional_double: inf");
1935 RunValidJsonTest(
1936 "DoubleFieldNegativeInfinity", REQUIRED,
1937 R"({"optionalDouble": "-Infinity"})",
1938 "optional_double: -inf");
1939 // Non-cannonical Nan will be correctly normalized.
1940 {
1941 TestAllTypesProto3 message;
1942 message.set_optional_double(
1943 WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
1944 RunValidJsonTestWithProtobufInput(
1945 "DoubleFieldNormalizeQuietNan", REQUIRED, message,
1946 "optional_double: nan");
1947 message.set_optional_double(
1948 WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
1949 RunValidJsonTestWithProtobufInput(
1950 "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
1951 "optional_double: nan");
1952 }
1953
1954 // Special values must be quoted.
1955 ExpectParseFailureForJson(
1956 "DoubleFieldNanNotQuoted", RECOMMENDED,
1957 R"({"optionalDouble": NaN})");
1958 ExpectParseFailureForJson(
1959 "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1960 R"({"optionalDouble": Infinity})");
1961 ExpectParseFailureForJson(
1962 "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1963 R"({"optionalDouble": -Infinity})");
1964
1965 // Parsers should reject out-of-bound values.
1966 ExpectParseFailureForJson(
1967 "DoubleFieldTooSmall", REQUIRED,
1968 R"({"optionalDouble": -1.89769e+308})");
1969 ExpectParseFailureForJson(
1970 "DoubleFieldTooLarge", REQUIRED,
1971 R"({"optionalDouble": +1.89769e+308})");
1972
1973 // Enum fields.
1974 RunValidJsonTest(
1975 "EnumField", REQUIRED,
1976 R"({"optionalNestedEnum": "FOO"})",
1977 "optional_nested_enum: FOO");
Hao Nguyen3d46d8d2018-12-14 16:41:44 -08001978 // Enum fields with alias
1979 RunValidJsonTest(
1980 "EnumFieldWithAlias", REQUIRED,
1981 R"({"optionalAliasedEnum": "ALIAS_BAZ"})",
1982 "optional_aliased_enum: ALIAS_BAZ");
1983 RunValidJsonTest(
1984 "EnumFieldWithAliasUseAlias", REQUIRED,
1985 R"({"optionalAliasedEnum": "QUX"})",
1986 "optional_aliased_enum: ALIAS_BAZ");
1987 RunValidJsonTest(
1988 "EnumFieldWithAliasLowerCase", REQUIRED,
1989 R"({"optionalAliasedEnum": "qux"})",
1990 "optional_aliased_enum: ALIAS_BAZ");
1991 RunValidJsonTest(
1992 "EnumFieldWithAliasDifferentCase", REQUIRED,
1993 R"({"optionalAliasedEnum": "bAz"})",
1994 "optional_aliased_enum: ALIAS_BAZ");
Feng Xiao6bbe1972018-08-08 17:00:41 -07001995 // Enum values must be represented as strings.
1996 ExpectParseFailureForJson(
1997 "EnumFieldNotQuoted", REQUIRED,
1998 R"({"optionalNestedEnum": FOO})");
1999 // Numeric values are allowed.
2000 RunValidJsonTest(
2001 "EnumFieldNumericValueZero", REQUIRED,
2002 R"({"optionalNestedEnum": 0})",
2003 "optional_nested_enum: FOO");
2004 RunValidJsonTest(
2005 "EnumFieldNumericValueNonZero", REQUIRED,
2006 R"({"optionalNestedEnum": 1})",
2007 "optional_nested_enum: BAR");
2008 // Unknown enum values are represented as numeric values.
2009 RunValidJsonTestWithValidator(
2010 "EnumFieldUnknownValue", REQUIRED,
2011 R"({"optionalNestedEnum": 123})",
2012 [](const Json::Value& value) {
2013 return value["optionalNestedEnum"].type() == Json::intValue &&
2014 value["optionalNestedEnum"].asInt() == 123;
2015 });
2016
2017 // String fields.
2018 RunValidJsonTest(
2019 "StringField", REQUIRED,
2020 R"({"optionalString": "Hello world!"})",
2021 "optional_string: \"Hello world!\"");
2022 RunValidJsonTest(
2023 "StringFieldUnicode", REQUIRED,
2024 // Google in Chinese.
2025 R"({"optionalString": "谷歌"})",
2026 R"(optional_string: "谷歌")");
2027 RunValidJsonTest(
2028 "StringFieldEscape", REQUIRED,
2029 R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
2030 R"(optional_string: "\"\\/\b\f\n\r\t")");
2031 RunValidJsonTest(
2032 "StringFieldUnicodeEscape", REQUIRED,
2033 R"({"optionalString": "\u8C37\u6B4C"})",
2034 R"(optional_string: "谷歌")");
2035 RunValidJsonTest(
2036 "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
2037 R"({"optionalString": "\u8c37\u6b4c"})",
2038 R"(optional_string: "谷歌")");
2039 RunValidJsonTest(
2040 "StringFieldSurrogatePair", REQUIRED,
2041 // The character is an emoji: grinning face with smiling eyes. 😁
2042 R"({"optionalString": "\uD83D\uDE01"})",
2043 R"(optional_string: "\xF0\x9F\x98\x81")");
2044
2045 // Unicode escapes must start with "\u" (lowercase u).
2046 ExpectParseFailureForJson(
2047 "StringFieldUppercaseEscapeLetter", RECOMMENDED,
2048 R"({"optionalString": "\U8C37\U6b4C"})");
2049 ExpectParseFailureForJson(
2050 "StringFieldInvalidEscape", RECOMMENDED,
2051 R"({"optionalString": "\uXXXX\u6B4C"})");
2052 ExpectParseFailureForJson(
2053 "StringFieldUnterminatedEscape", RECOMMENDED,
2054 R"({"optionalString": "\u8C3"})");
2055 ExpectParseFailureForJson(
2056 "StringFieldUnpairedHighSurrogate", RECOMMENDED,
2057 R"({"optionalString": "\uD800"})");
2058 ExpectParseFailureForJson(
2059 "StringFieldUnpairedLowSurrogate", RECOMMENDED,
2060 R"({"optionalString": "\uDC00"})");
2061 ExpectParseFailureForJson(
2062 "StringFieldSurrogateInWrongOrder", RECOMMENDED,
2063 R"({"optionalString": "\uDE01\uD83D"})");
2064 ExpectParseFailureForJson(
2065 "StringFieldNotAString", REQUIRED,
2066 R"({"optionalString": 12345})");
2067
2068 // Bytes fields.
2069 RunValidJsonTest(
2070 "BytesField", REQUIRED,
2071 R"({"optionalBytes": "AQI="})",
2072 R"(optional_bytes: "\x01\x02")");
2073 RunValidJsonTest(
2074 "BytesFieldBase64Url", RECOMMENDED,
2075 R"({"optionalBytes": "-_"})",
2076 R"(optional_bytes: "\xfb")");
2077
2078 // Message fields.
2079 RunValidJsonTest(
2080 "MessageField", REQUIRED,
2081 R"({"optionalNestedMessage": {"a": 1234}})",
2082 "optional_nested_message: {a: 1234}");
2083
2084 // Oneof fields.
2085 ExpectParseFailureForJson(
2086 "OneofFieldDuplicate", REQUIRED,
2087 R"({"oneofUint32": 1, "oneofString": "test"})");
2088 // Ensure zero values for oneof make it out/backs.
2089 TestAllTypesProto3 messageProto3;
2090 TestAllTypesProto2 messageProto2;
2091 TestOneofMessage(messageProto3, true);
2092 TestOneofMessage(messageProto2, false);
2093 RunValidJsonTest(
2094 "OneofZeroUint32", RECOMMENDED,
2095 R"({"oneofUint32": 0})", "oneof_uint32: 0");
2096 RunValidJsonTest(
2097 "OneofZeroMessage", RECOMMENDED,
2098 R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
2099 RunValidJsonTest(
2100 "OneofZeroString", RECOMMENDED,
2101 R"({"oneofString": ""})", "oneof_string: \"\"");
2102 RunValidJsonTest(
2103 "OneofZeroBytes", RECOMMENDED,
2104 R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
2105 RunValidJsonTest(
2106 "OneofZeroBool", RECOMMENDED,
2107 R"({"oneofBool": false})", "oneof_bool: false");
2108 RunValidJsonTest(
2109 "OneofZeroUint64", RECOMMENDED,
2110 R"({"oneofUint64": 0})", "oneof_uint64: 0");
2111 RunValidJsonTest(
2112 "OneofZeroFloat", RECOMMENDED,
2113 R"({"oneofFloat": 0.0})", "oneof_float: 0");
2114 RunValidJsonTest(
2115 "OneofZeroDouble", RECOMMENDED,
2116 R"({"oneofDouble": 0.0})", "oneof_double: 0");
2117 RunValidJsonTest(
2118 "OneofZeroEnum", RECOMMENDED,
2119 R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
2120
2121 // Repeated fields.
2122 RunValidJsonTest(
2123 "PrimitiveRepeatedField", REQUIRED,
2124 R"({"repeatedInt32": [1, 2, 3, 4]})",
2125 "repeated_int32: [1, 2, 3, 4]");
2126 RunValidJsonTest(
2127 "EnumRepeatedField", REQUIRED,
2128 R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
2129 "repeated_nested_enum: [FOO, BAR, BAZ]");
2130 RunValidJsonTest(
2131 "StringRepeatedField", REQUIRED,
2132 R"({"repeatedString": ["Hello", "world"]})",
2133 R"(repeated_string: ["Hello", "world"])");
2134 RunValidJsonTest(
2135 "BytesRepeatedField", REQUIRED,
2136 R"({"repeatedBytes": ["AAEC", "AQI="]})",
2137 R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
2138 RunValidJsonTest(
2139 "MessageRepeatedField", REQUIRED,
2140 R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
2141 "repeated_nested_message: {a: 1234}"
2142 "repeated_nested_message: {a: 5678}");
2143
2144 // Repeated field elements are of incorrect type.
2145 ExpectParseFailureForJson(
2146 "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
2147 R"({"repeatedInt32": [1, false, 3, 4]})");
2148 ExpectParseFailureForJson(
2149 "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
2150 R"({"repeatedInt32": [1, 2, "name", 4]})");
2151 ExpectParseFailureForJson(
2152 "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
2153 R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
2154 ExpectParseFailureForJson(
2155 "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
2156 R"({"repeatedString": ["1", 2, "3", "4"]})");
2157 ExpectParseFailureForJson(
2158 "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
2159 R"({"repeatedString": ["1", "2", false, "4"]})");
2160 ExpectParseFailureForJson(
2161 "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
2162 R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
2163 ExpectParseFailureForJson(
2164 "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
2165 R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
2166 ExpectParseFailureForJson(
2167 "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
2168 R"({"repeatedNestedMessage": [{"a": 1}, false]})");
2169 ExpectParseFailureForJson(
2170 "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
2171 R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
2172 // Trailing comma in the repeated field is not allowed.
2173 ExpectParseFailureForJson(
2174 "RepeatedFieldTrailingComma", RECOMMENDED,
2175 R"({"repeatedInt32": [1, 2, 3, 4,]})");
2176 ExpectParseFailureForJson(
2177 "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
2178 "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
2179 ExpectParseFailureForJson(
2180 "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
2181 "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
2182 ExpectParseFailureForJson(
2183 "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
2184 "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
2185
2186 // Map fields.
2187 RunValidJsonTest(
2188 "Int32MapField", REQUIRED,
2189 R"({"mapInt32Int32": {"1": 2, "3": 4}})",
2190 "map_int32_int32: {key: 1 value: 2}"
2191 "map_int32_int32: {key: 3 value: 4}");
2192 ExpectParseFailureForJson(
2193 "Int32MapFieldKeyNotQuoted", RECOMMENDED,
2194 R"({"mapInt32Int32": {1: 2, 3: 4}})");
2195 RunValidJsonTest(
2196 "Uint32MapField", REQUIRED,
2197 R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
2198 "map_uint32_uint32: {key: 1 value: 2}"
2199 "map_uint32_uint32: {key: 3 value: 4}");
2200 ExpectParseFailureForJson(
2201 "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
2202 R"({"mapUint32Uint32": {1: 2, 3: 4}})");
2203 RunValidJsonTest(
2204 "Int64MapField", REQUIRED,
2205 R"({"mapInt64Int64": {"1": 2, "3": 4}})",
2206 "map_int64_int64: {key: 1 value: 2}"
2207 "map_int64_int64: {key: 3 value: 4}");
2208 ExpectParseFailureForJson(
2209 "Int64MapFieldKeyNotQuoted", RECOMMENDED,
2210 R"({"mapInt64Int64": {1: 2, 3: 4}})");
2211 RunValidJsonTest(
2212 "Uint64MapField", REQUIRED,
2213 R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
2214 "map_uint64_uint64: {key: 1 value: 2}"
2215 "map_uint64_uint64: {key: 3 value: 4}");
2216 ExpectParseFailureForJson(
2217 "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
2218 R"({"mapUint64Uint64": {1: 2, 3: 4}})");
2219 RunValidJsonTest(
2220 "BoolMapField", REQUIRED,
2221 R"({"mapBoolBool": {"true": true, "false": false}})",
2222 "map_bool_bool: {key: true value: true}"
2223 "map_bool_bool: {key: false value: false}");
2224 ExpectParseFailureForJson(
2225 "BoolMapFieldKeyNotQuoted", RECOMMENDED,
2226 R"({"mapBoolBool": {true: true, false: false}})");
2227 RunValidJsonTest(
2228 "MessageMapField", REQUIRED,
2229 R"({
2230 "mapStringNestedMessage": {
2231 "hello": {"a": 1234},
2232 "world": {"a": 5678}
2233 }
2234 })",
2235 R"(
2236 map_string_nested_message: {
2237 key: "hello"
2238 value: {a: 1234}
2239 }
2240 map_string_nested_message: {
2241 key: "world"
2242 value: {a: 5678}
2243 }
2244 )");
2245 // Since Map keys are represented as JSON strings, escaping should be allowed.
2246 RunValidJsonTest(
2247 "Int32MapEscapedKey", REQUIRED,
2248 R"({"mapInt32Int32": {"\u0031": 2}})",
2249 "map_int32_int32: {key: 1 value: 2}");
2250 RunValidJsonTest(
2251 "Int64MapEscapedKey", REQUIRED,
2252 R"({"mapInt64Int64": {"\u0031": 2}})",
2253 "map_int64_int64: {key: 1 value: 2}");
2254 RunValidJsonTest(
2255 "BoolMapEscapedKey", REQUIRED,
2256 R"({"mapBoolBool": {"tr\u0075e": true}})",
2257 "map_bool_bool: {key: true value: true}");
2258
2259 // "null" is accepted for all fields types.
2260 RunValidJsonTest(
2261 "AllFieldAcceptNull", REQUIRED,
2262 R"({
2263 "optionalInt32": null,
2264 "optionalInt64": null,
2265 "optionalUint32": null,
2266 "optionalUint64": null,
2267 "optionalSint32": null,
2268 "optionalSint64": null,
2269 "optionalFixed32": null,
2270 "optionalFixed64": null,
2271 "optionalSfixed32": null,
2272 "optionalSfixed64": null,
2273 "optionalFloat": null,
2274 "optionalDouble": null,
2275 "optionalBool": null,
2276 "optionalString": null,
2277 "optionalBytes": null,
2278 "optionalNestedEnum": null,
2279 "optionalNestedMessage": null,
2280 "repeatedInt32": null,
2281 "repeatedInt64": null,
2282 "repeatedUint32": null,
2283 "repeatedUint64": null,
2284 "repeatedSint32": null,
2285 "repeatedSint64": null,
2286 "repeatedFixed32": null,
2287 "repeatedFixed64": null,
2288 "repeatedSfixed32": null,
2289 "repeatedSfixed64": null,
2290 "repeatedFloat": null,
2291 "repeatedDouble": null,
2292 "repeatedBool": null,
2293 "repeatedString": null,
2294 "repeatedBytes": null,
2295 "repeatedNestedEnum": null,
2296 "repeatedNestedMessage": null,
2297 "mapInt32Int32": null,
2298 "mapBoolBool": null,
2299 "mapStringNestedMessage": null
2300 })",
2301 "");
2302
2303 // Repeated field elements cannot be null.
2304 ExpectParseFailureForJson(
2305 "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
2306 R"({"repeatedInt32": [1, null, 2]})");
2307 ExpectParseFailureForJson(
2308 "RepeatedFieldMessageElementIsNull", RECOMMENDED,
2309 R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
2310 // Map field keys cannot be null.
2311 ExpectParseFailureForJson(
2312 "MapFieldKeyIsNull", RECOMMENDED,
2313 R"({"mapInt32Int32": {null: 1}})");
2314 // Map field values cannot be null.
2315 ExpectParseFailureForJson(
2316 "MapFieldValueIsNull", RECOMMENDED,
2317 R"({"mapInt32Int32": {"0": null}})");
2318
2319 // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
2320 // quotes.
2321 ExpectParseFailureForJson(
2322 "StringFieldSingleQuoteKey", RECOMMENDED,
2323 R"({'optionalString': "Hello world!"})");
2324 ExpectParseFailureForJson(
2325 "StringFieldSingleQuoteValue", RECOMMENDED,
2326 R"({"optionalString": 'Hello world!'})");
2327 ExpectParseFailureForJson(
2328 "StringFieldSingleQuoteBoth", RECOMMENDED,
2329 R"({'optionalString': 'Hello world!'})");
2330
2331 // Unknown fields.
2332 {
2333 TestAllTypesProto3 messageProto3;
2334 TestAllTypesProto2 messageProto2;
2335 //TODO(yilunchong): update this behavior when unknown field's behavior
2336 // changed in open source. Also delete
2337 // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
2338 // from failure list of python_cpp python java
2339 TestUnknownMessage(messageProto3, true);
2340 TestUnknownMessage(messageProto2, false);
2341 }
2342
2343 // Wrapper types.
2344 RunValidJsonTest(
2345 "OptionalBoolWrapper", REQUIRED,
2346 R"({"optionalBoolWrapper": false})",
2347 "optional_bool_wrapper: {value: false}");
2348 RunValidJsonTest(
2349 "OptionalInt32Wrapper", REQUIRED,
2350 R"({"optionalInt32Wrapper": 0})",
2351 "optional_int32_wrapper: {value: 0}");
2352 RunValidJsonTest(
2353 "OptionalUint32Wrapper", REQUIRED,
2354 R"({"optionalUint32Wrapper": 0})",
2355 "optional_uint32_wrapper: {value: 0}");
2356 RunValidJsonTest(
2357 "OptionalInt64Wrapper", REQUIRED,
2358 R"({"optionalInt64Wrapper": 0})",
2359 "optional_int64_wrapper: {value: 0}");
2360 RunValidJsonTest(
2361 "OptionalUint64Wrapper", REQUIRED,
2362 R"({"optionalUint64Wrapper": 0})",
2363 "optional_uint64_wrapper: {value: 0}");
2364 RunValidJsonTest(
2365 "OptionalFloatWrapper", REQUIRED,
2366 R"({"optionalFloatWrapper": 0})",
2367 "optional_float_wrapper: {value: 0}");
2368 RunValidJsonTest(
2369 "OptionalDoubleWrapper", REQUIRED,
2370 R"({"optionalDoubleWrapper": 0})",
2371 "optional_double_wrapper: {value: 0}");
2372 RunValidJsonTest(
2373 "OptionalStringWrapper", REQUIRED,
2374 R"({"optionalStringWrapper": ""})",
2375 R"(optional_string_wrapper: {value: ""})");
2376 RunValidJsonTest(
2377 "OptionalBytesWrapper", REQUIRED,
2378 R"({"optionalBytesWrapper": ""})",
2379 R"(optional_bytes_wrapper: {value: ""})");
2380 RunValidJsonTest(
2381 "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
2382 R"({
2383 "optionalBoolWrapper": true,
2384 "optionalInt32Wrapper": 1,
2385 "optionalUint32Wrapper": 1,
2386 "optionalInt64Wrapper": "1",
2387 "optionalUint64Wrapper": "1",
2388 "optionalFloatWrapper": 1,
2389 "optionalDoubleWrapper": 1,
2390 "optionalStringWrapper": "1",
2391 "optionalBytesWrapper": "AQI="
2392 })",
2393 R"(
2394 optional_bool_wrapper: {value: true}
2395 optional_int32_wrapper: {value: 1}
2396 optional_uint32_wrapper: {value: 1}
2397 optional_int64_wrapper: {value: 1}
2398 optional_uint64_wrapper: {value: 1}
2399 optional_float_wrapper: {value: 1}
2400 optional_double_wrapper: {value: 1}
2401 optional_string_wrapper: {value: "1"}
2402 optional_bytes_wrapper: {value: "\x01\x02"}
2403 )");
2404 RunValidJsonTest(
2405 "RepeatedBoolWrapper", REQUIRED,
2406 R"({"repeatedBoolWrapper": [true, false]})",
2407 "repeated_bool_wrapper: {value: true}"
2408 "repeated_bool_wrapper: {value: false}");
2409 RunValidJsonTest(
2410 "RepeatedInt32Wrapper", REQUIRED,
2411 R"({"repeatedInt32Wrapper": [0, 1]})",
2412 "repeated_int32_wrapper: {value: 0}"
2413 "repeated_int32_wrapper: {value: 1}");
2414 RunValidJsonTest(
2415 "RepeatedUint32Wrapper", REQUIRED,
2416 R"({"repeatedUint32Wrapper": [0, 1]})",
2417 "repeated_uint32_wrapper: {value: 0}"
2418 "repeated_uint32_wrapper: {value: 1}");
2419 RunValidJsonTest(
2420 "RepeatedInt64Wrapper", REQUIRED,
2421 R"({"repeatedInt64Wrapper": [0, 1]})",
2422 "repeated_int64_wrapper: {value: 0}"
2423 "repeated_int64_wrapper: {value: 1}");
2424 RunValidJsonTest(
2425 "RepeatedUint64Wrapper", REQUIRED,
2426 R"({"repeatedUint64Wrapper": [0, 1]})",
2427 "repeated_uint64_wrapper: {value: 0}"
2428 "repeated_uint64_wrapper: {value: 1}");
2429 RunValidJsonTest(
2430 "RepeatedFloatWrapper", REQUIRED,
2431 R"({"repeatedFloatWrapper": [0, 1]})",
2432 "repeated_float_wrapper: {value: 0}"
2433 "repeated_float_wrapper: {value: 1}");
2434 RunValidJsonTest(
2435 "RepeatedDoubleWrapper", REQUIRED,
2436 R"({"repeatedDoubleWrapper": [0, 1]})",
2437 "repeated_double_wrapper: {value: 0}"
2438 "repeated_double_wrapper: {value: 1}");
2439 RunValidJsonTest(
2440 "RepeatedStringWrapper", REQUIRED,
2441 R"({"repeatedStringWrapper": ["", "AQI="]})",
2442 R"(
2443 repeated_string_wrapper: {value: ""}
2444 repeated_string_wrapper: {value: "AQI="}
2445 )");
2446 RunValidJsonTest(
2447 "RepeatedBytesWrapper", REQUIRED,
2448 R"({"repeatedBytesWrapper": ["", "AQI="]})",
2449 R"(
2450 repeated_bytes_wrapper: {value: ""}
2451 repeated_bytes_wrapper: {value: "\x01\x02"}
2452 )");
2453 RunValidJsonTest(
2454 "WrapperTypesWithNullValue", REQUIRED,
2455 R"({
2456 "optionalBoolWrapper": null,
2457 "optionalInt32Wrapper": null,
2458 "optionalUint32Wrapper": null,
2459 "optionalInt64Wrapper": null,
2460 "optionalUint64Wrapper": null,
2461 "optionalFloatWrapper": null,
2462 "optionalDoubleWrapper": null,
2463 "optionalStringWrapper": null,
2464 "optionalBytesWrapper": null,
2465 "repeatedBoolWrapper": null,
2466 "repeatedInt32Wrapper": null,
2467 "repeatedUint32Wrapper": null,
2468 "repeatedInt64Wrapper": null,
2469 "repeatedUint64Wrapper": null,
2470 "repeatedFloatWrapper": null,
2471 "repeatedDoubleWrapper": null,
2472 "repeatedStringWrapper": null,
2473 "repeatedBytesWrapper": null
2474 })",
2475 "");
2476
2477 // Duration
2478 RunValidJsonTest(
2479 "DurationMinValue", REQUIRED,
2480 R"({"optionalDuration": "-315576000000.999999999s"})",
2481 "optional_duration: {seconds: -315576000000 nanos: -999999999}");
2482 RunValidJsonTest(
2483 "DurationMaxValue", REQUIRED,
2484 R"({"optionalDuration": "315576000000.999999999s"})",
2485 "optional_duration: {seconds: 315576000000 nanos: 999999999}");
2486 RunValidJsonTest(
2487 "DurationRepeatedValue", REQUIRED,
2488 R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
2489 "repeated_duration: {seconds: 1 nanos: 500000000}"
2490 "repeated_duration: {seconds: -1 nanos: -500000000}");
2491 RunValidJsonTest(
2492 "DurationNull", REQUIRED,
2493 R"({"optionalDuration": null})",
2494 "");
2495
2496 ExpectParseFailureForJson(
2497 "DurationMissingS", REQUIRED,
2498 R"({"optionalDuration": "1"})");
2499 ExpectParseFailureForJson(
2500 "DurationJsonInputTooSmall", REQUIRED,
2501 R"({"optionalDuration": "-315576000001.000000000s"})");
2502 ExpectParseFailureForJson(
2503 "DurationJsonInputTooLarge", REQUIRED,
2504 R"({"optionalDuration": "315576000001.000000000s"})");
2505 ExpectSerializeFailureForJson(
2506 "DurationProtoInputTooSmall", REQUIRED,
2507 "optional_duration: {seconds: -315576000001 nanos: 0}");
2508 ExpectSerializeFailureForJson(
2509 "DurationProtoInputTooLarge", REQUIRED,
2510 "optional_duration: {seconds: 315576000001 nanos: 0}");
2511
2512 RunValidJsonTestWithValidator(
2513 "DurationHasZeroFractionalDigit", RECOMMENDED,
2514 R"({"optionalDuration": "1.000000000s"})",
2515 [](const Json::Value& value) {
2516 return value["optionalDuration"].asString() == "1s";
2517 });
2518 RunValidJsonTestWithValidator(
2519 "DurationHas3FractionalDigits", RECOMMENDED,
2520 R"({"optionalDuration": "1.010000000s"})",
2521 [](const Json::Value& value) {
2522 return value["optionalDuration"].asString() == "1.010s";
2523 });
2524 RunValidJsonTestWithValidator(
2525 "DurationHas6FractionalDigits", RECOMMENDED,
2526 R"({"optionalDuration": "1.000010000s"})",
2527 [](const Json::Value& value) {
2528 return value["optionalDuration"].asString() == "1.000010s";
2529 });
2530 RunValidJsonTestWithValidator(
2531 "DurationHas9FractionalDigits", RECOMMENDED,
2532 R"({"optionalDuration": "1.000000010s"})",
2533 [](const Json::Value& value) {
2534 return value["optionalDuration"].asString() == "1.000000010s";
2535 });
2536
2537 // Timestamp
2538 RunValidJsonTest(
2539 "TimestampMinValue", REQUIRED,
2540 R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
2541 "optional_timestamp: {seconds: -62135596800}");
2542 RunValidJsonTest(
2543 "TimestampMaxValue", REQUIRED,
2544 R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
2545 "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
2546 RunValidJsonTest(
2547 "TimestampRepeatedValue", REQUIRED,
2548 R"({
2549 "repeatedTimestamp": [
2550 "0001-01-01T00:00:00Z",
2551 "9999-12-31T23:59:59.999999999Z"
2552 ]
2553 })",
2554 "repeated_timestamp: {seconds: -62135596800}"
2555 "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
Hao Nguyen51026d92019-06-26 11:01:34 -07002556 RunValidJsonTest("TimestampWithPositiveOffset", REQUIRED,
2557 R"({"optionalTimestamp": "1970-01-01T08:00:01+08:00"})",
2558 "optional_timestamp: {seconds: 1}");
2559 RunValidJsonTest("TimestampWithNegativeOffset", REQUIRED,
2560 R"({"optionalTimestamp": "1969-12-31T16:00:01-08:00"})",
2561 "optional_timestamp: {seconds: 1}");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002562 RunValidJsonTest(
2563 "TimestampNull", REQUIRED,
2564 R"({"optionalTimestamp": null})",
2565 "");
2566
2567 ExpectParseFailureForJson(
2568 "TimestampJsonInputTooSmall", REQUIRED,
2569 R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
2570 ExpectParseFailureForJson(
2571 "TimestampJsonInputTooLarge", REQUIRED,
2572 R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
2573 ExpectParseFailureForJson(
2574 "TimestampJsonInputMissingZ", REQUIRED,
2575 R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
2576 ExpectParseFailureForJson(
2577 "TimestampJsonInputMissingT", REQUIRED,
2578 R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
2579 ExpectParseFailureForJson(
2580 "TimestampJsonInputLowercaseZ", REQUIRED,
2581 R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
2582 ExpectParseFailureForJson(
2583 "TimestampJsonInputLowercaseT", REQUIRED,
2584 R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
2585 ExpectSerializeFailureForJson(
2586 "TimestampProtoInputTooSmall", REQUIRED,
2587 "optional_timestamp: {seconds: -62135596801}");
2588 ExpectSerializeFailureForJson(
2589 "TimestampProtoInputTooLarge", REQUIRED,
2590 "optional_timestamp: {seconds: 253402300800}");
2591 RunValidJsonTestWithValidator(
2592 "TimestampZeroNormalized", RECOMMENDED,
2593 R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
2594 [](const Json::Value& value) {
2595 return value["optionalTimestamp"].asString() ==
2596 "1970-01-01T00:00:00Z";
2597 });
2598 RunValidJsonTestWithValidator(
2599 "TimestampHasZeroFractionalDigit", RECOMMENDED,
2600 R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
2601 [](const Json::Value& value) {
2602 return value["optionalTimestamp"].asString() ==
2603 "1970-01-01T00:00:00Z";
2604 });
2605 RunValidJsonTestWithValidator(
2606 "TimestampHas3FractionalDigits", RECOMMENDED,
2607 R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
2608 [](const Json::Value& value) {
2609 return value["optionalTimestamp"].asString() ==
2610 "1970-01-01T00:00:00.010Z";
2611 });
2612 RunValidJsonTestWithValidator(
2613 "TimestampHas6FractionalDigits", RECOMMENDED,
2614 R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
2615 [](const Json::Value& value) {
2616 return value["optionalTimestamp"].asString() ==
2617 "1970-01-01T00:00:00.000010Z";
2618 });
2619 RunValidJsonTestWithValidator(
2620 "TimestampHas9FractionalDigits", RECOMMENDED,
2621 R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
2622 [](const Json::Value& value) {
2623 return value["optionalTimestamp"].asString() ==
2624 "1970-01-01T00:00:00.000000010Z";
2625 });
2626
2627 // FieldMask
2628 RunValidJsonTest(
2629 "FieldMask", REQUIRED,
2630 R"({"optionalFieldMask": "foo,barBaz"})",
2631 R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
Paul Yang7f42d6d2019-01-22 15:35:12 -08002632 RunValidJsonTest(
2633 "EmptyFieldMask", REQUIRED,
2634 R"({"optionalFieldMask": ""})",
2635 R"(optional_field_mask: {})");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002636 ExpectParseFailureForJson(
2637 "FieldMaskInvalidCharacter", RECOMMENDED,
2638 R"({"optionalFieldMask": "foo,bar_bar"})");
2639 ExpectSerializeFailureForJson(
2640 "FieldMaskPathsDontRoundTrip", RECOMMENDED,
2641 R"(optional_field_mask: {paths: "fooBar"})");
2642 ExpectSerializeFailureForJson(
2643 "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
2644 R"(optional_field_mask: {paths: "foo_3_bar"})");
2645 ExpectSerializeFailureForJson(
2646 "FieldMaskTooManyUnderscore", RECOMMENDED,
2647 R"(optional_field_mask: {paths: "foo__bar"})");
2648
2649 // Struct
2650 RunValidJsonTest(
2651 "Struct", REQUIRED,
2652 R"({
2653 "optionalStruct": {
2654 "nullValue": null,
2655 "intValue": 1234,
2656 "boolValue": true,
2657 "doubleValue": 1234.5678,
2658 "stringValue": "Hello world!",
2659 "listValue": [1234, "5678"],
2660 "objectValue": {
2661 "value": 0
2662 }
2663 }
2664 })",
2665 R"(
2666 optional_struct: {
2667 fields: {
2668 key: "nullValue"
2669 value: {null_value: NULL_VALUE}
2670 }
2671 fields: {
2672 key: "intValue"
2673 value: {number_value: 1234}
2674 }
2675 fields: {
2676 key: "boolValue"
2677 value: {bool_value: true}
2678 }
2679 fields: {
2680 key: "doubleValue"
2681 value: {number_value: 1234.5678}
2682 }
2683 fields: {
2684 key: "stringValue"
2685 value: {string_value: "Hello world!"}
2686 }
2687 fields: {
2688 key: "listValue"
2689 value: {
2690 list_value: {
2691 values: {
2692 number_value: 1234
2693 }
2694 values: {
2695 string_value: "5678"
2696 }
2697 }
2698 }
2699 }
2700 fields: {
2701 key: "objectValue"
2702 value: {
2703 struct_value: {
2704 fields: {
2705 key: "value"
2706 value: {
2707 number_value: 0
2708 }
2709 }
2710 }
2711 }
2712 }
2713 }
2714 )");
Paul Yanga1868082019-03-10 17:33:46 -07002715 RunValidJsonTest(
2716 "StructWithEmptyListValue", REQUIRED,
2717 R"({
2718 "optionalStruct": {
2719 "listValue": []
2720 }
2721 })",
2722 R"(
2723 optional_struct: {
2724 fields: {
2725 key: "listValue"
2726 value: {
2727 list_value: {
2728 }
2729 }
2730 }
2731 }
2732 )");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002733 // Value
2734 RunValidJsonTest(
2735 "ValueAcceptInteger", REQUIRED,
2736 R"({"optionalValue": 1})",
2737 "optional_value: { number_value: 1}");
2738 RunValidJsonTest(
2739 "ValueAcceptFloat", REQUIRED,
2740 R"({"optionalValue": 1.5})",
2741 "optional_value: { number_value: 1.5}");
2742 RunValidJsonTest(
2743 "ValueAcceptBool", REQUIRED,
2744 R"({"optionalValue": false})",
2745 "optional_value: { bool_value: false}");
2746 RunValidJsonTest(
2747 "ValueAcceptNull", REQUIRED,
2748 R"({"optionalValue": null})",
2749 "optional_value: { null_value: NULL_VALUE}");
2750 RunValidJsonTest(
2751 "ValueAcceptString", REQUIRED,
2752 R"({"optionalValue": "hello"})",
2753 R"(optional_value: { string_value: "hello"})");
2754 RunValidJsonTest(
2755 "ValueAcceptList", REQUIRED,
2756 R"({"optionalValue": [0, "hello"]})",
2757 R"(
2758 optional_value: {
2759 list_value: {
2760 values: {
2761 number_value: 0
2762 }
2763 values: {
2764 string_value: "hello"
2765 }
2766 }
2767 }
2768 )");
2769 RunValidJsonTest(
2770 "ValueAcceptObject", REQUIRED,
2771 R"({"optionalValue": {"value": 1}})",
2772 R"(
2773 optional_value: {
2774 struct_value: {
2775 fields: {
2776 key: "value"
2777 value: {
2778 number_value: 1
2779 }
2780 }
2781 }
2782 }
2783 )");
Paul Yang4b145b12019-03-12 10:56:58 -07002784 RunValidJsonTest(
2785 "RepeatedValue", REQUIRED,
2786 R"({
2787 "repeatedValue": [["a"]]
2788 })",
2789 R"(
2790 repeated_value: [
2791 {
2792 list_value: {
2793 values: [
2794 { string_value: "a"}
2795 ]
2796 }
2797 }
2798 ]
2799 )");
2800 RunValidJsonTest(
2801 "RepeatedListValue", REQUIRED,
2802 R"({
2803 "repeatedListValue": [["a"]]
2804 })",
2805 R"(
2806 repeated_list_value: [
2807 {
2808 values: [
2809 { string_value: "a"}
2810 ]
2811 }
2812 ]
2813 )");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002814
2815 // Any
2816 RunValidJsonTest(
2817 "Any", REQUIRED,
2818 R"({
2819 "optionalAny": {
2820 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2821 "optionalInt32": 12345
2822 }
2823 })",
2824 R"(
2825 optional_any: {
2826 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2827 optional_int32: 12345
2828 }
2829 }
2830 )");
2831 RunValidJsonTest(
2832 "AnyNested", REQUIRED,
2833 R"({
2834 "optionalAny": {
2835 "@type": "type.googleapis.com/google.protobuf.Any",
2836 "value": {
2837 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2838 "optionalInt32": 12345
2839 }
2840 }
2841 })",
2842 R"(
2843 optional_any: {
2844 [type.googleapis.com/google.protobuf.Any] {
2845 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2846 optional_int32: 12345
2847 }
2848 }
2849 }
2850 )");
2851 // The special "@type" tag is not required to appear first.
2852 RunValidJsonTest(
2853 "AnyUnorderedTypeTag", REQUIRED,
2854 R"({
2855 "optionalAny": {
2856 "optionalInt32": 12345,
2857 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
2858 }
2859 })",
2860 R"(
2861 optional_any: {
2862 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2863 optional_int32: 12345
2864 }
2865 }
2866 )");
2867 // Well-known types in Any.
2868 RunValidJsonTest(
2869 "AnyWithInt32ValueWrapper", REQUIRED,
2870 R"({
2871 "optionalAny": {
2872 "@type": "type.googleapis.com/google.protobuf.Int32Value",
2873 "value": 12345
2874 }
2875 })",
2876 R"(
2877 optional_any: {
2878 [type.googleapis.com/google.protobuf.Int32Value] {
2879 value: 12345
2880 }
2881 }
2882 )");
2883 RunValidJsonTest(
2884 "AnyWithDuration", REQUIRED,
2885 R"({
2886 "optionalAny": {
2887 "@type": "type.googleapis.com/google.protobuf.Duration",
2888 "value": "1.5s"
2889 }
2890 })",
2891 R"(
2892 optional_any: {
2893 [type.googleapis.com/google.protobuf.Duration] {
2894 seconds: 1
2895 nanos: 500000000
2896 }
2897 }
2898 )");
2899 RunValidJsonTest(
2900 "AnyWithTimestamp", REQUIRED,
2901 R"({
2902 "optionalAny": {
2903 "@type": "type.googleapis.com/google.protobuf.Timestamp",
2904 "value": "1970-01-01T00:00:00Z"
2905 }
2906 })",
2907 R"(
2908 optional_any: {
2909 [type.googleapis.com/google.protobuf.Timestamp] {
2910 seconds: 0
2911 nanos: 0
2912 }
2913 }
2914 )");
2915 RunValidJsonTest(
2916 "AnyWithFieldMask", REQUIRED,
2917 R"({
2918 "optionalAny": {
2919 "@type": "type.googleapis.com/google.protobuf.FieldMask",
2920 "value": "foo,barBaz"
2921 }
2922 })",
2923 R"(
2924 optional_any: {
2925 [type.googleapis.com/google.protobuf.FieldMask] {
2926 paths: ["foo", "bar_baz"]
2927 }
2928 }
2929 )");
2930 RunValidJsonTest(
2931 "AnyWithStruct", REQUIRED,
2932 R"({
2933 "optionalAny": {
2934 "@type": "type.googleapis.com/google.protobuf.Struct",
2935 "value": {
2936 "foo": 1
2937 }
2938 }
2939 })",
2940 R"(
2941 optional_any: {
2942 [type.googleapis.com/google.protobuf.Struct] {
2943 fields: {
2944 key: "foo"
2945 value: {
2946 number_value: 1
2947 }
2948 }
2949 }
2950 }
2951 )");
2952 RunValidJsonTest(
2953 "AnyWithValueForJsonObject", REQUIRED,
2954 R"({
2955 "optionalAny": {
2956 "@type": "type.googleapis.com/google.protobuf.Value",
2957 "value": {
2958 "foo": 1
2959 }
2960 }
2961 })",
2962 R"(
2963 optional_any: {
2964 [type.googleapis.com/google.protobuf.Value] {
2965 struct_value: {
2966 fields: {
2967 key: "foo"
2968 value: {
2969 number_value: 1
2970 }
2971 }
2972 }
2973 }
2974 }
2975 )");
2976 RunValidJsonTest(
2977 "AnyWithValueForInteger", REQUIRED,
2978 R"({
2979 "optionalAny": {
2980 "@type": "type.googleapis.com/google.protobuf.Value",
2981 "value": 1
2982 }
2983 })",
2984 R"(
2985 optional_any: {
2986 [type.googleapis.com/google.protobuf.Value] {
2987 number_value: 1
2988 }
2989 }
2990 )");
2991
2992 RunValidJsonIgnoreUnknownTest(
2993 "IgnoreUnknownJsonNumber", REQUIRED,
2994 R"({
2995 "unknown": 1
2996 })",
2997 "");
2998 RunValidJsonIgnoreUnknownTest(
2999 "IgnoreUnknownJsonString", REQUIRED,
3000 R"({
3001 "unknown": "a"
3002 })",
3003 "");
3004 RunValidJsonIgnoreUnknownTest(
3005 "IgnoreUnknownJsonTrue", REQUIRED,
3006 R"({
3007 "unknown": true
3008 })",
3009 "");
3010 RunValidJsonIgnoreUnknownTest(
3011 "IgnoreUnknownJsonFalse", REQUIRED,
3012 R"({
3013 "unknown": false
3014 })",
3015 "");
3016 RunValidJsonIgnoreUnknownTest(
3017 "IgnoreUnknownJsonNull", REQUIRED,
3018 R"({
3019 "unknown": null
3020 })",
3021 "");
3022 RunValidJsonIgnoreUnknownTest(
3023 "IgnoreUnknownJsonObject", REQUIRED,
3024 R"({
3025 "unknown": {"a": 1}
3026 })",
3027 "");
Hao Nguyen6b4b9862019-04-24 15:29:17 -07003028
3029 ExpectParseFailureForJson("RejectTopLevelNull", REQUIRED, "null");
Feng Xiao6bbe1972018-08-08 17:00:41 -07003030}
3031
Feng Xiao6bbe1972018-08-08 17:00:41 -07003032} // namespace protobuf
3033} // namespace google