blob: 4297c05d76cd69a79f86d507ae91978b44e50b23 [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
Feng Xiao6bbe1972018-08-08 17:00:41 -0700152#define UNKNOWN_FIELD 666
153
Paul Yang0c4b6072019-08-02 14:35:44 -0700154enum class Packed {
155 UNSPECIFIED = 0,
156 TRUE = 1,
157 FALSE = 2,
158};
Feng Xiao6bbe1972018-08-08 17:00:41 -0700159
Paul Yang0c4b6072019-08-02 14:35:44 -0700160const FieldDescriptor* GetFieldForType(
161 FieldDescriptor::Type type, bool repeated, bool is_proto3,
162 Packed packed = Packed::UNSPECIFIED) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700163 const Descriptor* d = is_proto3 ?
164 TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
165 for (int i = 0; i < d->field_count(); i++) {
166 const FieldDescriptor* f = d->field(i);
167 if (f->type() == type && f->is_repeated() == repeated) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700168 if (packed == Packed::TRUE && !f->is_packed() ||
169 packed == Packed::FALSE && f->is_packed()) {
170 continue;
171 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700172 return f;
173 }
174 }
Paul Yang0c4b6072019-08-02 14:35:44 -0700175
176 string packed_string = "";
177 const string repeated_string = repeated ? "Repeated " : "Singular ";
178 const string proto_string = is_proto3 ? "Proto3" : "Proto2";
179 if (packed == Packed::TRUE) {
180 packed_string = "Packed ";
181 }
182 if (packed == Packed::FALSE) {
183 packed_string = "Unpacked ";
184 }
185 GOOGLE_LOG(FATAL) << "Couldn't find field with type: "
186 << repeated_string.c_str()
187 << packed_string.c_str()
188 << FieldDescriptor::TypeName(type)
189 << " for "
190 << proto_string.c_str();
Feng Xiao6bbe1972018-08-08 17:00:41 -0700191 return nullptr;
192}
193
194string UpperCase(string str) {
195 for (int i = 0; i < str.size(); i++) {
196 str[i] = toupper(str[i]);
197 }
198 return str;
199}
200
201std::unique_ptr<Message> NewTestMessage(bool is_proto3) {
202 std::unique_ptr<Message> prototype;
203 if (is_proto3) {
204 prototype.reset(new TestAllTypesProto3());
205 } else {
206 prototype.reset(new TestAllTypesProto2());
207 }
208 return prototype;
209}
210
211} // anonymous namespace
212
213namespace google {
214namespace protobuf {
215
Paul Yangcecba292018-12-14 16:05:03 -0800216bool BinaryAndJsonConformanceSuite::ParseJsonResponse(
217 const ConformanceResponse& response,
218 Message* test_message) {
219 string binary_protobuf;
220 util::Status status =
221 JsonToBinaryString(type_resolver_.get(), type_url_,
222 response.json_payload(), &binary_protobuf);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700223
Paul Yangcecba292018-12-14 16:05:03 -0800224 if (!status.ok()) {
225 return false;
226 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700227
Paul Yangcecba292018-12-14 16:05:03 -0800228 if (!test_message->ParseFromString(binary_protobuf)) {
229 GOOGLE_LOG(FATAL)
230 << "INTERNAL ERROR: internal JSON->protobuf transcode "
231 << "yielded unparseable proto.";
232 return false;
233 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700234
Paul Yangcecba292018-12-14 16:05:03 -0800235 return true;
236}
237
238bool BinaryAndJsonConformanceSuite::ParseResponse(
239 const ConformanceResponse& response,
240 const ConformanceRequestSetting& setting,
241 Message* test_message) {
242 const ConformanceRequest& request = setting.GetRequest();
243 WireFormat requested_output = request.requested_output_format();
244 const string& test_name = setting.GetTestName();
245 ConformanceLevel level = setting.GetLevel();
246
247 switch (response.result_case()) {
248 case ConformanceResponse::kProtobufPayload: {
249 if (requested_output != conformance::PROTOBUF) {
250 ReportFailure(
251 test_name, level, request, response,
252 StrCat("Test was asked for ", WireFormatToString(requested_output),
253 " output but provided PROTOBUF instead.").c_str());
254 return false;
255 }
256
257 if (!test_message->ParseFromString(response.protobuf_payload())) {
258 ReportFailure(test_name, level, request, response,
259 "Protobuf output we received from test was unparseable.");
260 return false;
261 }
262
263 break;
264 }
265
266 case ConformanceResponse::kJsonPayload: {
267 if (requested_output != conformance::JSON) {
268 ReportFailure(
269 test_name, level, request, response,
270 StrCat("Test was asked for ", WireFormatToString(requested_output),
271 " output but provided JSON instead.").c_str());
272 return false;
273 }
274
275 if (!ParseJsonResponse(response, test_message)) {
276 ReportFailure(test_name, level, request, response,
277 "JSON output we received from test was unparseable.");
278 return false;
279 }
280
281 break;
282 }
283
284 default:
285 GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
286 << response.result_case();
287 }
288
289 return true;
290}
291
292void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion (
Feng Xiao6bbe1972018-08-08 17:00:41 -0700293 const string& proto, const string& test_name, ConformanceLevel level,
294 bool is_proto3) {
295 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
296 // We don't expect output, but if the program erroneously accepts the protobuf
297 // we let it send its response as this. We must not leave it unspecified.
298 ConformanceRequestSetting setting(
299 level, conformance::PROTOBUF, conformance::PROTOBUF,
300 conformance::BINARY_TEST,
301 *prototype, test_name, proto);
302
303 const ConformanceRequest& request = setting.GetRequest();
304 ConformanceResponse response;
305 string effective_test_name =
306 StrCat(setting.ConformanceLevelToString(level),
307 (is_proto3 ? ".Proto3" : ".Proto2"),
308 ".ProtobufInput.", test_name);
309
310 RunTest(effective_test_name, request, &response);
311 if (response.result_case() == ConformanceResponse::kParseError) {
312 ReportSuccess(effective_test_name);
313 } else if (response.result_case() == ConformanceResponse::kSkipped) {
314 ReportSkip(effective_test_name, request, response);
315 } else {
316 ReportFailure(effective_test_name, level, request, response,
317 "Should have failed to parse, but didn't.");
318 }
319}
320
321// Expect that this precise protobuf will cause a parse error.
Paul Yangcecba292018-12-14 16:05:03 -0800322void BinaryAndJsonConformanceSuite::ExpectParseFailureForProto(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700323 const string& proto, const string& test_name, ConformanceLevel level) {
324 ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true);
325 ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false);
326}
327
328// Expect that this protobuf will cause a parse error, even if it is followed
329// by valid protobuf data. We can try running this twice: once with this
330// data verbatim and once with this data followed by some valid data.
331//
332// TODO(haberman): implement the second of these.
Paul Yangcecba292018-12-14 16:05:03 -0800333void BinaryAndJsonConformanceSuite::ExpectHardParseFailureForProto(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700334 const string& proto, const string& test_name, ConformanceLevel level) {
335 return ExpectParseFailureForProto(proto, test_name, level);
336}
337
Paul Yangcecba292018-12-14 16:05:03 -0800338void BinaryAndJsonConformanceSuite::RunValidJsonTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700339 const string& test_name, ConformanceLevel level, const string& input_json,
340 const string& equivalent_text_format) {
341 TestAllTypesProto3 prototype;
342 ConformanceRequestSetting setting1(
343 level, conformance::JSON, conformance::PROTOBUF,
344 conformance::JSON_TEST,
345 prototype, test_name, input_json);
346 RunValidInputTest(setting1, equivalent_text_format);
347 ConformanceRequestSetting setting2(
348 level, conformance::JSON, conformance::JSON,
349 conformance::JSON_TEST,
350 prototype, test_name, input_json);
351 RunValidInputTest(setting2, equivalent_text_format);
352}
353
Paul Yangcecba292018-12-14 16:05:03 -0800354void BinaryAndJsonConformanceSuite::RunValidJsonTestWithProtobufInput(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700355 const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
356 const string& equivalent_text_format) {
357 ConformanceRequestSetting setting(
358 level, conformance::PROTOBUF, conformance::JSON,
359 conformance::JSON_TEST,
360 input, test_name, input.SerializeAsString());
361 RunValidInputTest(setting, equivalent_text_format);
362}
363
Paul Yangcecba292018-12-14 16:05:03 -0800364void BinaryAndJsonConformanceSuite::RunValidJsonIgnoreUnknownTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700365 const string& test_name, ConformanceLevel level, const string& input_json,
366 const string& equivalent_text_format) {
367 TestAllTypesProto3 prototype;
368 ConformanceRequestSetting setting(
369 level, conformance::JSON, conformance::PROTOBUF,
370 conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST,
371 prototype, test_name, input_json);
372 RunValidInputTest(setting, equivalent_text_format);
373}
374
Paul Yangcecba292018-12-14 16:05:03 -0800375void BinaryAndJsonConformanceSuite::RunValidProtobufTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700376 const string& test_name, ConformanceLevel level,
377 const string& input_protobuf, const string& equivalent_text_format,
378 bool is_proto3) {
379 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
380
381 ConformanceRequestSetting setting1(
382 level, conformance::PROTOBUF, conformance::PROTOBUF,
383 conformance::BINARY_TEST,
384 *prototype, test_name, input_protobuf);
385 RunValidInputTest(setting1, equivalent_text_format);
386
387 if (is_proto3) {
388 ConformanceRequestSetting setting2(
389 level, conformance::PROTOBUF, conformance::JSON,
390 conformance::BINARY_TEST,
391 *prototype, test_name, input_protobuf);
392 RunValidInputTest(setting2, equivalent_text_format);
393 }
394}
395
Paul Yangcecba292018-12-14 16:05:03 -0800396void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700397 const string& test_name, ConformanceLevel level,
398 const string& input_protobuf, bool is_proto3) {
Paul Yanga9bb6562019-07-26 10:05:14 -0700399 RunValidBinaryProtobufTest(
400 test_name, level, input_protobuf, input_protobuf, is_proto3);
401}
402
403void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest(
404 const string& test_name, ConformanceLevel level,
405 const string& input_protobuf,
406 const string& expected_protobuf,
407 bool is_proto3) {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700408 std::unique_ptr<Message> prototype = NewTestMessage(is_proto3);
409 ConformanceRequestSetting setting(
410 level, conformance::PROTOBUF, conformance::PROTOBUF,
411 conformance::BINARY_TEST,
412 *prototype, test_name, input_protobuf);
Paul Yanga9bb6562019-07-26 10:05:14 -0700413 RunValidBinaryInputTest(setting, expected_protobuf, true);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700414}
415
Paul Yangcecba292018-12-14 16:05:03 -0800416void BinaryAndJsonConformanceSuite::RunValidProtobufTestWithMessage(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700417 const string& test_name, ConformanceLevel level, const Message *input,
418 const string& equivalent_text_format, bool is_proto3) {
419 RunValidProtobufTest(test_name, level, input->SerializeAsString(),
420 equivalent_text_format, is_proto3);
421}
422
423// According to proto3 JSON specification, JSON serializers follow more strict
424// rules than parsers (e.g., a serializer must serialize int32 values as JSON
425// numbers while the parser is allowed to accept them as JSON strings). This
426// method allows strict checking on a proto3 JSON serializer by inspecting
427// the JSON output directly.
Paul Yangcecba292018-12-14 16:05:03 -0800428void BinaryAndJsonConformanceSuite::RunValidJsonTestWithValidator(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700429 const string& test_name, ConformanceLevel level, const string& input_json,
430 const Validator& validator) {
431 TestAllTypesProto3 prototype;
432 ConformanceRequestSetting setting(
433 level, conformance::JSON, conformance::JSON,
434 conformance::JSON_TEST,
435 prototype, test_name, input_json);
436 const ConformanceRequest& request = setting.GetRequest();
437 ConformanceResponse response;
438 string effective_test_name =
439 StrCat(setting.ConformanceLevelToString(level),
440 ".Proto3.JsonInput.",
441 test_name, ".Validator");
442
443 RunTest(effective_test_name, request, &response);
444
445 if (response.result_case() == ConformanceResponse::kSkipped) {
446 ReportSkip(effective_test_name, request, response);
447 return;
448 }
449
450 if (response.result_case() != ConformanceResponse::kJsonPayload) {
451 ReportFailure(effective_test_name, level, request, response,
452 "Expected JSON payload but got type %d.",
453 response.result_case());
454 return;
455 }
456 Json::Reader reader;
457 Json::Value value;
458 if (!reader.parse(response.json_payload(), value)) {
459 ReportFailure(effective_test_name, level, request, response,
460 "JSON payload cannot be parsed as valid JSON: %s",
461 reader.getFormattedErrorMessages().c_str());
462 return;
463 }
464 if (!validator(value)) {
465 ReportFailure(effective_test_name, level, request, response,
466 "JSON payload validation failed.");
467 return;
468 }
469 ReportSuccess(effective_test_name);
470}
471
Paul Yangcecba292018-12-14 16:05:03 -0800472void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700473 const string& test_name, ConformanceLevel level, const string& input_json) {
474 TestAllTypesProto3 prototype;
475 // We don't expect output, but if the program erroneously accepts the protobuf
476 // we let it send its response as this. We must not leave it unspecified.
477 ConformanceRequestSetting setting(
478 level, conformance::JSON, conformance::JSON,
479 conformance::JSON_TEST,
480 prototype, test_name, input_json);
481 const ConformanceRequest& request = setting.GetRequest();
482 ConformanceResponse response;
483 string effective_test_name =
484 StrCat(setting.ConformanceLevelToString(level),
485 ".Proto3.JsonInput.", test_name);
486
487 RunTest(effective_test_name, request, &response);
488 if (response.result_case() == ConformanceResponse::kParseError) {
489 ReportSuccess(effective_test_name);
490 } else if (response.result_case() == ConformanceResponse::kSkipped) {
491 ReportSkip(effective_test_name, request, response);
492 } else {
493 ReportFailure(effective_test_name, level, request, response,
494 "Should have failed to parse, but didn't.");
495 }
496}
497
Paul Yangcecba292018-12-14 16:05:03 -0800498void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700499 const string& test_name, ConformanceLevel level, const string& text_format) {
500 TestAllTypesProto3 payload_message;
501 GOOGLE_CHECK(
502 TextFormat::ParseFromString(text_format, &payload_message))
503 << "Failed to parse: " << text_format;
504
505 TestAllTypesProto3 prototype;
506 ConformanceRequestSetting setting(
507 level, conformance::PROTOBUF, conformance::JSON,
508 conformance::JSON_TEST,
509 prototype, test_name, payload_message.SerializeAsString());
510 const ConformanceRequest& request = setting.GetRequest();
511 ConformanceResponse response;
512 string effective_test_name =
513 StrCat(setting.ConformanceLevelToString(level),
514 ".", test_name, ".JsonOutput");
515
516 RunTest(effective_test_name, request, &response);
517 if (response.result_case() == ConformanceResponse::kSerializeError) {
518 ReportSuccess(effective_test_name);
519 } else if (response.result_case() == ConformanceResponse::kSkipped) {
520 ReportSkip(effective_test_name, request, response);
521 } else {
522 ReportFailure(effective_test_name, level, request, response,
523 "Should have failed to serialize, but didn't.");
524 }
525}
526
527//TODO: proto2?
Paul Yangcecba292018-12-14 16:05:03 -0800528void BinaryAndJsonConformanceSuite::TestPrematureEOFForType(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700529 FieldDescriptor::Type type) {
530 // Incomplete values for each wire type.
531 static const string incompletes[6] = {
532 string("\x80"), // VARINT
533 string("abcdefg"), // 64BIT
534 string("\x80"), // DELIMITED (partial length)
535 string(), // START_GROUP (no value required)
536 string(), // END_GROUP (no value required)
537 string("abc") // 32BIT
538 };
539
540 const FieldDescriptor* field = GetFieldForType(type, false, true);
541 const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
542 WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
543 static_cast<WireFormatLite::FieldType>(type));
544 const string& incomplete = incompletes[wire_type];
545 const string type_name =
546 UpperCase(string(".") + FieldDescriptor::TypeName(type));
547
548 ExpectParseFailureForProto(
549 tag(field->number(), wire_type),
550 "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
551
552 ExpectParseFailureForProto(
553 tag(rep_field->number(), wire_type),
554 "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
555
556 ExpectParseFailureForProto(
557 tag(UNKNOWN_FIELD, wire_type),
558 "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
559
560 ExpectParseFailureForProto(
561 cat( tag(field->number(), wire_type), incomplete ),
562 "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
563
564 ExpectParseFailureForProto(
565 cat( tag(rep_field->number(), wire_type), incomplete ),
566 "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
567
568 ExpectParseFailureForProto(
569 cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
570 "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
571
572 if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
573 ExpectParseFailureForProto(
574 cat( tag(field->number(), wire_type), varint(1) ),
575 "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
576 REQUIRED);
577
578 ExpectParseFailureForProto(
579 cat( tag(rep_field->number(), wire_type), varint(1) ),
580 "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
581 REQUIRED);
582
583 // EOF in the middle of delimited data for unknown value.
584 ExpectParseFailureForProto(
585 cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
586 "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
587
588 if (type == FieldDescriptor::TYPE_MESSAGE) {
589 // Submessage ends in the middle of a value.
590 string incomplete_submsg =
591 cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
592 incompletes[WireFormatLite::WIRETYPE_VARINT] );
593 ExpectHardParseFailureForProto(
594 cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
595 varint(incomplete_submsg.size()),
596 incomplete_submsg ),
597 "PrematureEofInSubmessageValue" + type_name, REQUIRED);
598 }
599 } else if (type != FieldDescriptor::TYPE_GROUP) {
600 // Non-delimited, non-group: eligible for packing.
601
602 // Packed region ends in the middle of a value.
603 ExpectHardParseFailureForProto(
604 cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
605 varint(incomplete.size()), incomplete),
606 "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
607
608 // EOF in the middle of packed region.
609 ExpectParseFailureForProto(
610 cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
611 varint(1)),
612 "PrematureEofInPackedField" + type_name, REQUIRED);
613 }
614}
615
Paul Yangcecba292018-12-14 16:05:03 -0800616void BinaryAndJsonConformanceSuite::TestValidDataForType(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700617 FieldDescriptor::Type type,
618 std::vector<std::pair<std::string, std::string>> values) {
619 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
620 const string type_name =
621 UpperCase(string(".") + FieldDescriptor::TypeName(type));
622 WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
623 static_cast<WireFormatLite::FieldType>(type));
624 const FieldDescriptor* field = GetFieldForType(type, false, is_proto3);
625 const FieldDescriptor* rep_field = GetFieldForType(type, true, is_proto3);
626
Paul Yanga9bb6562019-07-26 10:05:14 -0700627 // Test singular data for singular fields.
Paul Yang2849a792019-07-24 12:26:40 -0700628 for (size_t i = 0; i < values.size(); i++) {
Paul Yanga9bb6562019-07-26 10:05:14 -0700629 string proto =
630 cat(tag(field->number(), wire_type), values[i].first);
631 string expected_proto =
632 cat(tag(field->number(), wire_type), values[i].second);
633 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
634 test_message->MergeFromString(expected_proto);
635 string text = test_message->DebugString();
636
Paul Yang2849a792019-07-24 12:26:40 -0700637 RunValidProtobufTest(StrCat("ValidDataScalar", type_name, "[", i, "]"),
Paul Yanga9bb6562019-07-26 10:05:14 -0700638 REQUIRED, proto, text, is_proto3);
Paul Yang2849a792019-07-24 12:26:40 -0700639 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700640
Paul Yanga9bb6562019-07-26 10:05:14 -0700641 // Test repeated data for singular fields.
Paul Yang2849a792019-07-24 12:26:40 -0700642 // For scalar message fields, repeated values are merged, which is tested
643 // separately.
644 if (type != FieldDescriptor::TYPE_MESSAGE) {
Paul Yanga9bb6562019-07-26 10:05:14 -0700645 string proto;
646 for (size_t i = 0; i < values.size(); i++) {
647 proto += cat(tag(field->number(), wire_type), values[i].first);
648 }
649 string expected_proto =
650 cat(tag(field->number(), wire_type), values.back().second);
651 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
652 test_message->MergeFromString(expected_proto);
653 string text = test_message->DebugString();
654
Paul Yang2849a792019-07-24 12:26:40 -0700655 RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
656 proto, text, is_proto3);
657 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700658
Paul Yanga9bb6562019-07-26 10:05:14 -0700659 // Test repeated fields.
660 if (FieldDescriptor::IsTypePackable(type)) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700661 const FieldDescriptor* packed_field =
662 GetFieldForType(type, true, is_proto3, Packed::TRUE);
663 const FieldDescriptor* unpacked_field =
664 GetFieldForType(type, true, is_proto3, Packed::FALSE);
665
666 string default_proto_packed;
667 string default_proto_unpacked;
668 string default_proto_packed_expected;
669 string default_proto_unpacked_expected;
670 string packed_proto_packed;
671 string packed_proto_unpacked;
Paul Yanga9bb6562019-07-26 10:05:14 -0700672 string packed_proto_expected;
Paul Yang0c4b6072019-08-02 14:35:44 -0700673 string unpacked_proto_packed;
674 string unpacked_proto_unpacked;
Paul Yanga9bb6562019-07-26 10:05:14 -0700675 string unpacked_proto_expected;
Feng Xiao6bbe1972018-08-08 17:00:41 -0700676
Paul Yanga9bb6562019-07-26 10:05:14 -0700677 for (size_t i = 0; i < values.size(); i++) {
Paul Yang0c4b6072019-08-02 14:35:44 -0700678 default_proto_unpacked +=
Paul Yanga9bb6562019-07-26 10:05:14 -0700679 cat(tag(rep_field->number(), wire_type), values[i].first);
Paul Yang0c4b6072019-08-02 14:35:44 -0700680 default_proto_unpacked_expected +=
Paul Yanga9bb6562019-07-26 10:05:14 -0700681 cat(tag(rep_field->number(), wire_type), values[i].second);
Paul Yang0c4b6072019-08-02 14:35:44 -0700682 default_proto_packed += values[i].first;
683 default_proto_packed_expected += values[i].second;
684 packed_proto_unpacked +=
685 cat(tag(packed_field->number(), wire_type), values[i].first);
686 packed_proto_packed += values[i].first;
Paul Yanga9bb6562019-07-26 10:05:14 -0700687 packed_proto_expected += values[i].second;
Paul Yang0c4b6072019-08-02 14:35:44 -0700688 unpacked_proto_unpacked +=
689 cat(tag(unpacked_field->number(), wire_type), values[i].first);
690 unpacked_proto_packed += values[i].first;
691 unpacked_proto_expected +=
692 cat(tag(unpacked_field->number(), wire_type), values[i].second);
Paul Yanga9bb6562019-07-26 10:05:14 -0700693 }
Paul Yang0c4b6072019-08-02 14:35:44 -0700694 default_proto_packed =
Paul Yanga9bb6562019-07-26 10:05:14 -0700695 cat(tag(rep_field->number(),
696 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
Paul Yang0c4b6072019-08-02 14:35:44 -0700697 delim(default_proto_packed));
698 default_proto_packed_expected =
Paul Yanga9bb6562019-07-26 10:05:14 -0700699 cat(tag(rep_field->number(),
700 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
Paul Yang0c4b6072019-08-02 14:35:44 -0700701 delim(default_proto_packed_expected));
702 packed_proto_packed =
703 cat(tag(packed_field->number(),
704 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
705 delim(packed_proto_packed));
706 packed_proto_expected =
707 cat(tag(packed_field->number(),
708 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
Paul Yanga9bb6562019-07-26 10:05:14 -0700709 delim(packed_proto_expected));
Paul Yang0c4b6072019-08-02 14:35:44 -0700710 unpacked_proto_packed =
711 cat(tag(unpacked_field->number(),
712 WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
713 delim(unpacked_proto_packed));
714
Paul Yanga9bb6562019-07-26 10:05:14 -0700715
716 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
Paul Yang0c4b6072019-08-02 14:35:44 -0700717 test_message->MergeFromString(default_proto_packed_expected);
Paul Yanga9bb6562019-07-26 10:05:14 -0700718 string text = test_message->DebugString();
719
720 // Ensures both packed and unpacked data can be parsed.
721 RunValidProtobufTest(
722 StrCat("ValidDataRepeated", type_name, ".UnpackedInput"),
Paul Yang0c4b6072019-08-02 14:35:44 -0700723 REQUIRED, default_proto_unpacked, text, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700724 RunValidProtobufTest(
725 StrCat("ValidDataRepeated", type_name, ".PackedInput"),
Paul Yang0c4b6072019-08-02 14:35:44 -0700726 REQUIRED, default_proto_packed, text, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700727
728 // proto2 should encode as unpacked by default and proto3 should encode as
729 // packed by default.
730 string expected_proto =
Paul Yang0c4b6072019-08-02 14:35:44 -0700731 rep_field->is_packed() ? default_proto_packed_expected :
732 default_proto_unpacked_expected;
Paul Yanga9bb6562019-07-26 10:05:14 -0700733 RunValidBinaryProtobufTest(
734 StrCat("ValidDataRepeated", type_name,
735 ".UnpackedInput.DefaultOutput"),
736 RECOMMENDED,
Paul Yang0c4b6072019-08-02 14:35:44 -0700737 default_proto_unpacked,
Paul Yanga9bb6562019-07-26 10:05:14 -0700738 expected_proto, is_proto3);
739 RunValidBinaryProtobufTest(
740 StrCat("ValidDataRepeated", type_name,
741 ".PackedInput.DefaultOutput"),
742 RECOMMENDED,
Paul Yang0c4b6072019-08-02 14:35:44 -0700743 default_proto_packed,
Paul Yanga9bb6562019-07-26 10:05:14 -0700744 expected_proto, is_proto3);
Paul Yang0c4b6072019-08-02 14:35:44 -0700745 RunValidBinaryProtobufTest(
746 StrCat("ValidDataRepeated", type_name,
747 ".UnpackedInput.PackedOutput"),
748 RECOMMENDED,
749 packed_proto_unpacked,
750 packed_proto_expected, is_proto3);
751 RunValidBinaryProtobufTest(
752 StrCat("ValidDataRepeated", type_name,
753 ".PackedInput.PackedOutput"),
754 RECOMMENDED,
755 packed_proto_packed,
756 packed_proto_expected, is_proto3);
757 RunValidBinaryProtobufTest(
758 StrCat("ValidDataRepeated", type_name,
759 ".UnpackedInput.UnpackedOutput"),
760 RECOMMENDED,
761 unpacked_proto_unpacked,
762 unpacked_proto_expected, is_proto3);
763 RunValidBinaryProtobufTest(
764 StrCat("ValidDataRepeated", type_name,
765 ".PackedInput.UnpackedOutput"),
766 RECOMMENDED,
767 unpacked_proto_packed,
768 unpacked_proto_expected, is_proto3);
Paul Yanga9bb6562019-07-26 10:05:14 -0700769 } else {
770 string proto;
771 string expected_proto;
772 for (size_t i = 0; i < values.size(); i++) {
773 proto += cat(tag(rep_field->number(), wire_type), values[i].first);
774 expected_proto +=
775 cat(tag(rep_field->number(), wire_type), values[i].second);
776 }
777 std::unique_ptr<Message> test_message = NewTestMessage(is_proto3);
778 test_message->MergeFromString(expected_proto);
779 string text = test_message->DebugString();
780
781 RunValidProtobufTest(
782 StrCat("ValidDataRepeated", type_name),
783 REQUIRED, proto, text, is_proto3);
Feng Xiao6bbe1972018-08-08 17:00:41 -0700784 }
Feng Xiao6bbe1972018-08-08 17:00:41 -0700785 }
786}
787
Paul Yang2849a792019-07-24 12:26:40 -0700788void BinaryAndJsonConformanceSuite::TestValidDataForRepeatedScalarMessage() {
789 std::vector<std::string> values = {
790 delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
791 delim(cat(
792 tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234),
793 tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1234),
794 tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1234)
795 )))),
796 delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
797 delim(cat(
798 tag(1, WireFormatLite::WIRETYPE_VARINT), varint(4321),
799 tag(3, WireFormatLite::WIRETYPE_VARINT), varint(4321),
800 tag(31, WireFormatLite::WIRETYPE_VARINT), varint(4321)
801 )))),
802 };
803
804 const std::string expected =
805 R"({
806 corecursive: {
807 optional_int32: 4321,
808 optional_int64: 1234,
809 optional_uint32: 4321,
810 repeated_int32: [1234, 4321],
811 }
812 })";
813
814 for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) {
815 string proto;
816 const FieldDescriptor* field =
817 GetFieldForType(FieldDescriptor::TYPE_MESSAGE, false, is_proto3);
818 for (size_t i = 0; i < values.size(); i++) {
819 proto +=
820 cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
821 values[i]);
822 }
823
824 RunValidProtobufTest(
825 "RepeatedScalarMessageMerge", REQUIRED, proto,
826 field->name() + ": " + expected, is_proto3);
827 }
828}
829
Feng Xiao6bbe1972018-08-08 17:00:41 -0700830// TODO: proto2?
Paul Yangcecba292018-12-14 16:05:03 -0800831void BinaryAndJsonConformanceSuite::TestIllegalTags() {
Feng Xiao6bbe1972018-08-08 17:00:41 -0700832 // field num 0 is illegal
833 string nullfield[] = {
834 "\1DEADBEEF",
835 "\2\1\1",
836 "\3\4",
837 "\5DEAD"
838 };
839 for (int i = 0; i < 4; i++) {
840 string name = "IllegalZeroFieldNum_Case_0";
841 name.back() += i;
842 ExpectParseFailureForProto(nullfield[i], name, REQUIRED);
843 }
844}
845template <class MessageType>
Paul Yangcecba292018-12-14 16:05:03 -0800846void BinaryAndJsonConformanceSuite::TestOneofMessage (
Feng Xiao6bbe1972018-08-08 17:00:41 -0700847 MessageType &message, bool is_proto3) {
848 message.set_oneof_uint32(0);
849 RunValidProtobufTestWithMessage(
850 "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3);
851 message.mutable_oneof_nested_message()->set_a(0);
852 RunValidProtobufTestWithMessage(
853 "OneofZeroMessage", RECOMMENDED, &message,
854 is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
855 is_proto3);
856 message.mutable_oneof_nested_message()->set_a(1);
857 RunValidProtobufTestWithMessage(
858 "OneofZeroMessageSetTwice", RECOMMENDED, &message,
859 "oneof_nested_message: {a: 1}",
860 is_proto3);
861 message.set_oneof_string("");
862 RunValidProtobufTestWithMessage(
863 "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3);
864 message.set_oneof_bytes("");
865 RunValidProtobufTestWithMessage(
866 "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3);
867 message.set_oneof_bool(false);
868 RunValidProtobufTestWithMessage(
869 "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3);
870 message.set_oneof_uint64(0);
871 RunValidProtobufTestWithMessage(
872 "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3);
873 message.set_oneof_float(0.0f);
874 RunValidProtobufTestWithMessage(
875 "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3);
876 message.set_oneof_double(0.0);
877 RunValidProtobufTestWithMessage(
878 "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3);
879 message.set_oneof_enum(MessageType::FOO);
880 RunValidProtobufTestWithMessage(
881 "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3);
882}
883
884template <class MessageType>
Paul Yangcecba292018-12-14 16:05:03 -0800885void BinaryAndJsonConformanceSuite::TestUnknownMessage(
Feng Xiao6bbe1972018-08-08 17:00:41 -0700886 MessageType& message, bool is_proto3) {
887 message.ParseFromString("\xA8\x1F\x01");
888 RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
889 message.SerializeAsString(), is_proto3);
890}
891
Paul Yangcecba292018-12-14 16:05:03 -0800892void BinaryAndJsonConformanceSuite::RunSuiteImpl() {
Yilun Chongd8c25012019-02-22 18:13:33 +0800893 // Hack to get the list of test failures based on whether
894 // GOOGLE3_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER is enabled or not.
895 conformance::FailureSet failure_set;
896 ConformanceRequest req;
897 ConformanceResponse res;
898 req.set_message_type(failure_set.GetTypeName());
899 req.set_protobuf_payload("");
900 req.set_requested_output_format(conformance::WireFormat::PROTOBUF);
901 RunTest("FindFailures", req, &res);
902 GOOGLE_CHECK(failure_set.MergeFromString(res.protobuf_payload()));
903 for (const string& failure : failure_set.failure()) {
904 AddExpectedFailedTest(failure);
905 }
906
Feng Xiao6bbe1972018-08-08 17:00:41 -0700907 type_resolver_.reset(NewTypeResolverForDescriptorPool(
908 kTypeUrlPrefix, DescriptorPool::generated_pool()));
909 type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
910
911 for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
912 if (i == FieldDescriptor::TYPE_GROUP) continue;
913 TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
914 }
915
916 TestIllegalTags();
917
918 int64 kInt64Min = -9223372036854775808ULL;
919 int64 kInt64Max = 9223372036854775807ULL;
920 uint64 kUint64Max = 18446744073709551615ULL;
921 int32 kInt32Max = 2147483647;
922 int32 kInt32Min = -2147483648;
923 uint32 kUint32Max = 4294967295UL;
924
925 TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700926 {dbl(0.1), dbl(0.1)},
927 {dbl(1.7976931348623157e+308), dbl(1.7976931348623157e+308)},
928 {dbl(2.22507385850720138309e-308), dbl(2.22507385850720138309e-308)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700929 });
930 TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700931 {flt(0.1), flt(0.1)},
932 {flt(1.00000075e-36), flt(1.00000075e-36)},
933 {flt(3.402823e+38), flt(3.402823e+38)}, // 3.40282347e+38
934 {flt(1.17549435e-38f), flt(1.17549435e-38)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700935 });
936 TestValidDataForType(FieldDescriptor::TYPE_INT64, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700937 {varint(12345), varint(12345)},
938 {varint(kInt64Max), varint(kInt64Max)},
939 {varint(kInt64Min), varint(kInt64Min)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700940 });
941 TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700942 {varint(12345), varint(12345)},
943 {varint(kUint64Max), varint(kUint64Max)},
944 {varint(0), varint(0)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700945 });
946 TestValidDataForType(FieldDescriptor::TYPE_INT32, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700947 {varint(12345), varint(12345)},
948 {longvarint(12345, 2), varint(12345)},
949 {longvarint(12345, 7), varint(12345)},
950 {varint(kInt32Max), varint(kInt32Max)},
951 {varint(kInt32Min), varint(kInt32Min)},
952 {varint(1LL << 33), varint(0)},
953 {varint((1LL << 33) - 1), varint(-1)},
Feng Xiao6bbe1972018-08-08 17:00:41 -0700954 });
955 TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700956 {varint(12345), varint(12345)},
957 {longvarint(12345, 2), varint(12345)},
958 {longvarint(12345, 7), varint(12345)},
959 {varint(kUint32Max), varint(kUint32Max)}, // UINT32_MAX
960 {varint(0), varint(0)},
961 {varint(1LL << 33), varint(0)},
962 {varint((1LL << 33) - 1), varint((1LL << 32) - 1)},
Feng Xiao6bbe1972018-08-08 17:00:41 -0700963 });
964 TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700965 {u64(12345), u64(12345)},
966 {u64(kUint64Max), u64(kUint64Max)},
967 {u64(0), u64(0)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700968 });
969 TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700970 {u32(12345), u32(12345)},
971 {u32(kUint32Max), u32(kUint32Max)}, // UINT32_MAX
972 {u32(0), u32(0)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700973 });
974 TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700975 {u64(12345), u64(12345)},
976 {u64(kInt64Max), u64(kInt64Max)},
977 {u64(kInt64Min), u64(kInt64Min)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700978 });
979 TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700980 {u32(12345), u32(12345)},
981 {u32(kInt32Max), u32(kInt32Max)},
982 {u32(kInt32Min), u32(kInt32Min)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700983 });
984 TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700985 {varint(1), varint(1)},
986 {varint(0), varint(0)},
987 {varint(12345678), varint(1)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700988 });
989 TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700990 {zz32(12345), zz32(12345)},
991 {zz32(kInt32Max), zz32(kInt32Max)},
992 {zz32(kInt32Min), zz32(kInt32Min)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700993 });
994 TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
Paul Yanga9bb6562019-07-26 10:05:14 -0700995 {zz64(12345), zz64(12345)},
996 {zz64(kInt64Max), zz64(kInt64Max)},
997 {zz64(kInt64Min), zz64(kInt64Min)}
Feng Xiao6bbe1972018-08-08 17:00:41 -0700998 });
Paul Yangeef87dd2019-07-22 16:52:31 -0700999 TestValidDataForType(FieldDescriptor::TYPE_STRING, {
Paul Yanga9bb6562019-07-26 10:05:14 -07001000 {delim("Hello world!"), delim("Hello world!")},
Paul Yangeef87dd2019-07-22 16:52:31 -07001001 {delim("\'\"\?\\\a\b\f\n\r\t\v"),
Paul Yanga9bb6562019-07-26 10:05:14 -07001002 delim("\'\"\?\\\a\b\f\n\r\t\v")}, // escape
1003 {delim("谷歌"), delim("谷歌")}, // Google in Chinese
1004 {delim("\u8C37\u6B4C"), delim("谷歌")}, // unicode escape
1005 {delim("\u8c37\u6b4c"), delim("谷歌")}, // lowercase unicode
1006 {delim("\xF0\x9F\x98\x81"), delim("\xF0\x9F\x98\x81")}, // emoji: 😁
1007 {delim(""), delim("")},
Paul Yangeef87dd2019-07-22 16:52:31 -07001008 });
Paul Yang29e4fad2019-07-23 12:42:30 -07001009 TestValidDataForType(FieldDescriptor::TYPE_BYTES, {
Paul Yanga9bb6562019-07-26 10:05:14 -07001010 {delim("\x01\x02"), delim("\x01\x02")},
1011 {delim("\xfb"), delim("\xfb")},
1012 {delim(""), delim("")},
Paul Yang29e4fad2019-07-23 12:42:30 -07001013 });
Paul Yang455440f2019-07-23 15:07:26 -07001014 TestValidDataForType(FieldDescriptor::TYPE_ENUM, {
Paul Yanga9bb6562019-07-26 10:05:14 -07001015 {varint(0), varint(0)},
1016 {varint(1), varint(1)},
1017 {varint(2), varint(2)},
1018 {varint(-1), varint(-1)},
Paul Yang455440f2019-07-23 15:07:26 -07001019 });
Paul Yang2849a792019-07-24 12:26:40 -07001020 TestValidDataForRepeatedScalarMessage();
1021 TestValidDataForType(FieldDescriptor::TYPE_MESSAGE, {
1022 {delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))),
Paul Yanga9bb6562019-07-26 10:05:14 -07001023 delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)))},
1024 {delim(""), delim("")},
Paul Yang2849a792019-07-24 12:26:40 -07001025 });
Feng Xiao6bbe1972018-08-08 17:00:41 -07001026
1027 // TODO(haberman):
Feng Xiao6bbe1972018-08-08 17:00:41 -07001028 // TestValidDataForType(FieldDescriptor::TYPE_GROUP
Feng Xiao6bbe1972018-08-08 17:00:41 -07001029
1030 RunValidJsonTest("HelloWorld", REQUIRED,
1031 "{\"optionalString\":\"Hello, World!\"}",
1032 "optional_string: 'Hello, World!'");
1033
1034 // NOTE: The spec for JSON support is still being sorted out, these may not
1035 // all be correct.
1036 // Test field name conventions.
1037 RunValidJsonTest(
1038 "FieldNameInSnakeCase", REQUIRED,
1039 R"({
1040 "fieldname1": 1,
1041 "fieldName2": 2,
1042 "FieldName3": 3,
1043 "fieldName4": 4
1044 })",
1045 R"(
1046 fieldname1: 1
1047 field_name2: 2
1048 _field_name3: 3
1049 field__name4_: 4
1050 )");
1051 RunValidJsonTest(
1052 "FieldNameWithNumbers", REQUIRED,
1053 R"({
1054 "field0name5": 5,
1055 "field0Name6": 6
1056 })",
1057 R"(
1058 field0name5: 5
1059 field_0_name6: 6
1060 )");
1061 RunValidJsonTest(
1062 "FieldNameWithMixedCases", REQUIRED,
1063 R"({
1064 "fieldName7": 7,
1065 "FieldName8": 8,
1066 "fieldName9": 9,
1067 "FieldName10": 10,
1068 "FIELDNAME11": 11,
1069 "FIELDName12": 12
1070 })",
1071 R"(
1072 fieldName7: 7
1073 FieldName8: 8
1074 field_Name9: 9
1075 Field_Name10: 10
1076 FIELD_NAME11: 11
1077 FIELD_name12: 12
1078 )");
1079 RunValidJsonTest(
1080 "FieldNameWithDoubleUnderscores", RECOMMENDED,
1081 R"({
1082 "FieldName13": 13,
1083 "FieldName14": 14,
1084 "fieldName15": 15,
1085 "fieldName16": 16,
1086 "fieldName17": 17,
1087 "FieldName18": 18
1088 })",
1089 R"(
1090 __field_name13: 13
1091 __Field_name14: 14
1092 field__name15: 15
1093 field__Name16: 16
1094 field_name17__: 17
1095 Field_name18__: 18
1096 )");
1097 // Using the original proto field name in JSON is also allowed.
1098 RunValidJsonTest(
1099 "OriginalProtoFieldName", REQUIRED,
1100 R"({
1101 "fieldname1": 1,
1102 "field_name2": 2,
1103 "_field_name3": 3,
1104 "field__name4_": 4,
1105 "field0name5": 5,
1106 "field_0_name6": 6,
1107 "fieldName7": 7,
1108 "FieldName8": 8,
1109 "field_Name9": 9,
1110 "Field_Name10": 10,
1111 "FIELD_NAME11": 11,
1112 "FIELD_name12": 12,
1113 "__field_name13": 13,
1114 "__Field_name14": 14,
1115 "field__name15": 15,
1116 "field__Name16": 16,
1117 "field_name17__": 17,
1118 "Field_name18__": 18
1119 })",
1120 R"(
1121 fieldname1: 1
1122 field_name2: 2
1123 _field_name3: 3
1124 field__name4_: 4
1125 field0name5: 5
1126 field_0_name6: 6
1127 fieldName7: 7
1128 FieldName8: 8
1129 field_Name9: 9
1130 Field_Name10: 10
1131 FIELD_NAME11: 11
1132 FIELD_name12: 12
1133 __field_name13: 13
1134 __Field_name14: 14
1135 field__name15: 15
1136 field__Name16: 16
1137 field_name17__: 17
1138 Field_name18__: 18
1139 )");
1140 // Field names can be escaped.
1141 RunValidJsonTest(
1142 "FieldNameEscaped", REQUIRED,
1143 R"({"fieldn\u0061me1": 1})",
1144 "fieldname1: 1");
1145 // String ends with escape character.
1146 ExpectParseFailureForJson(
1147 "StringEndsWithEscapeChar", RECOMMENDED,
1148 "{\"optionalString\": \"abc\\");
1149 // Field names must be quoted (or it's not valid JSON).
1150 ExpectParseFailureForJson(
1151 "FieldNameNotQuoted", RECOMMENDED,
1152 "{fieldname1: 1}");
1153 // Trailing comma is not allowed (not valid JSON).
1154 ExpectParseFailureForJson(
1155 "TrailingCommaInAnObject", RECOMMENDED,
1156 R"({"fieldname1":1,})");
1157 ExpectParseFailureForJson(
1158 "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
1159 R"({"fieldname1":1 ,})");
1160 ExpectParseFailureForJson(
1161 "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
1162 R"({"fieldname1":1 , })");
1163 ExpectParseFailureForJson(
1164 "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
1165 R"({
1166 "fieldname1":1,
1167 })");
1168 // JSON doesn't support comments.
1169 ExpectParseFailureForJson(
1170 "JsonWithComments", RECOMMENDED,
1171 R"({
1172 // This is a comment.
1173 "fieldname1": 1
1174 })");
1175 // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
1176 RunValidJsonTest(
1177 "OneLineNoSpaces", RECOMMENDED,
1178 "{\"optionalInt32\":1,\"optionalInt64\":2}",
1179 R"(
1180 optional_int32: 1
1181 optional_int64: 2
1182 )");
1183 RunValidJsonTest(
1184 "OneLineWithSpaces", RECOMMENDED,
1185 "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
1186 R"(
1187 optional_int32: 1
1188 optional_int64: 2
1189 )");
1190 RunValidJsonTest(
1191 "MultilineNoSpaces", RECOMMENDED,
1192 "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
1193 R"(
1194 optional_int32: 1
1195 optional_int64: 2
1196 )");
1197 RunValidJsonTest(
1198 "MultilineWithSpaces", RECOMMENDED,
1199 "{\n \"optionalInt32\" : 1\n ,\n \"optionalInt64\" : 2\n}\n",
1200 R"(
1201 optional_int32: 1
1202 optional_int64: 2
1203 )");
1204 // Missing comma between key/value pairs.
1205 ExpectParseFailureForJson(
1206 "MissingCommaOneLine", RECOMMENDED,
1207 "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
1208 ExpectParseFailureForJson(
1209 "MissingCommaMultiline", RECOMMENDED,
1210 "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}");
1211 // Duplicated field names are not allowed.
1212 ExpectParseFailureForJson(
1213 "FieldNameDuplicate", RECOMMENDED,
1214 R"({
1215 "optionalNestedMessage": {a: 1},
1216 "optionalNestedMessage": {}
1217 })");
1218 ExpectParseFailureForJson(
1219 "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
1220 R"({
1221 "optional_nested_message": {a: 1},
1222 "optionalNestedMessage": {}
1223 })");
1224 ExpectParseFailureForJson(
1225 "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
1226 R"({
1227 "optionalNestedMessage": {a: 1},
1228 "optional_nested_message": {}
1229 })");
1230 // Serializers should use lowerCamelCase by default.
1231 RunValidJsonTestWithValidator(
1232 "FieldNameInLowerCamelCase", REQUIRED,
1233 R"({
1234 "fieldname1": 1,
1235 "fieldName2": 2,
1236 "FieldName3": 3,
1237 "fieldName4": 4
1238 })",
1239 [](const Json::Value& value) {
1240 return value.isMember("fieldname1") &&
1241 value.isMember("fieldName2") &&
1242 value.isMember("FieldName3") &&
1243 value.isMember("fieldName4");
1244 });
1245 RunValidJsonTestWithValidator(
1246 "FieldNameWithNumbers", REQUIRED,
1247 R"({
1248 "field0name5": 5,
1249 "field0Name6": 6
1250 })",
1251 [](const Json::Value& value) {
1252 return value.isMember("field0name5") &&
1253 value.isMember("field0Name6");
1254 });
1255 RunValidJsonTestWithValidator(
1256 "FieldNameWithMixedCases", REQUIRED,
1257 R"({
1258 "fieldName7": 7,
1259 "FieldName8": 8,
1260 "fieldName9": 9,
1261 "FieldName10": 10,
1262 "FIELDNAME11": 11,
1263 "FIELDName12": 12
1264 })",
1265 [](const Json::Value& value) {
1266 return value.isMember("fieldName7") &&
1267 value.isMember("FieldName8") &&
1268 value.isMember("fieldName9") &&
1269 value.isMember("FieldName10") &&
1270 value.isMember("FIELDNAME11") &&
1271 value.isMember("FIELDName12");
1272 });
1273 RunValidJsonTestWithValidator(
1274 "FieldNameWithDoubleUnderscores", RECOMMENDED,
1275 R"({
1276 "FieldName13": 13,
1277 "FieldName14": 14,
1278 "fieldName15": 15,
1279 "fieldName16": 16,
1280 "fieldName17": 17,
1281 "FieldName18": 18
1282 })",
1283 [](const Json::Value& value) {
1284 return value.isMember("FieldName13") &&
1285 value.isMember("FieldName14") &&
1286 value.isMember("fieldName15") &&
1287 value.isMember("fieldName16") &&
1288 value.isMember("fieldName17") &&
1289 value.isMember("FieldName18");
1290 });
1291
1292 // Integer fields.
1293 RunValidJsonTest(
1294 "Int32FieldMaxValue", REQUIRED,
1295 R"({"optionalInt32": 2147483647})",
1296 "optional_int32: 2147483647");
1297 RunValidJsonTest(
1298 "Int32FieldMinValue", REQUIRED,
1299 R"({"optionalInt32": -2147483648})",
1300 "optional_int32: -2147483648");
1301 RunValidJsonTest(
1302 "Uint32FieldMaxValue", REQUIRED,
1303 R"({"optionalUint32": 4294967295})",
1304 "optional_uint32: 4294967295");
1305 RunValidJsonTest(
1306 "Int64FieldMaxValue", REQUIRED,
1307 R"({"optionalInt64": "9223372036854775807"})",
1308 "optional_int64: 9223372036854775807");
1309 RunValidJsonTest(
1310 "Int64FieldMinValue", REQUIRED,
1311 R"({"optionalInt64": "-9223372036854775808"})",
1312 "optional_int64: -9223372036854775808");
1313 RunValidJsonTest(
1314 "Uint64FieldMaxValue", REQUIRED,
1315 R"({"optionalUint64": "18446744073709551615"})",
1316 "optional_uint64: 18446744073709551615");
1317 // While not the largest Int64, this is the largest
1318 // Int64 which can be exactly represented within an
1319 // IEEE-754 64-bit float, which is the expected level
1320 // of interoperability guarantee. Larger values may
1321 // work in some implementations, but should not be
1322 // relied upon.
1323 RunValidJsonTest(
1324 "Int64FieldMaxValueNotQuoted", REQUIRED,
1325 R"({"optionalInt64": 9223372036854774784})",
1326 "optional_int64: 9223372036854774784");
1327 RunValidJsonTest(
1328 "Int64FieldMinValueNotQuoted", REQUIRED,
1329 R"({"optionalInt64": -9223372036854775808})",
1330 "optional_int64: -9223372036854775808");
1331 // Largest interoperable Uint64; see comment above
1332 // for Int64FieldMaxValueNotQuoted.
1333 RunValidJsonTest(
1334 "Uint64FieldMaxValueNotQuoted", REQUIRED,
1335 R"({"optionalUint64": 18446744073709549568})",
1336 "optional_uint64: 18446744073709549568");
1337 // Values can be represented as JSON strings.
1338 RunValidJsonTest(
1339 "Int32FieldStringValue", REQUIRED,
1340 R"({"optionalInt32": "2147483647"})",
1341 "optional_int32: 2147483647");
1342 RunValidJsonTest(
1343 "Int32FieldStringValueEscaped", REQUIRED,
1344 R"({"optionalInt32": "2\u003147483647"})",
1345 "optional_int32: 2147483647");
1346
1347 // Parsers reject out-of-bound integer values.
1348 ExpectParseFailureForJson(
1349 "Int32FieldTooLarge", REQUIRED,
1350 R"({"optionalInt32": 2147483648})");
1351 ExpectParseFailureForJson(
1352 "Int32FieldTooSmall", REQUIRED,
1353 R"({"optionalInt32": -2147483649})");
1354 ExpectParseFailureForJson(
1355 "Uint32FieldTooLarge", REQUIRED,
1356 R"({"optionalUint32": 4294967296})");
1357 ExpectParseFailureForJson(
1358 "Int64FieldTooLarge", REQUIRED,
1359 R"({"optionalInt64": "9223372036854775808"})");
1360 ExpectParseFailureForJson(
1361 "Int64FieldTooSmall", REQUIRED,
1362 R"({"optionalInt64": "-9223372036854775809"})");
1363 ExpectParseFailureForJson(
1364 "Uint64FieldTooLarge", REQUIRED,
1365 R"({"optionalUint64": "18446744073709551616"})");
1366 // Parser reject non-integer numeric values as well.
1367 ExpectParseFailureForJson(
1368 "Int32FieldNotInteger", REQUIRED,
1369 R"({"optionalInt32": 0.5})");
1370 ExpectParseFailureForJson(
1371 "Uint32FieldNotInteger", REQUIRED,
1372 R"({"optionalUint32": 0.5})");
1373 ExpectParseFailureForJson(
1374 "Int64FieldNotInteger", REQUIRED,
1375 R"({"optionalInt64": "0.5"})");
1376 ExpectParseFailureForJson(
1377 "Uint64FieldNotInteger", REQUIRED,
1378 R"({"optionalUint64": "0.5"})");
1379
1380 // Integers but represented as float values are accepted.
1381 RunValidJsonTest(
1382 "Int32FieldFloatTrailingZero", REQUIRED,
1383 R"({"optionalInt32": 100000.000})",
1384 "optional_int32: 100000");
1385 RunValidJsonTest(
1386 "Int32FieldExponentialFormat", REQUIRED,
1387 R"({"optionalInt32": 1e5})",
1388 "optional_int32: 100000");
1389 RunValidJsonTest(
1390 "Int32FieldMaxFloatValue", REQUIRED,
1391 R"({"optionalInt32": 2.147483647e9})",
1392 "optional_int32: 2147483647");
1393 RunValidJsonTest(
1394 "Int32FieldMinFloatValue", REQUIRED,
1395 R"({"optionalInt32": -2.147483648e9})",
1396 "optional_int32: -2147483648");
1397 RunValidJsonTest(
1398 "Uint32FieldMaxFloatValue", REQUIRED,
1399 R"({"optionalUint32": 4.294967295e9})",
1400 "optional_uint32: 4294967295");
1401
1402 // Parser reject non-numeric values.
1403 ExpectParseFailureForJson(
1404 "Int32FieldNotNumber", REQUIRED,
1405 R"({"optionalInt32": "3x3"})");
1406 ExpectParseFailureForJson(
1407 "Uint32FieldNotNumber", REQUIRED,
1408 R"({"optionalUint32": "3x3"})");
1409 ExpectParseFailureForJson(
1410 "Int64FieldNotNumber", REQUIRED,
1411 R"({"optionalInt64": "3x3"})");
1412 ExpectParseFailureForJson(
1413 "Uint64FieldNotNumber", REQUIRED,
1414 R"({"optionalUint64": "3x3"})");
1415 // JSON does not allow "+" on numric values.
1416 ExpectParseFailureForJson(
1417 "Int32FieldPlusSign", REQUIRED,
1418 R"({"optionalInt32": +1})");
1419 // JSON doesn't allow leading 0s.
1420 ExpectParseFailureForJson(
1421 "Int32FieldLeadingZero", REQUIRED,
1422 R"({"optionalInt32": 01})");
1423 ExpectParseFailureForJson(
1424 "Int32FieldNegativeWithLeadingZero", REQUIRED,
1425 R"({"optionalInt32": -01})");
1426 // String values must follow the same syntax rule. Specifically leading
1427 // or trailing spaces are not allowed.
1428 ExpectParseFailureForJson(
1429 "Int32FieldLeadingSpace", REQUIRED,
1430 R"({"optionalInt32": " 1"})");
1431 ExpectParseFailureForJson(
1432 "Int32FieldTrailingSpace", REQUIRED,
1433 R"({"optionalInt32": "1 "})");
1434
1435 // 64-bit values are serialized as strings.
1436 RunValidJsonTestWithValidator(
1437 "Int64FieldBeString", RECOMMENDED,
1438 R"({"optionalInt64": 1})",
1439 [](const Json::Value& value) {
1440 return value["optionalInt64"].type() == Json::stringValue &&
1441 value["optionalInt64"].asString() == "1";
1442 });
1443 RunValidJsonTestWithValidator(
1444 "Uint64FieldBeString", RECOMMENDED,
1445 R"({"optionalUint64": 1})",
1446 [](const Json::Value& value) {
1447 return value["optionalUint64"].type() == Json::stringValue &&
1448 value["optionalUint64"].asString() == "1";
1449 });
1450
1451 // Bool fields.
1452 RunValidJsonTest(
1453 "BoolFieldTrue", REQUIRED,
1454 R"({"optionalBool":true})",
1455 "optional_bool: true");
1456 RunValidJsonTest(
1457 "BoolFieldFalse", REQUIRED,
1458 R"({"optionalBool":false})",
1459 "optional_bool: false");
1460
1461 // Other forms are not allowed.
1462 ExpectParseFailureForJson(
1463 "BoolFieldIntegerZero", RECOMMENDED,
1464 R"({"optionalBool":0})");
1465 ExpectParseFailureForJson(
1466 "BoolFieldIntegerOne", RECOMMENDED,
1467 R"({"optionalBool":1})");
1468 ExpectParseFailureForJson(
1469 "BoolFieldCamelCaseTrue", RECOMMENDED,
1470 R"({"optionalBool":True})");
1471 ExpectParseFailureForJson(
1472 "BoolFieldCamelCaseFalse", RECOMMENDED,
1473 R"({"optionalBool":False})");
1474 ExpectParseFailureForJson(
1475 "BoolFieldAllCapitalTrue", RECOMMENDED,
1476 R"({"optionalBool":TRUE})");
1477 ExpectParseFailureForJson(
1478 "BoolFieldAllCapitalFalse", RECOMMENDED,
1479 R"({"optionalBool":FALSE})");
1480 ExpectParseFailureForJson(
1481 "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1482 R"({"optionalBool":"true"})");
1483 ExpectParseFailureForJson(
1484 "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1485 R"({"optionalBool":"false"})");
1486
1487 // Float fields.
1488 RunValidJsonTest(
1489 "FloatFieldMinPositiveValue", REQUIRED,
1490 R"({"optionalFloat": 1.175494e-38})",
1491 "optional_float: 1.175494e-38");
1492 RunValidJsonTest(
1493 "FloatFieldMaxNegativeValue", REQUIRED,
1494 R"({"optionalFloat": -1.175494e-38})",
1495 "optional_float: -1.175494e-38");
1496 RunValidJsonTest(
1497 "FloatFieldMaxPositiveValue", REQUIRED,
1498 R"({"optionalFloat": 3.402823e+38})",
1499 "optional_float: 3.402823e+38");
1500 RunValidJsonTest(
1501 "FloatFieldMinNegativeValue", REQUIRED,
1502 R"({"optionalFloat": 3.402823e+38})",
1503 "optional_float: 3.402823e+38");
1504 // Values can be quoted.
1505 RunValidJsonTest(
1506 "FloatFieldQuotedValue", REQUIRED,
1507 R"({"optionalFloat": "1"})",
1508 "optional_float: 1");
1509 // Special values.
1510 RunValidJsonTest(
1511 "FloatFieldNan", REQUIRED,
1512 R"({"optionalFloat": "NaN"})",
1513 "optional_float: nan");
1514 RunValidJsonTest(
1515 "FloatFieldInfinity", REQUIRED,
1516 R"({"optionalFloat": "Infinity"})",
1517 "optional_float: inf");
1518 RunValidJsonTest(
1519 "FloatFieldNegativeInfinity", REQUIRED,
1520 R"({"optionalFloat": "-Infinity"})",
1521 "optional_float: -inf");
1522 // Non-cannonical Nan will be correctly normalized.
1523 {
1524 TestAllTypesProto3 message;
1525 // IEEE floating-point standard 32-bit quiet NaN:
1526 // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
1527 message.set_optional_float(
1528 WireFormatLite::DecodeFloat(0x7FA12345));
1529 RunValidJsonTestWithProtobufInput(
1530 "FloatFieldNormalizeQuietNan", REQUIRED, message,
1531 "optional_float: nan");
1532 // IEEE floating-point standard 64-bit signaling NaN:
1533 // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
1534 message.set_optional_float(
1535 WireFormatLite::DecodeFloat(0xFFB54321));
1536 RunValidJsonTestWithProtobufInput(
1537 "FloatFieldNormalizeSignalingNan", REQUIRED, message,
1538 "optional_float: nan");
1539 }
1540
1541 // Special values must be quoted.
1542 ExpectParseFailureForJson(
1543 "FloatFieldNanNotQuoted", RECOMMENDED,
1544 R"({"optionalFloat": NaN})");
1545 ExpectParseFailureForJson(
1546 "FloatFieldInfinityNotQuoted", RECOMMENDED,
1547 R"({"optionalFloat": Infinity})");
1548 ExpectParseFailureForJson(
1549 "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1550 R"({"optionalFloat": -Infinity})");
1551 // Parsers should reject out-of-bound values.
1552 ExpectParseFailureForJson(
1553 "FloatFieldTooSmall", REQUIRED,
1554 R"({"optionalFloat": -3.502823e+38})");
1555 ExpectParseFailureForJson(
1556 "FloatFieldTooLarge", REQUIRED,
1557 R"({"optionalFloat": 3.502823e+38})");
1558
1559 // Double fields.
1560 RunValidJsonTest(
1561 "DoubleFieldMinPositiveValue", REQUIRED,
1562 R"({"optionalDouble": 2.22507e-308})",
1563 "optional_double: 2.22507e-308");
1564 RunValidJsonTest(
1565 "DoubleFieldMaxNegativeValue", REQUIRED,
1566 R"({"optionalDouble": -2.22507e-308})",
1567 "optional_double: -2.22507e-308");
1568 RunValidJsonTest(
1569 "DoubleFieldMaxPositiveValue", REQUIRED,
1570 R"({"optionalDouble": 1.79769e+308})",
1571 "optional_double: 1.79769e+308");
1572 RunValidJsonTest(
1573 "DoubleFieldMinNegativeValue", REQUIRED,
1574 R"({"optionalDouble": -1.79769e+308})",
1575 "optional_double: -1.79769e+308");
1576 // Values can be quoted.
1577 RunValidJsonTest(
1578 "DoubleFieldQuotedValue", REQUIRED,
1579 R"({"optionalDouble": "1"})",
1580 "optional_double: 1");
1581 // Speical values.
1582 RunValidJsonTest(
1583 "DoubleFieldNan", REQUIRED,
1584 R"({"optionalDouble": "NaN"})",
1585 "optional_double: nan");
1586 RunValidJsonTest(
1587 "DoubleFieldInfinity", REQUIRED,
1588 R"({"optionalDouble": "Infinity"})",
1589 "optional_double: inf");
1590 RunValidJsonTest(
1591 "DoubleFieldNegativeInfinity", REQUIRED,
1592 R"({"optionalDouble": "-Infinity"})",
1593 "optional_double: -inf");
1594 // Non-cannonical Nan will be correctly normalized.
1595 {
1596 TestAllTypesProto3 message;
1597 message.set_optional_double(
1598 WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
1599 RunValidJsonTestWithProtobufInput(
1600 "DoubleFieldNormalizeQuietNan", REQUIRED, message,
1601 "optional_double: nan");
1602 message.set_optional_double(
1603 WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
1604 RunValidJsonTestWithProtobufInput(
1605 "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
1606 "optional_double: nan");
1607 }
1608
1609 // Special values must be quoted.
1610 ExpectParseFailureForJson(
1611 "DoubleFieldNanNotQuoted", RECOMMENDED,
1612 R"({"optionalDouble": NaN})");
1613 ExpectParseFailureForJson(
1614 "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1615 R"({"optionalDouble": Infinity})");
1616 ExpectParseFailureForJson(
1617 "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1618 R"({"optionalDouble": -Infinity})");
1619
1620 // Parsers should reject out-of-bound values.
1621 ExpectParseFailureForJson(
1622 "DoubleFieldTooSmall", REQUIRED,
1623 R"({"optionalDouble": -1.89769e+308})");
1624 ExpectParseFailureForJson(
1625 "DoubleFieldTooLarge", REQUIRED,
1626 R"({"optionalDouble": +1.89769e+308})");
1627
1628 // Enum fields.
1629 RunValidJsonTest(
1630 "EnumField", REQUIRED,
1631 R"({"optionalNestedEnum": "FOO"})",
1632 "optional_nested_enum: FOO");
Hao Nguyen3d46d8d2018-12-14 16:41:44 -08001633 // Enum fields with alias
1634 RunValidJsonTest(
1635 "EnumFieldWithAlias", REQUIRED,
1636 R"({"optionalAliasedEnum": "ALIAS_BAZ"})",
1637 "optional_aliased_enum: ALIAS_BAZ");
1638 RunValidJsonTest(
1639 "EnumFieldWithAliasUseAlias", REQUIRED,
1640 R"({"optionalAliasedEnum": "QUX"})",
1641 "optional_aliased_enum: ALIAS_BAZ");
1642 RunValidJsonTest(
1643 "EnumFieldWithAliasLowerCase", REQUIRED,
1644 R"({"optionalAliasedEnum": "qux"})",
1645 "optional_aliased_enum: ALIAS_BAZ");
1646 RunValidJsonTest(
1647 "EnumFieldWithAliasDifferentCase", REQUIRED,
1648 R"({"optionalAliasedEnum": "bAz"})",
1649 "optional_aliased_enum: ALIAS_BAZ");
Feng Xiao6bbe1972018-08-08 17:00:41 -07001650 // Enum values must be represented as strings.
1651 ExpectParseFailureForJson(
1652 "EnumFieldNotQuoted", REQUIRED,
1653 R"({"optionalNestedEnum": FOO})");
1654 // Numeric values are allowed.
1655 RunValidJsonTest(
1656 "EnumFieldNumericValueZero", REQUIRED,
1657 R"({"optionalNestedEnum": 0})",
1658 "optional_nested_enum: FOO");
1659 RunValidJsonTest(
1660 "EnumFieldNumericValueNonZero", REQUIRED,
1661 R"({"optionalNestedEnum": 1})",
1662 "optional_nested_enum: BAR");
1663 // Unknown enum values are represented as numeric values.
1664 RunValidJsonTestWithValidator(
1665 "EnumFieldUnknownValue", REQUIRED,
1666 R"({"optionalNestedEnum": 123})",
1667 [](const Json::Value& value) {
1668 return value["optionalNestedEnum"].type() == Json::intValue &&
1669 value["optionalNestedEnum"].asInt() == 123;
1670 });
1671
1672 // String fields.
1673 RunValidJsonTest(
1674 "StringField", REQUIRED,
1675 R"({"optionalString": "Hello world!"})",
1676 "optional_string: \"Hello world!\"");
1677 RunValidJsonTest(
1678 "StringFieldUnicode", REQUIRED,
1679 // Google in Chinese.
1680 R"({"optionalString": "谷歌"})",
1681 R"(optional_string: "谷歌")");
1682 RunValidJsonTest(
1683 "StringFieldEscape", REQUIRED,
1684 R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
1685 R"(optional_string: "\"\\/\b\f\n\r\t")");
1686 RunValidJsonTest(
1687 "StringFieldUnicodeEscape", REQUIRED,
1688 R"({"optionalString": "\u8C37\u6B4C"})",
1689 R"(optional_string: "谷歌")");
1690 RunValidJsonTest(
1691 "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
1692 R"({"optionalString": "\u8c37\u6b4c"})",
1693 R"(optional_string: "谷歌")");
1694 RunValidJsonTest(
1695 "StringFieldSurrogatePair", REQUIRED,
1696 // The character is an emoji: grinning face with smiling eyes. 😁
1697 R"({"optionalString": "\uD83D\uDE01"})",
1698 R"(optional_string: "\xF0\x9F\x98\x81")");
1699
1700 // Unicode escapes must start with "\u" (lowercase u).
1701 ExpectParseFailureForJson(
1702 "StringFieldUppercaseEscapeLetter", RECOMMENDED,
1703 R"({"optionalString": "\U8C37\U6b4C"})");
1704 ExpectParseFailureForJson(
1705 "StringFieldInvalidEscape", RECOMMENDED,
1706 R"({"optionalString": "\uXXXX\u6B4C"})");
1707 ExpectParseFailureForJson(
1708 "StringFieldUnterminatedEscape", RECOMMENDED,
1709 R"({"optionalString": "\u8C3"})");
1710 ExpectParseFailureForJson(
1711 "StringFieldUnpairedHighSurrogate", RECOMMENDED,
1712 R"({"optionalString": "\uD800"})");
1713 ExpectParseFailureForJson(
1714 "StringFieldUnpairedLowSurrogate", RECOMMENDED,
1715 R"({"optionalString": "\uDC00"})");
1716 ExpectParseFailureForJson(
1717 "StringFieldSurrogateInWrongOrder", RECOMMENDED,
1718 R"({"optionalString": "\uDE01\uD83D"})");
1719 ExpectParseFailureForJson(
1720 "StringFieldNotAString", REQUIRED,
1721 R"({"optionalString": 12345})");
1722
1723 // Bytes fields.
1724 RunValidJsonTest(
1725 "BytesField", REQUIRED,
1726 R"({"optionalBytes": "AQI="})",
1727 R"(optional_bytes: "\x01\x02")");
1728 RunValidJsonTest(
1729 "BytesFieldBase64Url", RECOMMENDED,
1730 R"({"optionalBytes": "-_"})",
1731 R"(optional_bytes: "\xfb")");
1732
1733 // Message fields.
1734 RunValidJsonTest(
1735 "MessageField", REQUIRED,
1736 R"({"optionalNestedMessage": {"a": 1234}})",
1737 "optional_nested_message: {a: 1234}");
1738
1739 // Oneof fields.
1740 ExpectParseFailureForJson(
1741 "OneofFieldDuplicate", REQUIRED,
1742 R"({"oneofUint32": 1, "oneofString": "test"})");
1743 // Ensure zero values for oneof make it out/backs.
1744 TestAllTypesProto3 messageProto3;
1745 TestAllTypesProto2 messageProto2;
1746 TestOneofMessage(messageProto3, true);
1747 TestOneofMessage(messageProto2, false);
1748 RunValidJsonTest(
1749 "OneofZeroUint32", RECOMMENDED,
1750 R"({"oneofUint32": 0})", "oneof_uint32: 0");
1751 RunValidJsonTest(
1752 "OneofZeroMessage", RECOMMENDED,
1753 R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
1754 RunValidJsonTest(
1755 "OneofZeroString", RECOMMENDED,
1756 R"({"oneofString": ""})", "oneof_string: \"\"");
1757 RunValidJsonTest(
1758 "OneofZeroBytes", RECOMMENDED,
1759 R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
1760 RunValidJsonTest(
1761 "OneofZeroBool", RECOMMENDED,
1762 R"({"oneofBool": false})", "oneof_bool: false");
1763 RunValidJsonTest(
1764 "OneofZeroUint64", RECOMMENDED,
1765 R"({"oneofUint64": 0})", "oneof_uint64: 0");
1766 RunValidJsonTest(
1767 "OneofZeroFloat", RECOMMENDED,
1768 R"({"oneofFloat": 0.0})", "oneof_float: 0");
1769 RunValidJsonTest(
1770 "OneofZeroDouble", RECOMMENDED,
1771 R"({"oneofDouble": 0.0})", "oneof_double: 0");
1772 RunValidJsonTest(
1773 "OneofZeroEnum", RECOMMENDED,
1774 R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
1775
1776 // Repeated fields.
1777 RunValidJsonTest(
1778 "PrimitiveRepeatedField", REQUIRED,
1779 R"({"repeatedInt32": [1, 2, 3, 4]})",
1780 "repeated_int32: [1, 2, 3, 4]");
1781 RunValidJsonTest(
1782 "EnumRepeatedField", REQUIRED,
1783 R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
1784 "repeated_nested_enum: [FOO, BAR, BAZ]");
1785 RunValidJsonTest(
1786 "StringRepeatedField", REQUIRED,
1787 R"({"repeatedString": ["Hello", "world"]})",
1788 R"(repeated_string: ["Hello", "world"])");
1789 RunValidJsonTest(
1790 "BytesRepeatedField", REQUIRED,
1791 R"({"repeatedBytes": ["AAEC", "AQI="]})",
1792 R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
1793 RunValidJsonTest(
1794 "MessageRepeatedField", REQUIRED,
1795 R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
1796 "repeated_nested_message: {a: 1234}"
1797 "repeated_nested_message: {a: 5678}");
1798
1799 // Repeated field elements are of incorrect type.
1800 ExpectParseFailureForJson(
1801 "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
1802 R"({"repeatedInt32": [1, false, 3, 4]})");
1803 ExpectParseFailureForJson(
1804 "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
1805 R"({"repeatedInt32": [1, 2, "name", 4]})");
1806 ExpectParseFailureForJson(
1807 "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
1808 R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
1809 ExpectParseFailureForJson(
1810 "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
1811 R"({"repeatedString": ["1", 2, "3", "4"]})");
1812 ExpectParseFailureForJson(
1813 "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
1814 R"({"repeatedString": ["1", "2", false, "4"]})");
1815 ExpectParseFailureForJson(
1816 "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
1817 R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
1818 ExpectParseFailureForJson(
1819 "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
1820 R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
1821 ExpectParseFailureForJson(
1822 "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
1823 R"({"repeatedNestedMessage": [{"a": 1}, false]})");
1824 ExpectParseFailureForJson(
1825 "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
1826 R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
1827 // Trailing comma in the repeated field is not allowed.
1828 ExpectParseFailureForJson(
1829 "RepeatedFieldTrailingComma", RECOMMENDED,
1830 R"({"repeatedInt32": [1, 2, 3, 4,]})");
1831 ExpectParseFailureForJson(
1832 "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
1833 "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
1834 ExpectParseFailureForJson(
1835 "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
1836 "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
1837 ExpectParseFailureForJson(
1838 "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
1839 "{\"repeatedInt32\": [\n 1,\n 2,\n 3,\n 4,\n]}");
1840
1841 // Map fields.
1842 RunValidJsonTest(
1843 "Int32MapField", REQUIRED,
1844 R"({"mapInt32Int32": {"1": 2, "3": 4}})",
1845 "map_int32_int32: {key: 1 value: 2}"
1846 "map_int32_int32: {key: 3 value: 4}");
1847 ExpectParseFailureForJson(
1848 "Int32MapFieldKeyNotQuoted", RECOMMENDED,
1849 R"({"mapInt32Int32": {1: 2, 3: 4}})");
1850 RunValidJsonTest(
1851 "Uint32MapField", REQUIRED,
1852 R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
1853 "map_uint32_uint32: {key: 1 value: 2}"
1854 "map_uint32_uint32: {key: 3 value: 4}");
1855 ExpectParseFailureForJson(
1856 "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
1857 R"({"mapUint32Uint32": {1: 2, 3: 4}})");
1858 RunValidJsonTest(
1859 "Int64MapField", REQUIRED,
1860 R"({"mapInt64Int64": {"1": 2, "3": 4}})",
1861 "map_int64_int64: {key: 1 value: 2}"
1862 "map_int64_int64: {key: 3 value: 4}");
1863 ExpectParseFailureForJson(
1864 "Int64MapFieldKeyNotQuoted", RECOMMENDED,
1865 R"({"mapInt64Int64": {1: 2, 3: 4}})");
1866 RunValidJsonTest(
1867 "Uint64MapField", REQUIRED,
1868 R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
1869 "map_uint64_uint64: {key: 1 value: 2}"
1870 "map_uint64_uint64: {key: 3 value: 4}");
1871 ExpectParseFailureForJson(
1872 "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
1873 R"({"mapUint64Uint64": {1: 2, 3: 4}})");
1874 RunValidJsonTest(
1875 "BoolMapField", REQUIRED,
1876 R"({"mapBoolBool": {"true": true, "false": false}})",
1877 "map_bool_bool: {key: true value: true}"
1878 "map_bool_bool: {key: false value: false}");
1879 ExpectParseFailureForJson(
1880 "BoolMapFieldKeyNotQuoted", RECOMMENDED,
1881 R"({"mapBoolBool": {true: true, false: false}})");
1882 RunValidJsonTest(
1883 "MessageMapField", REQUIRED,
1884 R"({
1885 "mapStringNestedMessage": {
1886 "hello": {"a": 1234},
1887 "world": {"a": 5678}
1888 }
1889 })",
1890 R"(
1891 map_string_nested_message: {
1892 key: "hello"
1893 value: {a: 1234}
1894 }
1895 map_string_nested_message: {
1896 key: "world"
1897 value: {a: 5678}
1898 }
1899 )");
1900 // Since Map keys are represented as JSON strings, escaping should be allowed.
1901 RunValidJsonTest(
1902 "Int32MapEscapedKey", REQUIRED,
1903 R"({"mapInt32Int32": {"\u0031": 2}})",
1904 "map_int32_int32: {key: 1 value: 2}");
1905 RunValidJsonTest(
1906 "Int64MapEscapedKey", REQUIRED,
1907 R"({"mapInt64Int64": {"\u0031": 2}})",
1908 "map_int64_int64: {key: 1 value: 2}");
1909 RunValidJsonTest(
1910 "BoolMapEscapedKey", REQUIRED,
1911 R"({"mapBoolBool": {"tr\u0075e": true}})",
1912 "map_bool_bool: {key: true value: true}");
1913
1914 // "null" is accepted for all fields types.
1915 RunValidJsonTest(
1916 "AllFieldAcceptNull", REQUIRED,
1917 R"({
1918 "optionalInt32": null,
1919 "optionalInt64": null,
1920 "optionalUint32": null,
1921 "optionalUint64": null,
1922 "optionalSint32": null,
1923 "optionalSint64": null,
1924 "optionalFixed32": null,
1925 "optionalFixed64": null,
1926 "optionalSfixed32": null,
1927 "optionalSfixed64": null,
1928 "optionalFloat": null,
1929 "optionalDouble": null,
1930 "optionalBool": null,
1931 "optionalString": null,
1932 "optionalBytes": null,
1933 "optionalNestedEnum": null,
1934 "optionalNestedMessage": null,
1935 "repeatedInt32": null,
1936 "repeatedInt64": null,
1937 "repeatedUint32": null,
1938 "repeatedUint64": null,
1939 "repeatedSint32": null,
1940 "repeatedSint64": null,
1941 "repeatedFixed32": null,
1942 "repeatedFixed64": null,
1943 "repeatedSfixed32": null,
1944 "repeatedSfixed64": null,
1945 "repeatedFloat": null,
1946 "repeatedDouble": null,
1947 "repeatedBool": null,
1948 "repeatedString": null,
1949 "repeatedBytes": null,
1950 "repeatedNestedEnum": null,
1951 "repeatedNestedMessage": null,
1952 "mapInt32Int32": null,
1953 "mapBoolBool": null,
1954 "mapStringNestedMessage": null
1955 })",
1956 "");
1957
1958 // Repeated field elements cannot be null.
1959 ExpectParseFailureForJson(
1960 "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
1961 R"({"repeatedInt32": [1, null, 2]})");
1962 ExpectParseFailureForJson(
1963 "RepeatedFieldMessageElementIsNull", RECOMMENDED,
1964 R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
1965 // Map field keys cannot be null.
1966 ExpectParseFailureForJson(
1967 "MapFieldKeyIsNull", RECOMMENDED,
1968 R"({"mapInt32Int32": {null: 1}})");
1969 // Map field values cannot be null.
1970 ExpectParseFailureForJson(
1971 "MapFieldValueIsNull", RECOMMENDED,
1972 R"({"mapInt32Int32": {"0": null}})");
1973
1974 // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
1975 // quotes.
1976 ExpectParseFailureForJson(
1977 "StringFieldSingleQuoteKey", RECOMMENDED,
1978 R"({'optionalString': "Hello world!"})");
1979 ExpectParseFailureForJson(
1980 "StringFieldSingleQuoteValue", RECOMMENDED,
1981 R"({"optionalString": 'Hello world!'})");
1982 ExpectParseFailureForJson(
1983 "StringFieldSingleQuoteBoth", RECOMMENDED,
1984 R"({'optionalString': 'Hello world!'})");
1985
1986 // Unknown fields.
1987 {
1988 TestAllTypesProto3 messageProto3;
1989 TestAllTypesProto2 messageProto2;
1990 //TODO(yilunchong): update this behavior when unknown field's behavior
1991 // changed in open source. Also delete
1992 // Required.Proto3.ProtobufInput.UnknownVarint.ProtobufOutput
1993 // from failure list of python_cpp python java
1994 TestUnknownMessage(messageProto3, true);
1995 TestUnknownMessage(messageProto2, false);
1996 }
1997
1998 // Wrapper types.
1999 RunValidJsonTest(
2000 "OptionalBoolWrapper", REQUIRED,
2001 R"({"optionalBoolWrapper": false})",
2002 "optional_bool_wrapper: {value: false}");
2003 RunValidJsonTest(
2004 "OptionalInt32Wrapper", REQUIRED,
2005 R"({"optionalInt32Wrapper": 0})",
2006 "optional_int32_wrapper: {value: 0}");
2007 RunValidJsonTest(
2008 "OptionalUint32Wrapper", REQUIRED,
2009 R"({"optionalUint32Wrapper": 0})",
2010 "optional_uint32_wrapper: {value: 0}");
2011 RunValidJsonTest(
2012 "OptionalInt64Wrapper", REQUIRED,
2013 R"({"optionalInt64Wrapper": 0})",
2014 "optional_int64_wrapper: {value: 0}");
2015 RunValidJsonTest(
2016 "OptionalUint64Wrapper", REQUIRED,
2017 R"({"optionalUint64Wrapper": 0})",
2018 "optional_uint64_wrapper: {value: 0}");
2019 RunValidJsonTest(
2020 "OptionalFloatWrapper", REQUIRED,
2021 R"({"optionalFloatWrapper": 0})",
2022 "optional_float_wrapper: {value: 0}");
2023 RunValidJsonTest(
2024 "OptionalDoubleWrapper", REQUIRED,
2025 R"({"optionalDoubleWrapper": 0})",
2026 "optional_double_wrapper: {value: 0}");
2027 RunValidJsonTest(
2028 "OptionalStringWrapper", REQUIRED,
2029 R"({"optionalStringWrapper": ""})",
2030 R"(optional_string_wrapper: {value: ""})");
2031 RunValidJsonTest(
2032 "OptionalBytesWrapper", REQUIRED,
2033 R"({"optionalBytesWrapper": ""})",
2034 R"(optional_bytes_wrapper: {value: ""})");
2035 RunValidJsonTest(
2036 "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
2037 R"({
2038 "optionalBoolWrapper": true,
2039 "optionalInt32Wrapper": 1,
2040 "optionalUint32Wrapper": 1,
2041 "optionalInt64Wrapper": "1",
2042 "optionalUint64Wrapper": "1",
2043 "optionalFloatWrapper": 1,
2044 "optionalDoubleWrapper": 1,
2045 "optionalStringWrapper": "1",
2046 "optionalBytesWrapper": "AQI="
2047 })",
2048 R"(
2049 optional_bool_wrapper: {value: true}
2050 optional_int32_wrapper: {value: 1}
2051 optional_uint32_wrapper: {value: 1}
2052 optional_int64_wrapper: {value: 1}
2053 optional_uint64_wrapper: {value: 1}
2054 optional_float_wrapper: {value: 1}
2055 optional_double_wrapper: {value: 1}
2056 optional_string_wrapper: {value: "1"}
2057 optional_bytes_wrapper: {value: "\x01\x02"}
2058 )");
2059 RunValidJsonTest(
2060 "RepeatedBoolWrapper", REQUIRED,
2061 R"({"repeatedBoolWrapper": [true, false]})",
2062 "repeated_bool_wrapper: {value: true}"
2063 "repeated_bool_wrapper: {value: false}");
2064 RunValidJsonTest(
2065 "RepeatedInt32Wrapper", REQUIRED,
2066 R"({"repeatedInt32Wrapper": [0, 1]})",
2067 "repeated_int32_wrapper: {value: 0}"
2068 "repeated_int32_wrapper: {value: 1}");
2069 RunValidJsonTest(
2070 "RepeatedUint32Wrapper", REQUIRED,
2071 R"({"repeatedUint32Wrapper": [0, 1]})",
2072 "repeated_uint32_wrapper: {value: 0}"
2073 "repeated_uint32_wrapper: {value: 1}");
2074 RunValidJsonTest(
2075 "RepeatedInt64Wrapper", REQUIRED,
2076 R"({"repeatedInt64Wrapper": [0, 1]})",
2077 "repeated_int64_wrapper: {value: 0}"
2078 "repeated_int64_wrapper: {value: 1}");
2079 RunValidJsonTest(
2080 "RepeatedUint64Wrapper", REQUIRED,
2081 R"({"repeatedUint64Wrapper": [0, 1]})",
2082 "repeated_uint64_wrapper: {value: 0}"
2083 "repeated_uint64_wrapper: {value: 1}");
2084 RunValidJsonTest(
2085 "RepeatedFloatWrapper", REQUIRED,
2086 R"({"repeatedFloatWrapper": [0, 1]})",
2087 "repeated_float_wrapper: {value: 0}"
2088 "repeated_float_wrapper: {value: 1}");
2089 RunValidJsonTest(
2090 "RepeatedDoubleWrapper", REQUIRED,
2091 R"({"repeatedDoubleWrapper": [0, 1]})",
2092 "repeated_double_wrapper: {value: 0}"
2093 "repeated_double_wrapper: {value: 1}");
2094 RunValidJsonTest(
2095 "RepeatedStringWrapper", REQUIRED,
2096 R"({"repeatedStringWrapper": ["", "AQI="]})",
2097 R"(
2098 repeated_string_wrapper: {value: ""}
2099 repeated_string_wrapper: {value: "AQI="}
2100 )");
2101 RunValidJsonTest(
2102 "RepeatedBytesWrapper", REQUIRED,
2103 R"({"repeatedBytesWrapper": ["", "AQI="]})",
2104 R"(
2105 repeated_bytes_wrapper: {value: ""}
2106 repeated_bytes_wrapper: {value: "\x01\x02"}
2107 )");
2108 RunValidJsonTest(
2109 "WrapperTypesWithNullValue", REQUIRED,
2110 R"({
2111 "optionalBoolWrapper": null,
2112 "optionalInt32Wrapper": null,
2113 "optionalUint32Wrapper": null,
2114 "optionalInt64Wrapper": null,
2115 "optionalUint64Wrapper": null,
2116 "optionalFloatWrapper": null,
2117 "optionalDoubleWrapper": null,
2118 "optionalStringWrapper": null,
2119 "optionalBytesWrapper": null,
2120 "repeatedBoolWrapper": null,
2121 "repeatedInt32Wrapper": null,
2122 "repeatedUint32Wrapper": null,
2123 "repeatedInt64Wrapper": null,
2124 "repeatedUint64Wrapper": null,
2125 "repeatedFloatWrapper": null,
2126 "repeatedDoubleWrapper": null,
2127 "repeatedStringWrapper": null,
2128 "repeatedBytesWrapper": null
2129 })",
2130 "");
2131
2132 // Duration
2133 RunValidJsonTest(
2134 "DurationMinValue", REQUIRED,
2135 R"({"optionalDuration": "-315576000000.999999999s"})",
2136 "optional_duration: {seconds: -315576000000 nanos: -999999999}");
2137 RunValidJsonTest(
2138 "DurationMaxValue", REQUIRED,
2139 R"({"optionalDuration": "315576000000.999999999s"})",
2140 "optional_duration: {seconds: 315576000000 nanos: 999999999}");
2141 RunValidJsonTest(
2142 "DurationRepeatedValue", REQUIRED,
2143 R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
2144 "repeated_duration: {seconds: 1 nanos: 500000000}"
2145 "repeated_duration: {seconds: -1 nanos: -500000000}");
2146 RunValidJsonTest(
2147 "DurationNull", REQUIRED,
2148 R"({"optionalDuration": null})",
2149 "");
2150
2151 ExpectParseFailureForJson(
2152 "DurationMissingS", REQUIRED,
2153 R"({"optionalDuration": "1"})");
2154 ExpectParseFailureForJson(
2155 "DurationJsonInputTooSmall", REQUIRED,
2156 R"({"optionalDuration": "-315576000001.000000000s"})");
2157 ExpectParseFailureForJson(
2158 "DurationJsonInputTooLarge", REQUIRED,
2159 R"({"optionalDuration": "315576000001.000000000s"})");
2160 ExpectSerializeFailureForJson(
2161 "DurationProtoInputTooSmall", REQUIRED,
2162 "optional_duration: {seconds: -315576000001 nanos: 0}");
2163 ExpectSerializeFailureForJson(
2164 "DurationProtoInputTooLarge", REQUIRED,
2165 "optional_duration: {seconds: 315576000001 nanos: 0}");
2166
2167 RunValidJsonTestWithValidator(
2168 "DurationHasZeroFractionalDigit", RECOMMENDED,
2169 R"({"optionalDuration": "1.000000000s"})",
2170 [](const Json::Value& value) {
2171 return value["optionalDuration"].asString() == "1s";
2172 });
2173 RunValidJsonTestWithValidator(
2174 "DurationHas3FractionalDigits", RECOMMENDED,
2175 R"({"optionalDuration": "1.010000000s"})",
2176 [](const Json::Value& value) {
2177 return value["optionalDuration"].asString() == "1.010s";
2178 });
2179 RunValidJsonTestWithValidator(
2180 "DurationHas6FractionalDigits", RECOMMENDED,
2181 R"({"optionalDuration": "1.000010000s"})",
2182 [](const Json::Value& value) {
2183 return value["optionalDuration"].asString() == "1.000010s";
2184 });
2185 RunValidJsonTestWithValidator(
2186 "DurationHas9FractionalDigits", RECOMMENDED,
2187 R"({"optionalDuration": "1.000000010s"})",
2188 [](const Json::Value& value) {
2189 return value["optionalDuration"].asString() == "1.000000010s";
2190 });
2191
2192 // Timestamp
2193 RunValidJsonTest(
2194 "TimestampMinValue", REQUIRED,
2195 R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
2196 "optional_timestamp: {seconds: -62135596800}");
2197 RunValidJsonTest(
2198 "TimestampMaxValue", REQUIRED,
2199 R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
2200 "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
2201 RunValidJsonTest(
2202 "TimestampRepeatedValue", REQUIRED,
2203 R"({
2204 "repeatedTimestamp": [
2205 "0001-01-01T00:00:00Z",
2206 "9999-12-31T23:59:59.999999999Z"
2207 ]
2208 })",
2209 "repeated_timestamp: {seconds: -62135596800}"
2210 "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
Hao Nguyen51026d92019-06-26 11:01:34 -07002211 RunValidJsonTest("TimestampWithPositiveOffset", REQUIRED,
2212 R"({"optionalTimestamp": "1970-01-01T08:00:01+08:00"})",
2213 "optional_timestamp: {seconds: 1}");
2214 RunValidJsonTest("TimestampWithNegativeOffset", REQUIRED,
2215 R"({"optionalTimestamp": "1969-12-31T16:00:01-08:00"})",
2216 "optional_timestamp: {seconds: 1}");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002217 RunValidJsonTest(
2218 "TimestampNull", REQUIRED,
2219 R"({"optionalTimestamp": null})",
2220 "");
2221
2222 ExpectParseFailureForJson(
2223 "TimestampJsonInputTooSmall", REQUIRED,
2224 R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
2225 ExpectParseFailureForJson(
2226 "TimestampJsonInputTooLarge", REQUIRED,
2227 R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
2228 ExpectParseFailureForJson(
2229 "TimestampJsonInputMissingZ", REQUIRED,
2230 R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
2231 ExpectParseFailureForJson(
2232 "TimestampJsonInputMissingT", REQUIRED,
2233 R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
2234 ExpectParseFailureForJson(
2235 "TimestampJsonInputLowercaseZ", REQUIRED,
2236 R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
2237 ExpectParseFailureForJson(
2238 "TimestampJsonInputLowercaseT", REQUIRED,
2239 R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
2240 ExpectSerializeFailureForJson(
2241 "TimestampProtoInputTooSmall", REQUIRED,
2242 "optional_timestamp: {seconds: -62135596801}");
2243 ExpectSerializeFailureForJson(
2244 "TimestampProtoInputTooLarge", REQUIRED,
2245 "optional_timestamp: {seconds: 253402300800}");
2246 RunValidJsonTestWithValidator(
2247 "TimestampZeroNormalized", RECOMMENDED,
2248 R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
2249 [](const Json::Value& value) {
2250 return value["optionalTimestamp"].asString() ==
2251 "1970-01-01T00:00:00Z";
2252 });
2253 RunValidJsonTestWithValidator(
2254 "TimestampHasZeroFractionalDigit", RECOMMENDED,
2255 R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
2256 [](const Json::Value& value) {
2257 return value["optionalTimestamp"].asString() ==
2258 "1970-01-01T00:00:00Z";
2259 });
2260 RunValidJsonTestWithValidator(
2261 "TimestampHas3FractionalDigits", RECOMMENDED,
2262 R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
2263 [](const Json::Value& value) {
2264 return value["optionalTimestamp"].asString() ==
2265 "1970-01-01T00:00:00.010Z";
2266 });
2267 RunValidJsonTestWithValidator(
2268 "TimestampHas6FractionalDigits", RECOMMENDED,
2269 R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
2270 [](const Json::Value& value) {
2271 return value["optionalTimestamp"].asString() ==
2272 "1970-01-01T00:00:00.000010Z";
2273 });
2274 RunValidJsonTestWithValidator(
2275 "TimestampHas9FractionalDigits", RECOMMENDED,
2276 R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
2277 [](const Json::Value& value) {
2278 return value["optionalTimestamp"].asString() ==
2279 "1970-01-01T00:00:00.000000010Z";
2280 });
2281
2282 // FieldMask
2283 RunValidJsonTest(
2284 "FieldMask", REQUIRED,
2285 R"({"optionalFieldMask": "foo,barBaz"})",
2286 R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
Paul Yang7f42d6d2019-01-22 15:35:12 -08002287 RunValidJsonTest(
2288 "EmptyFieldMask", REQUIRED,
2289 R"({"optionalFieldMask": ""})",
2290 R"(optional_field_mask: {})");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002291 ExpectParseFailureForJson(
2292 "FieldMaskInvalidCharacter", RECOMMENDED,
2293 R"({"optionalFieldMask": "foo,bar_bar"})");
2294 ExpectSerializeFailureForJson(
2295 "FieldMaskPathsDontRoundTrip", RECOMMENDED,
2296 R"(optional_field_mask: {paths: "fooBar"})");
2297 ExpectSerializeFailureForJson(
2298 "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
2299 R"(optional_field_mask: {paths: "foo_3_bar"})");
2300 ExpectSerializeFailureForJson(
2301 "FieldMaskTooManyUnderscore", RECOMMENDED,
2302 R"(optional_field_mask: {paths: "foo__bar"})");
2303
2304 // Struct
2305 RunValidJsonTest(
2306 "Struct", REQUIRED,
2307 R"({
2308 "optionalStruct": {
2309 "nullValue": null,
2310 "intValue": 1234,
2311 "boolValue": true,
2312 "doubleValue": 1234.5678,
2313 "stringValue": "Hello world!",
2314 "listValue": [1234, "5678"],
2315 "objectValue": {
2316 "value": 0
2317 }
2318 }
2319 })",
2320 R"(
2321 optional_struct: {
2322 fields: {
2323 key: "nullValue"
2324 value: {null_value: NULL_VALUE}
2325 }
2326 fields: {
2327 key: "intValue"
2328 value: {number_value: 1234}
2329 }
2330 fields: {
2331 key: "boolValue"
2332 value: {bool_value: true}
2333 }
2334 fields: {
2335 key: "doubleValue"
2336 value: {number_value: 1234.5678}
2337 }
2338 fields: {
2339 key: "stringValue"
2340 value: {string_value: "Hello world!"}
2341 }
2342 fields: {
2343 key: "listValue"
2344 value: {
2345 list_value: {
2346 values: {
2347 number_value: 1234
2348 }
2349 values: {
2350 string_value: "5678"
2351 }
2352 }
2353 }
2354 }
2355 fields: {
2356 key: "objectValue"
2357 value: {
2358 struct_value: {
2359 fields: {
2360 key: "value"
2361 value: {
2362 number_value: 0
2363 }
2364 }
2365 }
2366 }
2367 }
2368 }
2369 )");
Paul Yanga1868082019-03-10 17:33:46 -07002370 RunValidJsonTest(
2371 "StructWithEmptyListValue", REQUIRED,
2372 R"({
2373 "optionalStruct": {
2374 "listValue": []
2375 }
2376 })",
2377 R"(
2378 optional_struct: {
2379 fields: {
2380 key: "listValue"
2381 value: {
2382 list_value: {
2383 }
2384 }
2385 }
2386 }
2387 )");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002388 // Value
2389 RunValidJsonTest(
2390 "ValueAcceptInteger", REQUIRED,
2391 R"({"optionalValue": 1})",
2392 "optional_value: { number_value: 1}");
2393 RunValidJsonTest(
2394 "ValueAcceptFloat", REQUIRED,
2395 R"({"optionalValue": 1.5})",
2396 "optional_value: { number_value: 1.5}");
2397 RunValidJsonTest(
2398 "ValueAcceptBool", REQUIRED,
2399 R"({"optionalValue": false})",
2400 "optional_value: { bool_value: false}");
2401 RunValidJsonTest(
2402 "ValueAcceptNull", REQUIRED,
2403 R"({"optionalValue": null})",
2404 "optional_value: { null_value: NULL_VALUE}");
2405 RunValidJsonTest(
2406 "ValueAcceptString", REQUIRED,
2407 R"({"optionalValue": "hello"})",
2408 R"(optional_value: { string_value: "hello"})");
2409 RunValidJsonTest(
2410 "ValueAcceptList", REQUIRED,
2411 R"({"optionalValue": [0, "hello"]})",
2412 R"(
2413 optional_value: {
2414 list_value: {
2415 values: {
2416 number_value: 0
2417 }
2418 values: {
2419 string_value: "hello"
2420 }
2421 }
2422 }
2423 )");
2424 RunValidJsonTest(
2425 "ValueAcceptObject", REQUIRED,
2426 R"({"optionalValue": {"value": 1}})",
2427 R"(
2428 optional_value: {
2429 struct_value: {
2430 fields: {
2431 key: "value"
2432 value: {
2433 number_value: 1
2434 }
2435 }
2436 }
2437 }
2438 )");
Paul Yang4b145b12019-03-12 10:56:58 -07002439 RunValidJsonTest(
2440 "RepeatedValue", REQUIRED,
2441 R"({
2442 "repeatedValue": [["a"]]
2443 })",
2444 R"(
2445 repeated_value: [
2446 {
2447 list_value: {
2448 values: [
2449 { string_value: "a"}
2450 ]
2451 }
2452 }
2453 ]
2454 )");
2455 RunValidJsonTest(
2456 "RepeatedListValue", REQUIRED,
2457 R"({
2458 "repeatedListValue": [["a"]]
2459 })",
2460 R"(
2461 repeated_list_value: [
2462 {
2463 values: [
2464 { string_value: "a"}
2465 ]
2466 }
2467 ]
2468 )");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002469
2470 // Any
2471 RunValidJsonTest(
2472 "Any", REQUIRED,
2473 R"({
2474 "optionalAny": {
2475 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2476 "optionalInt32": 12345
2477 }
2478 })",
2479 R"(
2480 optional_any: {
2481 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2482 optional_int32: 12345
2483 }
2484 }
2485 )");
2486 RunValidJsonTest(
2487 "AnyNested", REQUIRED,
2488 R"({
2489 "optionalAny": {
2490 "@type": "type.googleapis.com/google.protobuf.Any",
2491 "value": {
2492 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2493 "optionalInt32": 12345
2494 }
2495 }
2496 })",
2497 R"(
2498 optional_any: {
2499 [type.googleapis.com/google.protobuf.Any] {
2500 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2501 optional_int32: 12345
2502 }
2503 }
2504 }
2505 )");
2506 // The special "@type" tag is not required to appear first.
2507 RunValidJsonTest(
2508 "AnyUnorderedTypeTag", REQUIRED,
2509 R"({
2510 "optionalAny": {
2511 "optionalInt32": 12345,
2512 "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
2513 }
2514 })",
2515 R"(
2516 optional_any: {
2517 [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2518 optional_int32: 12345
2519 }
2520 }
2521 )");
2522 // Well-known types in Any.
2523 RunValidJsonTest(
2524 "AnyWithInt32ValueWrapper", REQUIRED,
2525 R"({
2526 "optionalAny": {
2527 "@type": "type.googleapis.com/google.protobuf.Int32Value",
2528 "value": 12345
2529 }
2530 })",
2531 R"(
2532 optional_any: {
2533 [type.googleapis.com/google.protobuf.Int32Value] {
2534 value: 12345
2535 }
2536 }
2537 )");
2538 RunValidJsonTest(
2539 "AnyWithDuration", REQUIRED,
2540 R"({
2541 "optionalAny": {
2542 "@type": "type.googleapis.com/google.protobuf.Duration",
2543 "value": "1.5s"
2544 }
2545 })",
2546 R"(
2547 optional_any: {
2548 [type.googleapis.com/google.protobuf.Duration] {
2549 seconds: 1
2550 nanos: 500000000
2551 }
2552 }
2553 )");
2554 RunValidJsonTest(
2555 "AnyWithTimestamp", REQUIRED,
2556 R"({
2557 "optionalAny": {
2558 "@type": "type.googleapis.com/google.protobuf.Timestamp",
2559 "value": "1970-01-01T00:00:00Z"
2560 }
2561 })",
2562 R"(
2563 optional_any: {
2564 [type.googleapis.com/google.protobuf.Timestamp] {
2565 seconds: 0
2566 nanos: 0
2567 }
2568 }
2569 )");
2570 RunValidJsonTest(
2571 "AnyWithFieldMask", REQUIRED,
2572 R"({
2573 "optionalAny": {
2574 "@type": "type.googleapis.com/google.protobuf.FieldMask",
2575 "value": "foo,barBaz"
2576 }
2577 })",
2578 R"(
2579 optional_any: {
2580 [type.googleapis.com/google.protobuf.FieldMask] {
2581 paths: ["foo", "bar_baz"]
2582 }
2583 }
2584 )");
2585 RunValidJsonTest(
2586 "AnyWithStruct", REQUIRED,
2587 R"({
2588 "optionalAny": {
2589 "@type": "type.googleapis.com/google.protobuf.Struct",
2590 "value": {
2591 "foo": 1
2592 }
2593 }
2594 })",
2595 R"(
2596 optional_any: {
2597 [type.googleapis.com/google.protobuf.Struct] {
2598 fields: {
2599 key: "foo"
2600 value: {
2601 number_value: 1
2602 }
2603 }
2604 }
2605 }
2606 )");
2607 RunValidJsonTest(
2608 "AnyWithValueForJsonObject", REQUIRED,
2609 R"({
2610 "optionalAny": {
2611 "@type": "type.googleapis.com/google.protobuf.Value",
2612 "value": {
2613 "foo": 1
2614 }
2615 }
2616 })",
2617 R"(
2618 optional_any: {
2619 [type.googleapis.com/google.protobuf.Value] {
2620 struct_value: {
2621 fields: {
2622 key: "foo"
2623 value: {
2624 number_value: 1
2625 }
2626 }
2627 }
2628 }
2629 }
2630 )");
2631 RunValidJsonTest(
2632 "AnyWithValueForInteger", REQUIRED,
2633 R"({
2634 "optionalAny": {
2635 "@type": "type.googleapis.com/google.protobuf.Value",
2636 "value": 1
2637 }
2638 })",
2639 R"(
2640 optional_any: {
2641 [type.googleapis.com/google.protobuf.Value] {
2642 number_value: 1
2643 }
2644 }
2645 )");
2646
2647 RunValidJsonIgnoreUnknownTest(
2648 "IgnoreUnknownJsonNumber", REQUIRED,
2649 R"({
2650 "unknown": 1
2651 })",
2652 "");
2653 RunValidJsonIgnoreUnknownTest(
2654 "IgnoreUnknownJsonString", REQUIRED,
2655 R"({
2656 "unknown": "a"
2657 })",
2658 "");
2659 RunValidJsonIgnoreUnknownTest(
2660 "IgnoreUnknownJsonTrue", REQUIRED,
2661 R"({
2662 "unknown": true
2663 })",
2664 "");
2665 RunValidJsonIgnoreUnknownTest(
2666 "IgnoreUnknownJsonFalse", REQUIRED,
2667 R"({
2668 "unknown": false
2669 })",
2670 "");
2671 RunValidJsonIgnoreUnknownTest(
2672 "IgnoreUnknownJsonNull", REQUIRED,
2673 R"({
2674 "unknown": null
2675 })",
2676 "");
2677 RunValidJsonIgnoreUnknownTest(
2678 "IgnoreUnknownJsonObject", REQUIRED,
2679 R"({
2680 "unknown": {"a": 1}
2681 })",
2682 "");
Hao Nguyen6b4b9862019-04-24 15:29:17 -07002683
2684 ExpectParseFailureForJson("RejectTopLevelNull", REQUIRED, "null");
Feng Xiao6bbe1972018-08-08 17:00:41 -07002685}
2686
Feng Xiao6bbe1972018-08-08 17:00:41 -07002687} // namespace protobuf
2688} // namespace google