conformance_test.cc 85.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdarg.h>
#include <string>
33
#include <fstream>
34 35

#include "conformance.pb.h"
36
#include "conformance_test.h"
37
#include <google/protobuf/test_messages_proto3.pb.h>
Yilun Chong's avatar
Yilun Chong committed
38
#include <google/protobuf/test_messages_proto2.pb.h>
39

40
#include <google/protobuf/stubs/common.h>
41
#include <google/protobuf/stubs/stringprintf.h>
42
#include <google/protobuf/text_format.h>
43
#include <google/protobuf/util/field_comparator.h>
44
#include <google/protobuf/util/json_util.h>
45 46
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/util/type_resolver_util.h>
47 48
#include <google/protobuf/wire_format_lite.h>

49
#include "third_party/jsoncpp/json.h"
50

51 52
using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
53
using conformance::WireFormat;
54 55 56
using google::protobuf::Descriptor;
using google::protobuf::FieldDescriptor;
using google::protobuf::internal::WireFormatLite;
57
using google::protobuf::TextFormat;
58
using google::protobuf::util::DefaultFieldComparator;
59 60 61 62
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::MessageDifferencer;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
63
using protobuf_test_messages::proto3::TestAllTypes;
Yilun Chong's avatar
Yilun Chong committed
64
using protobuf_test_messages::proto2::TestAllTypesProto2;
65 66
using std::string;

67
namespace {
68

69 70 71 72 73 74
static const char kTypeUrlPrefix[] = "type.googleapis.com";

static string GetTypeUrl(const Descriptor* message) {
  return string(kTypeUrlPrefix) + "/" + message->full_name();
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
/* Routines for building arbitrary protos *************************************/

// We would use CodedOutputStream except that we want more freedom to build
// arbitrary protos (even invalid ones).

const string empty;

string cat(const string& a, const string& b,
           const string& c = empty,
           const string& d = empty,
           const string& e = empty,
           const string& f = empty,
           const string& g = empty,
           const string& h = empty,
           const string& i = empty,
           const string& j = empty,
           const string& k = empty,
           const string& l = empty) {
  string ret;
  ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() +
              g.size() + h.size() + i.size() + j.size() + k.size() + l.size());
  ret.append(a);
  ret.append(b);
  ret.append(c);
  ret.append(d);
  ret.append(e);
  ret.append(f);
  ret.append(g);
  ret.append(h);
  ret.append(i);
  ret.append(j);
  ret.append(k);
  ret.append(l);
  return ret;
}

// The maximum number of bytes that it takes to encode a 64-bit varint.
#define VARINT_MAX_LEN 10

114
size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) {
115 116 117 118 119
  if (val == 0) { buf[0] = 0; return 1; }
  size_t i = 0;
  while (val) {
    uint8_t byte = val & 0x7fU;
    val >>= 7;
120 121 122 123 124 125
    if (val || over_encoded_bytes) byte |= 0x80U;
    buf[i++] = byte;
  }
  while (over_encoded_bytes--) {
    assert(i < 10);
    uint8_t byte = over_encoded_bytes ? 0x80 : 0;
126 127 128 129 130 131 132
    buf[i++] = byte;
  }
  return i;
}

string varint(uint64_t x) {
  char buf[VARINT_MAX_LEN];
133 134 135 136 137 138 139 140 141
  size_t len = vencode64(x, 0, buf);
  return string(buf, len);
}

// Encodes a varint that is |extra| bytes longer than it needs to be, but still
// valid.
string longvarint(uint64_t x, int extra) {
  char buf[VARINT_MAX_LEN];
  size_t len = vencode64(x, extra, buf);
142 143 144 145 146 147 148 149
  return string(buf, len);
}

// TODO: proper byte-swapping for big-endian machines.
string fixed32(void *data) { return string(static_cast<char*>(data), 4); }
string fixed64(void *data) { return string(static_cast<char*>(data), 8); }

string delim(const string& buf) { return cat(varint(buf.size()), buf); }
150 151
string u32(uint32_t u32) { return fixed32(&u32); }
string u64(uint64_t u64) { return fixed64(&u64); }
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
string flt(float f) { return fixed32(&f); }
string dbl(double d) { return fixed64(&d); }
string zz32(int32_t x) { return varint(WireFormatLite::ZigZagEncode32(x)); }
string zz64(int64_t x) { return varint(WireFormatLite::ZigZagEncode64(x)); }

string tag(uint32_t fieldnum, char wire_type) {
  return varint((fieldnum << 3) | wire_type);
}

string submsg(uint32_t fn, const string& buf) {
  return cat( tag(fn, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(buf) );
}

#define UNKNOWN_FIELD 666

167
const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type,
Yilun Chong's avatar
Yilun Chong committed
168 169 170 171
                                       bool repeated, bool isProto3) {

  const Descriptor* d = isProto3 ?
      TestAllTypes().GetDescriptor() : TestAllTypesProto2().GetDescriptor();
172 173
  for (int i = 0; i < d->field_count(); i++) {
    const FieldDescriptor* f = d->field(i);
174
    if (f->type() == type && f->is_repeated() == repeated) {
175
      return f;
176 177 178
    }
  }
  GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
179
  return nullptr;
180 181
}

182 183 184 185 186 187 188
string UpperCase(string str) {
  for (int i = 0; i < str.size(); i++) {
    str[i] = toupper(str[i]);
  }
  return str;
}

189 190 191 192 193
}  // anonymous namespace

namespace google {
namespace protobuf {

194 195 196 197 198 199 200 201
void ConformanceTestSuite::ReportSuccess(const string& test_name) {
  if (expected_to_fail_.erase(test_name) != 0) {
    StringAppendF(&output_,
                  "ERROR: test %s is in the failure list, but test succeeded.  "
                  "Remove it from the failure list.\n",
                  test_name.c_str());
    unexpected_succeeding_tests_.insert(test_name);
  }
202 203 204
  successes_++;
}

205
void ConformanceTestSuite::ReportFailure(const string& test_name,
Bo Yang's avatar
Bo Yang committed
206
                                         ConformanceLevel level,
207 208
                                         const ConformanceRequest& request,
                                         const ConformanceResponse& response,
209 210
                                         const char* fmt, ...) {
  if (expected_to_fail_.erase(test_name) == 1) {
211 212 213
    expected_failures_++;
    if (!verbose_)
      return;
Bo Yang's avatar
Bo Yang committed
214 215
  } else if (level == RECOMMENDED && !enforce_recommended_) {
    StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str());
216
  } else {
217
    StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
218 219
    unexpected_failing_tests_.insert(test_name);
  }
220 221 222 223
  va_list args;
  va_start(args, fmt);
  StringAppendV(&output_, fmt, args);
  va_end(args);
224 225 226 227 228 229 230 231 232 233 234 235 236 237
  StringAppendF(&output_, " request=%s, response=%s\n",
                request.ShortDebugString().c_str(),
                response.ShortDebugString().c_str());
}

void ConformanceTestSuite::ReportSkip(const string& test_name,
                                      const ConformanceRequest& request,
                                      const ConformanceResponse& response) {
  if (verbose_) {
    StringAppendF(&output_, "SKIPPED, test=%s request=%s, response=%s\n",
                  test_name.c_str(), request.ShortDebugString().c_str(),
                  response.ShortDebugString().c_str());
  }
  skipped_.insert(test_name);
238 239
}

Bo Yang's avatar
Bo Yang committed
240 241 242 243 244 245 246 247 248
string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) {
  switch (level) {
    case REQUIRED: return "Required";
    case RECOMMENDED: return "Recommended";
  }
  GOOGLE_LOG(FATAL) << "Unknown value: " << level;
  return "";
}

249 250
void ConformanceTestSuite::RunTest(const string& test_name,
                                   const ConformanceRequest& request,
251
                                   ConformanceResponse* response) {
252 253
  if (test_names_.insert(test_name).second == false) {
    GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
254 255
  }

256 257 258 259
  string serialized_request;
  string serialized_response;
  request.SerializeToString(&serialized_request);

260
  runner_->RunTest(test_name, serialized_request, &serialized_response);
261 262 263 264 265 266 267

  if (!response->ParseFromString(serialized_response)) {
    response->Clear();
    response->set_runtime_error("response proto could not be parsed.");
  }

  if (verbose_) {
268 269
    StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
                  test_name.c_str(),
270 271 272 273 274
                  request.ShortDebugString().c_str(),
                  response->ShortDebugString().c_str());
  }
}

275
void ConformanceTestSuite::RunValidInputTest(
Bo Yang's avatar
Bo Yang committed
276 277
    const string& test_name, ConformanceLevel level, const string& input,
    WireFormat input_format, const string& equivalent_text_format,
Yilun Chong's avatar
Yilun Chong committed
278
    WireFormat requested_output, bool isProto3) {
279
  TestAllTypes reference_message;
280
  TestAllTypesProto2 reference_message_proto2;
281
  GOOGLE_CHECK(
282 283 284 285 286
      isProto3 ?
          TextFormat::ParseFromString(equivalent_text_format, &reference_message)
          :
          TextFormat::ParseFromString(equivalent_text_format, &reference_message_proto2)
  )
287 288
          << "Failed to parse data for test case: " << test_name
          << ", data: " << equivalent_text_format;
289 290 291 292 293

  ConformanceRequest request;
  ConformanceResponse response;

  switch (input_format) {
Yilun Chong's avatar
Yilun Chong committed
294
    case conformance::PROTOBUF: {
295
      request.set_protobuf_payload(input);
Yilun Chong's avatar
Yilun Chong committed
296 297 298 299 300
      if (isProto3) {
        request.set_message_type("proto3");
      } else {
        request.set_message_type("proto2");
      }
301
      break;
Yilun Chong's avatar
Yilun Chong committed
302
    }
303 304 305 306 307

    case conformance::JSON:
      request.set_json_payload(input);
      break;

308
    default:
309 310 311 312 313 314 315 316
      GOOGLE_LOG(FATAL) << "Unspecified input format";
  }

  request.set_requested_output_format(requested_output);

  RunTest(test_name, request, &response);

  TestAllTypes test_message;
Yilun Chong's avatar
Yilun Chong committed
317
  TestAllTypesProto2 test_message_proto2;
318 319

  switch (response.result_case()) {
320
    case ConformanceResponse::RESULT_NOT_SET:
321
      ReportFailure(test_name, level, request, response,
322 323 324
                    "Response didn't have any field in the Response.");
      return;

325 326
    case ConformanceResponse::kParseError:
    case ConformanceResponse::kRuntimeError:
327
    case ConformanceResponse::kSerializeError:
328
      ReportFailure(test_name, level, request, response,
329
                    "Failed to parse input or produce output.");
330 331 332 333 334 335 336 337 338
      return;

    case ConformanceResponse::kSkipped:
      ReportSkip(test_name, request, response);
      return;

    case ConformanceResponse::kJsonPayload: {
      if (requested_output != conformance::JSON) {
        ReportFailure(
Bo Yang's avatar
Bo Yang committed
339
            test_name, level, request, response,
340 341 342 343 344 345 346 347
            "Test was asked for protobuf output but provided JSON instead.");
        return;
      }
      string binary_protobuf;
      Status status =
          JsonToBinaryString(type_resolver_.get(), type_url_,
                             response.json_payload(), &binary_protobuf);
      if (!status.ok()) {
Bo Yang's avatar
Bo Yang committed
348
        ReportFailure(test_name, level, request, response,
349 350 351 352
                      "JSON output we received from test was unparseable.");
        return;
      }

Yilun Chong's avatar
Yilun Chong committed
353 354 355
      if (isProto3) {
        if (!test_message.ParseFromString(binary_protobuf)) {
          ReportFailure(test_name, level, request, response,
356 357
                      "INTERNAL ERROR: internal JSON->protobuf transcode "
                      "yielded unparseable proto.");
Yilun Chong's avatar
Yilun Chong committed
358 359 360 361 362 363 364 365 366
          return;
        }
      } else {
        if (!test_message_proto2.ParseFromString(binary_protobuf)) {
          ReportFailure(test_name, level, request, response,
                      "INTERNAL ERROR: internal JSON->protobuf transcode "
                      "yielded unparseable proto.");
          return;
        }
367 368
      }

369 370 371 372 373 374
      break;
    }

    case ConformanceResponse::kProtobufPayload: {
      if (requested_output != conformance::PROTOBUF) {
        ReportFailure(
Bo Yang's avatar
Bo Yang committed
375
            test_name, level, request, response,
376 377 378 379
            "Test was asked for JSON output but provided protobuf instead.");
        return;
      }

Yilun Chong's avatar
Yilun Chong committed
380 381 382 383 384 385 386 387 388 389 390 391
      if (isProto3) {
        if (!test_message.ParseFromString(response.protobuf_payload())) {
          ReportFailure(test_name, level, request, response,
                     "Protobuf output we received from test was unparseable.");
          return;
        }
      } else {
        if (!test_message_proto2.ParseFromString(response.protobuf_payload())) {
          ReportFailure(test_name, level, request, response,
                     "Protobuf output we received from test was unparseable.");
          return;
        }
392 393 394 395
      }

      break;
    }
396 397 398 399

    default:
      GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
                        << response.result_case();
400 401 402
  }

  MessageDifferencer differencer;
403 404 405
  DefaultFieldComparator field_comparator;
  field_comparator.set_treat_nan_as_equal(true);
  differencer.set_field_comparator(&field_comparator);
406 407 408
  string differences;
  differencer.ReportDifferencesToString(&differences);

409 410 411 412 413 414 415
  bool check;
  if (isProto3) {
    check = differencer.Compare(reference_message, test_message);
  } else {
    check = differencer.Compare(reference_message_proto2, test_message_proto2);
  }
  if (check) {
416 417
    ReportSuccess(test_name);
  } else {
Bo Yang's avatar
Bo Yang committed
418
    ReportFailure(test_name, level, request, response,
419 420 421 422 423
                  "Output was not equivalent to reference message: %s.",
                  differences.c_str());
  }
}

424 425
// Expect that this precise protobuf will cause a parse error.
void ConformanceTestSuite::ExpectParseFailureForProto(
Yilun Chong's avatar
Yilun Chong committed
426 427
    const string& proto, const string& test_name, ConformanceLevel level,
    bool isProto3) {
428 429 430
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(proto);
Yilun Chong's avatar
Yilun Chong committed
431 432 433 434 435
  if (isProto3) {
    request.set_message_type("proto3");
  } else {
    request.set_message_type("proto2");
  }
Bo Yang's avatar
Bo Yang committed
436 437
  string effective_test_name = ConformanceLevelToString(level) +
      ".ProtobufInput." + test_name;
438 439 440

  // We don't expect output, but if the program erroneously accepts the protobuf
  // we let it send its response as this.  We must not leave it unspecified.
441
  request.set_requested_output_format(conformance::PROTOBUF);
442

443
  RunTest(effective_test_name, request, &response);
444
  if (response.result_case() == ConformanceResponse::kParseError) {
445
    ReportSuccess(effective_test_name);
446 447
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
448
  } else {
Bo Yang's avatar
Bo Yang committed
449
    ReportFailure(effective_test_name, level, request, response,
450
                  "Should have failed to parse, but didn't.");
451 452 453 454 455 456 457 458
  }
}

// Expect that this protobuf will cause a parse error, even if it is followed
// by valid protobuf data.  We can try running this twice: once with this
// data verbatim and once with this data followed by some valid data.
//
// TODO(haberman): implement the second of these.
459
void ConformanceTestSuite::ExpectHardParseFailureForProto(
Yilun Chong's avatar
Yilun Chong committed
460 461 462
    const string& proto, const string& test_name, ConformanceLevel level,
    bool isProto3) {
  return ExpectParseFailureForProto(proto, test_name, level, isProto3);
463
}
464

465
void ConformanceTestSuite::RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
466
    const string& test_name, ConformanceLevel level, const string& input_json,
467
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
468 469 470
  RunValidInputTest(
      ConformanceLevelToString(level) + ".JsonInput." + test_name +
      ".ProtobufOutput", level, input_json, conformance::JSON,
Yilun Chong's avatar
Yilun Chong committed
471
      equivalent_text_format, conformance::PROTOBUF, true);
Bo Yang's avatar
Bo Yang committed
472 473 474
  RunValidInputTest(
      ConformanceLevelToString(level) + ".JsonInput." + test_name +
      ".JsonOutput", level, input_json, conformance::JSON,
Yilun Chong's avatar
Yilun Chong committed
475
      equivalent_text_format, conformance::JSON, true);
476 477 478
}

void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
479
    const string& test_name, ConformanceLevel level, const TestAllTypes& input,
Yilun Chong's avatar
Yilun Chong committed
480
    const string& equivalent_text_format, bool isProto3) {
Bo Yang's avatar
Bo Yang committed
481 482 483
  RunValidInputTest(
      ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
      ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
Yilun Chong's avatar
Yilun Chong committed
484
      equivalent_text_format, conformance::JSON, isProto3);
485 486
}

487
void ConformanceTestSuite::RunValidProtobufTest(
488
    const string& test_name, ConformanceLevel level,
Yilun Chong's avatar
Yilun Chong committed
489 490
    const string& input_protobuf, const string& equivalent_text_format,
    bool isProto3) {
491 492 493 494
  string rname = ".ProtobufInput.";
  if (!isProto3) {
    rname = ".Protobuf2Input.";
  }
495
  RunValidInputTest(
496
      ConformanceLevelToString(level) + rname + test_name +
497
      ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
Yilun Chong's avatar
Yilun Chong committed
498
      equivalent_text_format, conformance::PROTOBUF, isProto3);
499
  RunValidInputTest(
500
      ConformanceLevelToString(level) + rname +  test_name +
501
      ".JsonOutput", level, input_protobuf, conformance::PROTOBUF,
Yilun Chong's avatar
Yilun Chong committed
502
      equivalent_text_format, conformance::JSON, isProto3);
503 504 505
}

void ConformanceTestSuite::RunValidProtobufTestWithMessage(
506
    const string& test_name, ConformanceLevel level, const TestAllTypes& input,
Yilun Chong's avatar
Yilun Chong committed
507 508
    const string& equivalent_text_format, bool isProto3) {
  RunValidProtobufTest(test_name, level, input.SerializeAsString(), equivalent_text_format, isProto3);
509 510
}

511 512 513 514 515 516
// According to proto3 JSON specification, JSON serializers follow more strict
// rules than parsers (e.g., a serializer must serialize int32 values as JSON
// numbers while the parser is allowed to accept them as JSON strings). This
// method allows strict checking on a proto3 JSON serializer by inspecting
// the JSON output directly.
void ConformanceTestSuite::RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
517
    const string& test_name, ConformanceLevel level, const string& input_json,
518 519 520 521 522 523
    const Validator& validator) {
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
  request.set_requested_output_format(conformance::JSON);

Bo Yang's avatar
Bo Yang committed
524 525
  string effective_test_name = ConformanceLevelToString(level) +
      ".JsonInput." + test_name + ".Validator";
526 527 528

  RunTest(effective_test_name, request, &response);

529 530 531 532 533
  if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
    return;
  }

534
  if (response.result_case() != ConformanceResponse::kJsonPayload) {
Bo Yang's avatar
Bo Yang committed
535
    ReportFailure(effective_test_name, level, request, response,
536 537 538 539 540 541 542
                  "Expected JSON payload but got type %d.",
                  response.result_case());
    return;
  }
  Json::Reader reader;
  Json::Value value;
  if (!reader.parse(response.json_payload(), value)) {
Bo Yang's avatar
Bo Yang committed
543
    ReportFailure(effective_test_name, level, request, response,
544 545 546 547 548
                  "JSON payload cannot be parsed as valid JSON: %s",
                  reader.getFormattedErrorMessages().c_str());
    return;
  }
  if (!validator(value)) {
Bo Yang's avatar
Bo Yang committed
549
    ReportFailure(effective_test_name, level, request, response,
550 551 552 553 554 555 556
                  "JSON payload validation failed.");
    return;
  }
  ReportSuccess(effective_test_name);
}

void ConformanceTestSuite::ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
557
    const string& test_name, ConformanceLevel level, const string& input_json) {
558 559 560
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
Bo Yang's avatar
Bo Yang committed
561 562
  string effective_test_name =
      ConformanceLevelToString(level) + ".JsonInput." + test_name;
563 564 565 566 567 568 569 570

  // We don't expect output, but if the program erroneously accepts the protobuf
  // we let it send its response as this.  We must not leave it unspecified.
  request.set_requested_output_format(conformance::JSON);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kParseError) {
    ReportSuccess(effective_test_name);
571 572
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
573
  } else {
Bo Yang's avatar
Bo Yang committed
574
    ReportFailure(effective_test_name, level, request, response,
575 576 577 578 579
                  "Should have failed to parse, but didn't.");
  }
}

void ConformanceTestSuite::ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
580
    const string& test_name, ConformanceLevel level, const string& text_format) {
581 582 583 584 585 586 587 588
  TestAllTypes payload_message;
  GOOGLE_CHECK(
      TextFormat::ParseFromString(text_format, &payload_message))
          << "Failed to parse: " << text_format;

  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(payload_message.SerializeAsString());
Yilun Chong's avatar
Yilun Chong committed
589
  request.set_message_type("proto3");
Bo Yang's avatar
Bo Yang committed
590 591
  string effective_test_name =
      ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
592 593 594 595 596
  request.set_requested_output_format(conformance::JSON);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kSerializeError) {
    ReportSuccess(effective_test_name);
597 598
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
599
  } else {
Bo Yang's avatar
Bo Yang committed
600
    ReportFailure(effective_test_name, level, request, response,
601 602 603 604
                  "Should have failed to serialize, but didn't.");
  }
}

Yilun Chong's avatar
Yilun Chong committed
605
//TODO: proto2?
606
void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
607 608 609 610 611 612 613 614 615 616
  // Incomplete values for each wire type.
  static const string incompletes[6] = {
    string("\x80"),     // VARINT
    string("abcdefg"),  // 64BIT
    string("\x80"),     // DELIMITED (partial length)
    string(),           // START_GROUP (no value required)
    string(),           // END_GROUP (no value required)
    string("abc")       // 32BIT
  };

Yilun Chong's avatar
Yilun Chong committed
617 618
  const FieldDescriptor* field = GetFieldForType(type, false, true);
  const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
619 620
  WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
      static_cast<WireFormatLite::FieldType>(type));
621
  const string& incomplete = incompletes[wire_type];
622 623
  const string type_name =
      UpperCase(string(".") + FieldDescriptor::TypeName(type));
624

625
  ExpectParseFailureForProto(
626
      tag(field->number(), wire_type),
Yilun Chong's avatar
Yilun Chong committed
627
      "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED, true);
628

629
  ExpectParseFailureForProto(
630
      tag(rep_field->number(), wire_type),
Yilun Chong's avatar
Yilun Chong committed
631
      "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED, true);
632

633 634
  ExpectParseFailureForProto(
      tag(UNKNOWN_FIELD, wire_type),
Yilun Chong's avatar
Yilun Chong committed
635
      "PrematureEofBeforeUnknownValue" + type_name, REQUIRED, true);
636 637

  ExpectParseFailureForProto(
638
      cat( tag(field->number(), wire_type), incomplete ),
Yilun Chong's avatar
Yilun Chong committed
639
      "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED, true);
640 641

  ExpectParseFailureForProto(
642
      cat( tag(rep_field->number(), wire_type), incomplete ),
Yilun Chong's avatar
Yilun Chong committed
643
      "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED, true);
644 645

  ExpectParseFailureForProto(
646
      cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
Yilun Chong's avatar
Yilun Chong committed
647
      "PrematureEofInsideUnknownValue" + type_name, REQUIRED, true);
648 649 650

  if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
    ExpectParseFailureForProto(
651
        cat( tag(field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
652
        "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
Yilun Chong's avatar
Yilun Chong committed
653
        REQUIRED, true);
654 655

    ExpectParseFailureForProto(
656
        cat( tag(rep_field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
657
        "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
Yilun Chong's avatar
Yilun Chong committed
658
        REQUIRED, true);
659 660 661

    // EOF in the middle of delimited data for unknown value.
    ExpectParseFailureForProto(
662
        cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
Yilun Chong's avatar
Yilun Chong committed
663
        "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED, true);
664

665
    if (type == FieldDescriptor::TYPE_MESSAGE) {
666 667 668 669 670
      // Submessage ends in the middle of a value.
      string incomplete_submsg =
          cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
                incompletes[WireFormatLite::WIRETYPE_VARINT] );
      ExpectHardParseFailureForProto(
671
          cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
672
               varint(incomplete_submsg.size()),
673
               incomplete_submsg ),
Yilun Chong's avatar
Yilun Chong committed
674
          "PrematureEofInSubmessageValue" + type_name, REQUIRED, true);
675
    }
676
  } else if (type != FieldDescriptor::TYPE_GROUP) {
677 678 679 680
    // Non-delimited, non-group: eligible for packing.

    // Packed region ends in the middle of a value.
    ExpectHardParseFailureForProto(
681 682
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(incomplete.size()), incomplete),
Yilun Chong's avatar
Yilun Chong committed
683
        "PrematureEofInPackedFieldValue" + type_name, REQUIRED, true);
684 685 686

    // EOF in the middle of packed region.
    ExpectParseFailureForProto(
687 688
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(1)),
Yilun Chong's avatar
Yilun Chong committed
689
        "PrematureEofInPackedField" + type_name, REQUIRED, true);
690 691 692
  }
}

693 694
void ConformanceTestSuite::TestValidDataForType(
    FieldDescriptor::Type type,
Yilun Chong's avatar
Yilun Chong committed
695
    std::vector<std::pair<std::string, std::string>> values, bool isProto3) {
696 697 698 699
  const string type_name =
      UpperCase(string(".") + FieldDescriptor::TypeName(type));
  WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
      static_cast<WireFormatLite::FieldType>(type));
Yilun Chong's avatar
Yilun Chong committed
700 701
  const FieldDescriptor* field = GetFieldForType(type, false, isProto3);
  const FieldDescriptor* rep_field = GetFieldForType(type, true, isProto3);
702 703 704

  RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED,
                       cat(tag(field->number(), wire_type), values[0].first),
Yilun Chong's avatar
Yilun Chong committed
705
                       field->name() + ": " + values[0].second, isProto3);
706 707 708 709 710 711 712

  string proto;
  string text = field->name() + ": " + values.back().second;
  for (size_t i = 0; i < values.size(); i++) {
    proto += cat(tag(field->number(), wire_type), values[i].first);
  }
  RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
Yilun Chong's avatar
Yilun Chong committed
713
                       proto, text, isProto3);
714 715 716 717 718 719 720 721

  proto.clear();
  text.clear();

  for (size_t i = 0; i < values.size(); i++) {
    proto += cat(tag(rep_field->number(), wire_type), values[i].first);
    text += rep_field->name() + ": " + values[i].second + " ";
  }
722 723
  RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED,
                       proto, text, isProto3);
724 725
}

726 727 728
void ConformanceTestSuite::SetFailureList(const string& filename,
                                          const vector<string>& failure_list) {
  failure_list_filename_ = filename;
729 730 731 732 733 734
  expected_to_fail_.clear();
  std::copy(failure_list.begin(), failure_list.end(),
            std::inserter(expected_to_fail_, expected_to_fail_.end()));
}

bool ConformanceTestSuite::CheckSetEmpty(const set<string>& set_to_check,
735 736
                                         const std::string& write_to_file,
                                         const std::string& msg) {
737 738 739 740
  if (set_to_check.empty()) {
    return true;
  } else {
    StringAppendF(&output_, "\n");
741
    StringAppendF(&output_, "%s\n\n", msg.c_str());
742 743
    for (set<string>::const_iterator iter = set_to_check.begin();
         iter != set_to_check.end(); ++iter) {
744
      StringAppendF(&output_, "  %s\n", iter->c_str());
745
    }
746
    StringAppendF(&output_, "\n");
747 748 749 750 751 752 753 754 755 756 757 758 759 760

    if (!write_to_file.empty()) {
      std::ofstream os(write_to_file);
      if (os) {
        for (set<string>::const_iterator iter = set_to_check.begin();
             iter != set_to_check.end(); ++iter) {
          os << *iter << "\n";
        }
      } else {
        StringAppendF(&output_, "Failed to open file: %s\n",
                      write_to_file.c_str());
      }
    }

761 762 763 764
    return false;
  }
}

Yilun Chong's avatar
Yilun Chong committed
765
// TODO: proto2?
766 767 768 769 770 771 772 773 774 775 776
void ConformanceTestSuite::TestIllegalTags() {
  // field num 0 is illegal
  string nullfield[] = {
    "\1DEADBEEF",
    "\2\1\1",
    "\3\4",
    "\5DEAD"
  };
  for (int i = 0; i < 4; i++) {
    string name = "IllegalZeroFieldNum_Case_0";
    name.back() += i;
Yilun Chong's avatar
Yilun Chong committed
777
    ExpectParseFailureForProto(nullfield[i], name, REQUIRED, true);
778 779 780
  }
}

781
bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
782 783 784
                                    std::string* output) {
  runner_ = runner;
  successes_ = 0;
785 786
  expected_failures_ = 0;
  skipped_.clear();
787 788 789
  test_names_.clear();
  unexpected_failing_tests_.clear();
  unexpected_succeeding_tests_.clear();
790 791 792 793 794
  type_resolver_.reset(NewTypeResolverForDescriptorPool(
      kTypeUrlPrefix, DescriptorPool::generated_pool()));
  type_url_ = GetTypeUrl(TestAllTypes::descriptor());

  output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
795 796

  for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
797
    if (i == FieldDescriptor::TYPE_GROUP) continue;
798
    TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
799 800
  }

801 802
  TestIllegalTags();

803 804 805 806 807 808 809 810 811 812 813
  int64 kInt64Min = -9223372036854775808ULL;
  int64 kInt64Max = 9223372036854775807ULL;
  uint64 kUint64Max = 18446744073709551615ULL;
  int32 kInt32Max = 2147483647;
  int32 kInt32Min = -2147483648;
  uint32 kUint32Max = 4294967295UL;

  TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
    {dbl(0.1), "0.1"},
    {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
    {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
Yilun Chong's avatar
Yilun Chong committed
814
  }, true);
815 816 817 818 819 820
  TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
    {dbl(0.1), "0.1"},
    {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
    {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
  }, false);

821 822
  TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
    {flt(0.1), "0.1"},
823
    {flt(1.00000075e-36), "1.00000075e-36"},
824 825
    {flt(3.402823e+38), "3.402823e+38"},  // 3.40282347e+38
    {flt(1.17549435e-38f), "1.17549435e-38"}
Yilun Chong's avatar
Yilun Chong committed
826
  }, true);
827 828 829 830
  TestValidDataForType(FieldDescriptor::TYPE_INT64, {
    {varint(12345), "12345"},
    {varint(kInt64Max), std::to_string(kInt64Max)},
    {varint(kInt64Min), std::to_string(kInt64Min)}
Yilun Chong's avatar
Yilun Chong committed
831
  }, true);
832 833 834 835
  TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
    {varint(12345), "12345"},
    {varint(kUint64Max), std::to_string(kUint64Max)},
    {varint(0), "0"}
Yilun Chong's avatar
Yilun Chong committed
836
  }, true);
837 838
  TestValidDataForType(FieldDescriptor::TYPE_INT32, {
    {varint(12345), "12345"},
839 840
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
841 842
    {varint(kInt32Max), std::to_string(kInt32Max)},
    {varint(kInt32Min), std::to_string(kInt32Min)},
843 844 845
    {varint(1LL << 33), std::to_string(static_cast<int32>(1LL << 33))},
    {varint((1LL << 33) - 1),
     std::to_string(static_cast<int32>((1LL << 33) - 1))},
Yilun Chong's avatar
Yilun Chong committed
846
  }, true);
847 848
  TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
    {varint(12345), "12345"},
849 850
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
851
    {varint(kUint32Max), std::to_string(kUint32Max)},  // UINT32_MAX
852 853 854 855
    {varint(0), "0"},
    {varint(1LL << 33), std::to_string(static_cast<uint32>(1LL << 33))},
    {varint((1LL << 33) - 1),
     std::to_string(static_cast<uint32>((1LL << 33) - 1))},
Yilun Chong's avatar
Yilun Chong committed
856
  }, true);
857 858 859 860
  TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
    {u64(12345), "12345"},
    {u64(kUint64Max), std::to_string(kUint64Max)},
    {u64(0), "0"}
Yilun Chong's avatar
Yilun Chong committed
861
  }, true);
862 863 864 865
  TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
    {u32(12345), "12345"},
    {u32(kUint32Max), std::to_string(kUint32Max)},  // UINT32_MAX
    {u32(0), "0"}
Yilun Chong's avatar
Yilun Chong committed
866
  }, true);
867 868 869 870
  TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
    {u64(12345), "12345"},
    {u64(kInt64Max), std::to_string(kInt64Max)},
    {u64(kInt64Min), std::to_string(kInt64Min)}
Yilun Chong's avatar
Yilun Chong committed
871
  }, true);
872 873 874 875
  TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
    {u32(12345), "12345"},
    {u32(kInt32Max), std::to_string(kInt32Max)},
    {u32(kInt32Min), std::to_string(kInt32Min)}
Yilun Chong's avatar
Yilun Chong committed
876
  }, true);
877 878 879 880
  TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
    {varint(1), "true"},
    {varint(0), "false"},
    {varint(12345678), "true"}
Yilun Chong's avatar
Yilun Chong committed
881
  }, true);
882 883 884 885
  TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
    {zz32(12345), "12345"},
    {zz32(kInt32Max), std::to_string(kInt32Max)},
    {zz32(kInt32Min), std::to_string(kInt32Min)}
Yilun Chong's avatar
Yilun Chong committed
886
  }, true);
887 888 889 890
  TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
    {zz64(12345), "12345"},
    {zz64(kInt64Max), std::to_string(kInt64Max)},
    {zz64(kInt64Min), std::to_string(kInt64Min)}
Yilun Chong's avatar
Yilun Chong committed
891
  }, true);
892 893 894 895 896 897 898 899

  // TODO(haberman):
  // TestValidDataForType(FieldDescriptor::TYPE_STRING
  // TestValidDataForType(FieldDescriptor::TYPE_GROUP
  // TestValidDataForType(FieldDescriptor::TYPE_MESSAGE
  // TestValidDataForType(FieldDescriptor::TYPE_BYTES
  // TestValidDataForType(FieldDescriptor::TYPE_ENUM

Bo Yang's avatar
Bo Yang committed
900 901
  RunValidJsonTest("HelloWorld", REQUIRED,
                   "{\"optionalString\":\"Hello, World!\"}",
902
                   "optional_string: 'Hello, World!'");
903

904 905
  // NOTE: The spec for JSON support is still being sorted out, these may not
  // all be correct.
906 907
  // Test field name conventions.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
908
      "FieldNameInSnakeCase", REQUIRED,
909 910 911
      R"({
        "fieldname1": 1,
        "fieldName2": 2,
912
        "FieldName3": 3,
913
        "fieldName4": 4
914 915 916 917 918
      })",
      R"(
        fieldname1: 1
        field_name2: 2
        _field_name3: 3
919
        field__name4_: 4
920 921
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
922
      "FieldNameWithNumbers", REQUIRED,
923 924 925 926 927 928 929 930 931
      R"({
        "field0name5": 5,
        "field0Name6": 6
      })",
      R"(
        field0name5: 5
        field_0_name6: 6
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
932
      "FieldNameWithMixedCases", REQUIRED,
933 934
      R"({
        "fieldName7": 7,
Bo Yang's avatar
Bo Yang committed
935
        "FieldName8": 8,
936
        "fieldName9": 9,
Bo Yang's avatar
Bo Yang committed
937 938 939
        "FieldName10": 10,
        "FIELDNAME11": 11,
        "FIELDName12": 12
940 941 942 943 944 945 946 947 948
      })",
      R"(
        fieldName7: 7
        FieldName8: 8
        field_Name9: 9
        Field_Name10: 10
        FIELD_NAME11: 11
        FIELD_name12: 12
      )");
949
  RunValidJsonTest(
950
      "FieldNameWithDoubleUnderscores", RECOMMENDED,
951
      R"({
952 953
        "FieldName13": 13,
        "FieldName14": 14,
954 955 956
        "fieldName15": 15,
        "fieldName16": 16,
        "fieldName17": 17,
957
        "FieldName18": 18
958 959 960 961 962 963 964 965 966
      })",
      R"(
        __field_name13: 13
        __Field_name14: 14
        field__name15: 15
        field__Name16: 16
        field_name17__: 17
        Field_name18__: 18
      )");
967 968
  // Using the original proto field name in JSON is also allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
969
      "OriginalProtoFieldName", REQUIRED,
970 971 972 973
      R"({
        "fieldname1": 1,
        "field_name2": 2,
        "_field_name3": 3,
974
        "field__name4_": 4,
975 976 977 978 979 980 981
        "field0name5": 5,
        "field_0_name6": 6,
        "fieldName7": 7,
        "FieldName8": 8,
        "field_Name9": 9,
        "Field_Name10": 10,
        "FIELD_NAME11": 11,
982 983 984 985 986 987 988
        "FIELD_name12": 12,
        "__field_name13": 13,
        "__Field_name14": 14,
        "field__name15": 15,
        "field__Name16": 16,
        "field_name17__": 17,
        "Field_name18__": 18
989 990 991 992 993
      })",
      R"(
        fieldname1: 1
        field_name2: 2
        _field_name3: 3
994
        field__name4_: 4
995 996 997 998 999 1000 1001 1002
        field0name5: 5
        field_0_name6: 6
        fieldName7: 7
        FieldName8: 8
        field_Name9: 9
        Field_Name10: 10
        FIELD_NAME11: 11
        FIELD_name12: 12
1003 1004 1005 1006 1007 1008
        __field_name13: 13
        __Field_name14: 14
        field__name15: 15
        field__Name16: 16
        field_name17__: 17
        Field_name18__: 18
1009 1010 1011
      )");
  // Field names can be escaped.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1012
      "FieldNameEscaped", REQUIRED,
1013 1014
      R"({"fieldn\u0061me1": 1})",
      "fieldname1: 1");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1015 1016
  // String ends with escape character.
  ExpectParseFailureForJson(
1017
      "StringEndsWithEscapeChar", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1018
      "{\"optionalString\": \"abc\\");
1019 1020
  // Field names must be quoted (or it's not valid JSON).
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1021
      "FieldNameNotQuoted", RECOMMENDED,
1022 1023 1024
      "{fieldname1: 1}");
  // Trailing comma is not allowed (not valid JSON).
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1025
      "TrailingCommaInAnObject", RECOMMENDED,
1026
      R"({"fieldname1":1,})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1027
  ExpectParseFailureForJson(
1028
      "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1029 1030
      R"({"fieldname1":1 ,})");
  ExpectParseFailureForJson(
1031
      "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1032 1033
      R"({"fieldname1":1 , })");
  ExpectParseFailureForJson(
1034
      "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1035 1036 1037
      R"({
        "fieldname1":1,
      })");
1038 1039
  // JSON doesn't support comments.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1040
      "JsonWithComments", RECOMMENDED,
1041 1042 1043 1044
      R"({
        // This is a comment.
        "fieldname1": 1
      })");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1045 1046
  // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
  RunValidJsonTest(
1047
      "OneLineNoSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1048 1049 1050 1051 1052 1053
      "{\"optionalInt32\":1,\"optionalInt64\":2}",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
1054
      "OneLineWithSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1055 1056 1057 1058 1059 1060
      "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
1061
      "MultilineNoSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1062 1063 1064 1065 1066 1067
      "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
1068
      "MultilineWithSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1069 1070 1071 1072 1073 1074 1075
      "{\n  \"optionalInt32\"  :  1\n  ,\n  \"optionalInt64\"  :  2\n}\n",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  // Missing comma between key/value pairs.
  ExpectParseFailureForJson(
1076
      "MissingCommaOneLine", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1077 1078
      "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
  ExpectParseFailureForJson(
1079
      "MissingCommaMultiline", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1080
      "{\n  \"optionalInt32\": 1\n  \"optionalInt64\": 2\n}");
1081 1082
  // Duplicated field names are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1083
      "FieldNameDuplicate", RECOMMENDED,
1084 1085 1086 1087 1088
      R"({
        "optionalNestedMessage": {a: 1},
        "optionalNestedMessage": {}
      })");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1089
      "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
1090 1091 1092 1093 1094
      R"({
        "optional_nested_message": {a: 1},
        "optionalNestedMessage": {}
      })");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1095
      "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
1096 1097 1098 1099 1100 1101
      R"({
        "optionalNestedMessage": {a: 1},
        "optional_nested_message": {}
      })");
  // Serializers should use lowerCamelCase by default.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1102
      "FieldNameInLowerCamelCase", REQUIRED,
1103 1104 1105
      R"({
        "fieldname1": 1,
        "fieldName2": 2,
1106
        "FieldName3": 3,
1107
        "fieldName4": 4
1108 1109 1110 1111
      })",
      [](const Json::Value& value) {
        return value.isMember("fieldname1") &&
            value.isMember("fieldName2") &&
1112
            value.isMember("FieldName3") &&
1113
            value.isMember("fieldName4");
1114 1115
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1116
      "FieldNameWithNumbers", REQUIRED,
1117 1118 1119 1120 1121 1122 1123 1124 1125
      R"({
        "field0name5": 5,
        "field0Name6": 6
      })",
      [](const Json::Value& value) {
        return value.isMember("field0name5") &&
            value.isMember("field0Name6");
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1126
      "FieldNameWithMixedCases", REQUIRED,
1127 1128
      R"({
        "fieldName7": 7,
Bo Yang's avatar
Bo Yang committed
1129
        "FieldName8": 8,
1130
        "fieldName9": 9,
Bo Yang's avatar
Bo Yang committed
1131 1132 1133
        "FieldName10": 10,
        "FIELDNAME11": 11,
        "FIELDName12": 12
1134 1135 1136
      })",
      [](const Json::Value& value) {
        return value.isMember("fieldName7") &&
Bo Yang's avatar
Bo Yang committed
1137
            value.isMember("FieldName8") &&
1138
            value.isMember("fieldName9") &&
Bo Yang's avatar
Bo Yang committed
1139 1140 1141
            value.isMember("FieldName10") &&
            value.isMember("FIELDNAME11") &&
            value.isMember("FIELDName12");
1142
      });
1143
  RunValidJsonTestWithValidator(
1144
      "FieldNameWithDoubleUnderscores", RECOMMENDED,
1145
      R"({
1146 1147
        "FieldName13": 13,
        "FieldName14": 14,
1148 1149 1150
        "fieldName15": 15,
        "fieldName16": 16,
        "fieldName17": 17,
1151
        "FieldName18": 18
1152 1153
      })",
      [](const Json::Value& value) {
1154 1155
        return value.isMember("FieldName13") &&
            value.isMember("FieldName14") &&
1156 1157 1158
            value.isMember("fieldName15") &&
            value.isMember("fieldName16") &&
            value.isMember("fieldName17") &&
1159
            value.isMember("FieldName18");
1160
      });
1161 1162 1163

  // Integer fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1164
      "Int32FieldMaxValue", REQUIRED,
1165 1166 1167
      R"({"optionalInt32": 2147483647})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1168
      "Int32FieldMinValue", REQUIRED,
1169 1170 1171
      R"({"optionalInt32": -2147483648})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1172
      "Uint32FieldMaxValue", REQUIRED,
1173 1174 1175
      R"({"optionalUint32": 4294967295})",
      "optional_uint32: 4294967295");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1176
      "Int64FieldMaxValue", REQUIRED,
1177 1178 1179
      R"({"optionalInt64": "9223372036854775807"})",
      "optional_int64: 9223372036854775807");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1180
      "Int64FieldMinValue", REQUIRED,
1181 1182 1183
      R"({"optionalInt64": "-9223372036854775808"})",
      "optional_int64: -9223372036854775808");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1184
      "Uint64FieldMaxValue", REQUIRED,
1185 1186
      R"({"optionalUint64": "18446744073709551615"})",
      "optional_uint64: 18446744073709551615");
1187 1188 1189 1190 1191 1192
  // While not the largest Int64, this is the largest
  // Int64 which can be exactly represented within an
  // IEEE-754 64-bit float, which is the expected level
  // of interoperability guarantee. Larger values may
  // work in some implementations, but should not be
  // relied upon.
1193
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1194
      "Int64FieldMaxValueNotQuoted", REQUIRED,
1195 1196
      R"({"optionalInt64": 9223372036854774784})",
      "optional_int64: 9223372036854774784");
1197
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1198
      "Int64FieldMinValueNotQuoted", REQUIRED,
1199 1200
      R"({"optionalInt64": -9223372036854775808})",
      "optional_int64: -9223372036854775808");
1201 1202
  // Largest interoperable Uint64; see comment above
  // for Int64FieldMaxValueNotQuoted.
1203
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1204
      "Uint64FieldMaxValueNotQuoted", REQUIRED,
1205 1206
      R"({"optionalUint64": 18446744073709549568})",
      "optional_uint64: 18446744073709549568");
1207 1208
  // Values can be represented as JSON strings.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1209
      "Int32FieldStringValue", REQUIRED,
1210 1211 1212
      R"({"optionalInt32": "2147483647"})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1213
      "Int32FieldStringValueEscaped", REQUIRED,
1214 1215 1216 1217 1218
      R"({"optionalInt32": "2\u003147483647"})",
      "optional_int32: 2147483647");

  // Parsers reject out-of-bound integer values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1219
      "Int32FieldTooLarge", REQUIRED,
1220 1221
      R"({"optionalInt32": 2147483648})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1222
      "Int32FieldTooSmall", REQUIRED,
1223 1224
      R"({"optionalInt32": -2147483649})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1225
      "Uint32FieldTooLarge", REQUIRED,
1226 1227
      R"({"optionalUint32": 4294967296})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1228
      "Int64FieldTooLarge", REQUIRED,
1229 1230
      R"({"optionalInt64": "9223372036854775808"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1231
      "Int64FieldTooSmall", REQUIRED,
1232 1233
      R"({"optionalInt64": "-9223372036854775809"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1234
      "Uint64FieldTooLarge", REQUIRED,
1235 1236 1237
      R"({"optionalUint64": "18446744073709551616"})");
  // Parser reject non-integer numeric values as well.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1238
      "Int32FieldNotInteger", REQUIRED,
1239 1240
      R"({"optionalInt32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1241
      "Uint32FieldNotInteger", REQUIRED,
1242 1243
      R"({"optionalUint32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1244
      "Int64FieldNotInteger", REQUIRED,
1245 1246
      R"({"optionalInt64": "0.5"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1247
      "Uint64FieldNotInteger", REQUIRED,
1248 1249 1250 1251
      R"({"optionalUint64": "0.5"})");

  // Integers but represented as float values are accepted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1252
      "Int32FieldFloatTrailingZero", REQUIRED,
1253 1254 1255
      R"({"optionalInt32": 100000.000})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1256
      "Int32FieldExponentialFormat", REQUIRED,
1257 1258 1259
      R"({"optionalInt32": 1e5})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1260
      "Int32FieldMaxFloatValue", REQUIRED,
1261 1262 1263
      R"({"optionalInt32": 2.147483647e9})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1264
      "Int32FieldMinFloatValue", REQUIRED,
1265 1266 1267
      R"({"optionalInt32": -2.147483648e9})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1268
      "Uint32FieldMaxFloatValue", REQUIRED,
1269 1270 1271 1272 1273
      R"({"optionalUint32": 4.294967295e9})",
      "optional_uint32: 4294967295");

  // Parser reject non-numeric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1274
      "Int32FieldNotNumber", REQUIRED,
1275 1276
      R"({"optionalInt32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1277
      "Uint32FieldNotNumber", REQUIRED,
1278 1279
      R"({"optionalUint32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1280
      "Int64FieldNotNumber", REQUIRED,
1281 1282
      R"({"optionalInt64": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1283
      "Uint64FieldNotNumber", REQUIRED,
1284 1285 1286
      R"({"optionalUint64": "3x3"})");
  // JSON does not allow "+" on numric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1287
      "Int32FieldPlusSign", REQUIRED,
1288 1289 1290
      R"({"optionalInt32": +1})");
  // JSON doesn't allow leading 0s.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1291
      "Int32FieldLeadingZero", REQUIRED,
1292 1293
      R"({"optionalInt32": 01})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1294
      "Int32FieldNegativeWithLeadingZero", REQUIRED,
1295 1296
      R"({"optionalInt32": -01})");
  // String values must follow the same syntax rule. Specifically leading
1297
  // or trailing spaces are not allowed.
1298
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1299
      "Int32FieldLeadingSpace", REQUIRED,
1300 1301
      R"({"optionalInt32": " 1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1302
      "Int32FieldTrailingSpace", REQUIRED,
1303 1304 1305 1306
      R"({"optionalInt32": "1 "})");

  // 64-bit values are serialized as strings.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1307
      "Int64FieldBeString", RECOMMENDED,
1308 1309 1310 1311 1312 1313
      R"({"optionalInt64": 1})",
      [](const Json::Value& value) {
        return value["optionalInt64"].type() == Json::stringValue &&
            value["optionalInt64"].asString() == "1";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1314
      "Uint64FieldBeString", RECOMMENDED,
1315 1316 1317 1318 1319 1320 1321 1322
      R"({"optionalUint64": 1})",
      [](const Json::Value& value) {
        return value["optionalUint64"].type() == Json::stringValue &&
            value["optionalUint64"].asString() == "1";
      });

  // Bool fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1323
      "BoolFieldTrue", REQUIRED,
1324 1325 1326
      R"({"optionalBool":true})",
      "optional_bool: true");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1327
      "BoolFieldFalse", REQUIRED,
1328 1329 1330 1331 1332
      R"({"optionalBool":false})",
      "optional_bool: false");

  // Other forms are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1333
      "BoolFieldIntegerZero", RECOMMENDED,
1334 1335
      R"({"optionalBool":0})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1336
      "BoolFieldIntegerOne", RECOMMENDED,
1337 1338
      R"({"optionalBool":1})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1339
      "BoolFieldCamelCaseTrue", RECOMMENDED,
1340 1341
      R"({"optionalBool":True})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1342
      "BoolFieldCamelCaseFalse", RECOMMENDED,
1343 1344
      R"({"optionalBool":False})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1345
      "BoolFieldAllCapitalTrue", RECOMMENDED,
1346 1347
      R"({"optionalBool":TRUE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1348
      "BoolFieldAllCapitalFalse", RECOMMENDED,
1349 1350
      R"({"optionalBool":FALSE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1351
      "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1352 1353
      R"({"optionalBool":"true"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1354
      "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1355 1356 1357 1358
      R"({"optionalBool":"false"})");

  // Float fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1359
      "FloatFieldMinPositiveValue", REQUIRED,
1360 1361 1362
      R"({"optionalFloat": 1.175494e-38})",
      "optional_float: 1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1363
      "FloatFieldMaxNegativeValue", REQUIRED,
1364 1365 1366
      R"({"optionalFloat": -1.175494e-38})",
      "optional_float: -1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1367
      "FloatFieldMaxPositiveValue", REQUIRED,
1368 1369 1370
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1371
      "FloatFieldMinNegativeValue", REQUIRED,
1372 1373 1374 1375
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1376
      "FloatFieldQuotedValue", REQUIRED,
1377 1378 1379 1380
      R"({"optionalFloat": "1"})",
      "optional_float: 1");
  // Special values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1381
      "FloatFieldNan", REQUIRED,
1382 1383 1384
      R"({"optionalFloat": "NaN"})",
      "optional_float: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1385
      "FloatFieldInfinity", REQUIRED,
1386 1387 1388
      R"({"optionalFloat": "Infinity"})",
      "optional_float: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1389
      "FloatFieldNegativeInfinity", REQUIRED,
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
      R"({"optionalFloat": "-Infinity"})",
      "optional_float: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
    TestAllTypes message;
    // IEEE floating-point standard 32-bit quiet NaN:
    //   0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
    message.set_optional_float(
        WireFormatLite::DecodeFloat(0x7FA12345));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1400
        "FloatFieldNormalizeQuietNan", REQUIRED, message,
Yilun Chong's avatar
Yilun Chong committed
1401
        "optional_float: nan", true);
1402 1403 1404 1405 1406
    // IEEE floating-point standard 64-bit signaling NaN:
    //   1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx
    message.set_optional_float(
        WireFormatLite::DecodeFloat(0xFFB54321));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1407
        "FloatFieldNormalizeSignalingNan", REQUIRED, message,
Yilun Chong's avatar
Yilun Chong committed
1408
        "optional_float: nan", true);
1409
  }
1410

1411 1412
  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1413
      "FloatFieldNanNotQuoted", RECOMMENDED,
1414 1415
      R"({"optionalFloat": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1416
      "FloatFieldInfinityNotQuoted", RECOMMENDED,
1417 1418
      R"({"optionalFloat": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1419
      "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1420 1421 1422
      R"({"optionalFloat": -Infinity})");
  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1423
      "FloatFieldTooSmall", REQUIRED,
1424 1425
      R"({"optionalFloat": -3.502823e+38})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1426
      "FloatFieldTooLarge", REQUIRED,
1427 1428 1429 1430
      R"({"optionalFloat": 3.502823e+38})");

  // Double fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1431
      "DoubleFieldMinPositiveValue", REQUIRED,
1432 1433 1434
      R"({"optionalDouble": 2.22507e-308})",
      "optional_double: 2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1435
      "DoubleFieldMaxNegativeValue", REQUIRED,
1436 1437 1438
      R"({"optionalDouble": -2.22507e-308})",
      "optional_double: -2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1439
      "DoubleFieldMaxPositiveValue", REQUIRED,
1440 1441 1442
      R"({"optionalDouble": 1.79769e+308})",
      "optional_double: 1.79769e+308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1443
      "DoubleFieldMinNegativeValue", REQUIRED,
1444 1445 1446 1447
      R"({"optionalDouble": -1.79769e+308})",
      "optional_double: -1.79769e+308");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1448
      "DoubleFieldQuotedValue", REQUIRED,
1449 1450 1451 1452
      R"({"optionalDouble": "1"})",
      "optional_double: 1");
  // Speical values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1453
      "DoubleFieldNan", REQUIRED,
1454 1455 1456
      R"({"optionalDouble": "NaN"})",
      "optional_double: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1457
      "DoubleFieldInfinity", REQUIRED,
1458 1459 1460
      R"({"optionalDouble": "Infinity"})",
      "optional_double: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1461
      "DoubleFieldNegativeInfinity", REQUIRED,
1462 1463 1464 1465 1466 1467 1468 1469
      R"({"optionalDouble": "-Infinity"})",
      "optional_double: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
    TestAllTypes message;
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1470
        "DoubleFieldNormalizeQuietNan", REQUIRED, message,
Yilun Chong's avatar
Yilun Chong committed
1471
        "optional_double: nan", true);
1472 1473 1474
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1475
        "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
Yilun Chong's avatar
Yilun Chong committed
1476
        "optional_double: nan", true);
1477 1478 1479 1480
  }

  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1481
      "DoubleFieldNanNotQuoted", RECOMMENDED,
1482 1483
      R"({"optionalDouble": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1484
      "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1485 1486
      R"({"optionalDouble": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1487
      "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1488 1489 1490 1491
      R"({"optionalDouble": -Infinity})");

  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1492
      "DoubleFieldTooSmall", REQUIRED,
1493 1494
      R"({"optionalDouble": -1.89769e+308})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1495
      "DoubleFieldTooLarge", REQUIRED,
1496 1497 1498 1499
      R"({"optionalDouble": +1.89769e+308})");

  // Enum fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1500
      "EnumField", REQUIRED,
1501 1502 1503 1504
      R"({"optionalNestedEnum": "FOO"})",
      "optional_nested_enum: FOO");
  // Enum values must be represented as strings.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1505
      "EnumFieldNotQuoted", REQUIRED,
1506 1507 1508
      R"({"optionalNestedEnum": FOO})");
  // Numeric values are allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1509
      "EnumFieldNumericValueZero", REQUIRED,
1510 1511 1512
      R"({"optionalNestedEnum": 0})",
      "optional_nested_enum: FOO");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1513
      "EnumFieldNumericValueNonZero", REQUIRED,
1514 1515 1516 1517
      R"({"optionalNestedEnum": 1})",
      "optional_nested_enum: BAR");
  // Unknown enum values are represented as numeric values.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1518
      "EnumFieldUnknownValue", REQUIRED,
1519 1520 1521 1522 1523 1524 1525 1526
      R"({"optionalNestedEnum": 123})",
      [](const Json::Value& value) {
        return value["optionalNestedEnum"].type() == Json::intValue &&
            value["optionalNestedEnum"].asInt() == 123;
      });

  // String fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1527
      "StringField", REQUIRED,
1528 1529 1530
      R"({"optionalString": "Hello world!"})",
      "optional_string: \"Hello world!\"");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1531
      "StringFieldUnicode", REQUIRED,
1532 1533 1534 1535
      // Google in Chinese.
      R"({"optionalString": "谷歌"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1536
      "StringFieldEscape", REQUIRED,
1537 1538 1539
      R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
      R"(optional_string: "\"\\/\b\f\n\r\t")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1540
      "StringFieldUnicodeEscape", REQUIRED,
1541 1542 1543
      R"({"optionalString": "\u8C37\u6B4C"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1544
      "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
1545 1546 1547
      R"({"optionalString": "\u8c37\u6b4c"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1548
      "StringFieldSurrogatePair", REQUIRED,
1549 1550 1551 1552 1553 1554
      // The character is an emoji: grinning face with smiling eyes. 😁
      R"({"optionalString": "\uD83D\uDE01"})",
      R"(optional_string: "\xF0\x9F\x98\x81")");

  // Unicode escapes must start with "\u" (lowercase u).
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1555
      "StringFieldUppercaseEscapeLetter", RECOMMENDED,
1556 1557
      R"({"optionalString": "\U8C37\U6b4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1558
      "StringFieldInvalidEscape", RECOMMENDED,
1559 1560
      R"({"optionalString": "\uXXXX\u6B4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1561
      "StringFieldUnterminatedEscape", RECOMMENDED,
1562 1563
      R"({"optionalString": "\u8C3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1564
      "StringFieldUnpairedHighSurrogate", RECOMMENDED,
1565 1566
      R"({"optionalString": "\uD800"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1567
      "StringFieldUnpairedLowSurrogate", RECOMMENDED,
1568 1569
      R"({"optionalString": "\uDC00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1570
      "StringFieldSurrogateInWrongOrder", RECOMMENDED,
1571 1572
      R"({"optionalString": "\uDE01\uD83D"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1573
      "StringFieldNotAString", REQUIRED,
1574 1575 1576 1577
      R"({"optionalString": 12345})");

  // Bytes fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1578
      "BytesField", REQUIRED,
1579 1580 1581
      R"({"optionalBytes": "AQI="})",
      R"(optional_bytes: "\x01\x02")");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1582
      "BytesFieldInvalidBase64Characters", REQUIRED,
1583 1584 1585 1586
      R"({"optionalBytes": "-_=="})");

  // Message fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1587
      "MessageField", REQUIRED,
1588 1589 1590 1591 1592
      R"({"optionalNestedMessage": {"a": 1234}})",
      "optional_nested_message: {a: 1234}");

  // Oneof fields.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1593
      "OneofFieldDuplicate", REQUIRED,
1594
      R"({"oneofUint32": 1, "oneofString": "test"})");
1595 1596 1597 1598
  // Ensure zero values for oneof make it out/backs.
  {
    TestAllTypes message;
    message.set_oneof_uint32(0);
1599
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1600
        "OneofZeroUint32", RECOMMENDED, message, "oneof_uint32: 0", true);
1601
    message.mutable_oneof_nested_message()->set_a(0);
1602
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1603
        "OneofZeroMessage", RECOMMENDED, message, "oneof_nested_message: {}", true);
1604
    message.set_oneof_string("");
1605
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1606
        "OneofZeroString", RECOMMENDED, message, "oneof_string: \"\"", true);
1607
    message.set_oneof_bytes("");
1608
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1609
        "OneofZeroBytes", RECOMMENDED, message, "oneof_bytes: \"\"", true);
1610
    message.set_oneof_bool(false);
1611
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1612
        "OneofZeroBool", RECOMMENDED, message, "oneof_bool: false", true);
1613
    message.set_oneof_uint64(0);
1614
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1615
        "OneofZeroUint64", RECOMMENDED, message, "oneof_uint64: 0", true);
1616
    message.set_oneof_float(0.0f);
1617
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1618
        "OneofZeroFloat", RECOMMENDED, message, "oneof_float: 0", true);
1619
    message.set_oneof_double(0.0);
1620
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1621
        "OneofZeroDouble", RECOMMENDED, message, "oneof_double: 0", true);
1622
    message.set_oneof_enum(TestAllTypes::FOO);
1623
    RunValidProtobufTestWithMessage(
Yilun Chong's avatar
Yilun Chong committed
1624
        "OneofZeroEnum", RECOMMENDED, message, "oneof_enum: FOO", true);
1625 1626
  }
  RunValidJsonTest(
1627
      "OneofZeroUint32", RECOMMENDED,
1628 1629
      R"({"oneofUint32": 0})", "oneof_uint32: 0");
  RunValidJsonTest(
1630
      "OneofZeroMessage", RECOMMENDED,
1631 1632
      R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  RunValidJsonTest(
1633
      "OneofZeroString", RECOMMENDED,
1634 1635
      R"({"oneofString": ""})", "oneof_string: \"\"");
  RunValidJsonTest(
1636
      "OneofZeroBytes", RECOMMENDED,
1637
      R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
1638
  RunValidJsonTest(
1639
      "OneofZeroBool", RECOMMENDED,
1640 1641
      R"({"oneofBool": false})", "oneof_bool: false");
  RunValidJsonTest(
1642
      "OneofZeroUint64", RECOMMENDED,
1643 1644
      R"({"oneofUint64": 0})", "oneof_uint64: 0");
  RunValidJsonTest(
1645
      "OneofZeroFloat", RECOMMENDED,
1646 1647
      R"({"oneofFloat": 0.0})", "oneof_float: 0");
  RunValidJsonTest(
1648
      "OneofZeroDouble", RECOMMENDED,
1649 1650
      R"({"oneofDouble": 0.0})", "oneof_double: 0");
  RunValidJsonTest(
1651
      "OneofZeroEnum", RECOMMENDED,
1652
      R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
1653 1654 1655

  // Repeated fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1656
      "PrimitiveRepeatedField", REQUIRED,
1657 1658 1659
      R"({"repeatedInt32": [1, 2, 3, 4]})",
      "repeated_int32: [1, 2, 3, 4]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1660
      "EnumRepeatedField", REQUIRED,
1661 1662 1663
      R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
      "repeated_nested_enum: [FOO, BAR, BAZ]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1664
      "StringRepeatedField", REQUIRED,
1665 1666 1667
      R"({"repeatedString": ["Hello", "world"]})",
      R"(repeated_string: ["Hello", "world"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1668
      "BytesRepeatedField", REQUIRED,
1669 1670 1671
      R"({"repeatedBytes": ["AAEC", "AQI="]})",
      R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1672
      "MessageRepeatedField", REQUIRED,
1673 1674 1675 1676 1677 1678
      R"({"repeatedNestedMessage": [{"a": 1234}, {"a": 5678}]})",
      "repeated_nested_message: {a: 1234}"
      "repeated_nested_message: {a: 5678}");

  // Repeated field elements are of incorrect type.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1679
      "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
1680 1681
      R"({"repeatedInt32": [1, false, 3, 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1682
      "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
1683 1684
      R"({"repeatedInt32": [1, 2, "name", 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1685
      "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
1686 1687
      R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1688
      "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
1689 1690
      R"({"repeatedString": ["1", 2, "3", "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1691
      "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
1692 1693
      R"({"repeatedString": ["1", "2", false, "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1694
      "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
1695 1696
      R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1697
      "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
1698 1699
      R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1700
      "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
1701 1702
      R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1703
      "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
1704 1705 1706
      R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  // Trailing comma in the repeated field is not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1707
      "RepeatedFieldTrailingComma", RECOMMENDED,
1708
      R"({"repeatedInt32": [1, 2, 3, 4,]})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1709
  ExpectParseFailureForJson(
1710
      "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1711 1712
      "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  ExpectParseFailureForJson(
1713
      "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1714 1715
      "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  ExpectParseFailureForJson(
1716
      "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1717
      "{\"repeatedInt32\": [\n  1,\n  2,\n  3,\n  4,\n]}");
1718 1719 1720

  // Map fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1721
      "Int32MapField", REQUIRED,
1722 1723 1724 1725
      R"({"mapInt32Int32": {"1": 2, "3": 4}})",
      "map_int32_int32: {key: 1 value: 2}"
      "map_int32_int32: {key: 3 value: 4}");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1726
      "Int32MapFieldKeyNotQuoted", RECOMMENDED,
1727 1728
      R"({"mapInt32Int32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1729
      "Uint32MapField", REQUIRED,
1730 1731 1732 1733
      R"({"mapUint32Uint32": {"1": 2, "3": 4}})",
      "map_uint32_uint32: {key: 1 value: 2}"
      "map_uint32_uint32: {key: 3 value: 4}");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1734
      "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
1735 1736
      R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1737
      "Int64MapField", REQUIRED,
1738 1739 1740 1741
      R"({"mapInt64Int64": {"1": 2, "3": 4}})",
      "map_int64_int64: {key: 1 value: 2}"
      "map_int64_int64: {key: 3 value: 4}");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1742
      "Int64MapFieldKeyNotQuoted", RECOMMENDED,
1743 1744
      R"({"mapInt64Int64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1745
      "Uint64MapField", REQUIRED,
1746 1747 1748 1749
      R"({"mapUint64Uint64": {"1": 2, "3": 4}})",
      "map_uint64_uint64: {key: 1 value: 2}"
      "map_uint64_uint64: {key: 3 value: 4}");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1750
      "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
1751 1752
      R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1753
      "BoolMapField", REQUIRED,
1754 1755 1756 1757
      R"({"mapBoolBool": {"true": true, "false": false}})",
      "map_bool_bool: {key: true value: true}"
      "map_bool_bool: {key: false value: false}");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1758
      "BoolMapFieldKeyNotQuoted", RECOMMENDED,
1759 1760
      R"({"mapBoolBool": {true: true, false: false}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1761
      "MessageMapField", REQUIRED,
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
      R"({
        "mapStringNestedMessage": {
          "hello": {"a": 1234},
          "world": {"a": 5678}
        }
      })",
      R"(
        map_string_nested_message: {
          key: "hello"
          value: {a: 1234}
        }
        map_string_nested_message: {
          key: "world"
          value: {a: 5678}
        }
      )");
  // Since Map keys are represented as JSON strings, escaping should be allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1780
      "Int32MapEscapedKey", REQUIRED,
1781 1782 1783
      R"({"mapInt32Int32": {"\u0031": 2}})",
      "map_int32_int32: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1784
      "Int64MapEscapedKey", REQUIRED,
1785 1786 1787
      R"({"mapInt64Int64": {"\u0031": 2}})",
      "map_int64_int64: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1788
      "BoolMapEscapedKey", REQUIRED,
1789 1790 1791 1792 1793
      R"({"mapBoolBool": {"tr\u0075e": true}})",
      "map_bool_bool: {key: true value: true}");

  // "null" is accepted for all fields types.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1794
      "AllFieldAcceptNull", REQUIRED,
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
      R"({
        "optionalInt32": null,
        "optionalInt64": null,
        "optionalUint32": null,
        "optionalUint64": null,
        "optionalBool": null,
        "optionalString": null,
        "optionalBytes": null,
        "optionalNestedEnum": null,
        "optionalNestedMessage": null,
        "repeatedInt32": null,
        "repeatedInt64": null,
        "repeatedUint32": null,
        "repeatedUint64": null,
        "repeatedBool": null,
        "repeatedString": null,
        "repeatedBytes": null,
        "repeatedNestedEnum": null,
        "repeatedNestedMessage": null,
        "mapInt32Int32": null,
        "mapBoolBool": null,
        "mapStringNestedMessage": null
      })",
      "");

  // Repeated field elements cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1822
      "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
1823 1824
      R"({"repeatedInt32": [1, null, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1825
      "RepeatedFieldMessageElementIsNull", RECOMMENDED,
1826 1827 1828
      R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  // Map field keys cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1829
      "MapFieldKeyIsNull", RECOMMENDED,
1830 1831 1832
      R"({"mapInt32Int32": {null: 1}})");
  // Map field values cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1833
      "MapFieldValueIsNull", RECOMMENDED,
1834 1835
      R"({"mapInt32Int32": {"0": null}})");

Thomas Van Lenten's avatar
Thomas Van Lenten committed
1836 1837 1838
  // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  // quotes.
  ExpectParseFailureForJson(
1839
      "StringFieldSingleQuoteKey", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1840 1841
      R"({'optionalString': "Hello world!"})");
  ExpectParseFailureForJson(
1842
      "StringFieldSingleQuoteValue", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1843 1844
      R"({"optionalString": 'Hello world!'})");
  ExpectParseFailureForJson(
1845
      "StringFieldSingleQuoteBoth", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1846 1847
      R"({'optionalString': 'Hello world!'})");

1848 1849
  // Wrapper types.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1850
      "OptionalBoolWrapper", REQUIRED,
1851 1852 1853
      R"({"optionalBoolWrapper": false})",
      "optional_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1854
      "OptionalInt32Wrapper", REQUIRED,
1855 1856 1857
      R"({"optionalInt32Wrapper": 0})",
      "optional_int32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1858
      "OptionalUint32Wrapper", REQUIRED,
1859 1860 1861
      R"({"optionalUint32Wrapper": 0})",
      "optional_uint32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1862
      "OptionalInt64Wrapper", REQUIRED,
1863 1864 1865
      R"({"optionalInt64Wrapper": 0})",
      "optional_int64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1866
      "OptionalUint64Wrapper", REQUIRED,
1867 1868 1869
      R"({"optionalUint64Wrapper": 0})",
      "optional_uint64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1870
      "OptionalFloatWrapper", REQUIRED,
1871 1872 1873
      R"({"optionalFloatWrapper": 0})",
      "optional_float_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1874
      "OptionalDoubleWrapper", REQUIRED,
1875 1876 1877
      R"({"optionalDoubleWrapper": 0})",
      "optional_double_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1878
      "OptionalStringWrapper", REQUIRED,
1879 1880 1881
      R"({"optionalStringWrapper": ""})",
      R"(optional_string_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1882
      "OptionalBytesWrapper", REQUIRED,
1883 1884 1885
      R"({"optionalBytesWrapper": ""})",
      R"(optional_bytes_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1886
      "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
      R"({
        "optionalBoolWrapper": true,
        "optionalInt32Wrapper": 1,
        "optionalUint32Wrapper": 1,
        "optionalInt64Wrapper": "1",
        "optionalUint64Wrapper": "1",
        "optionalFloatWrapper": 1,
        "optionalDoubleWrapper": 1,
        "optionalStringWrapper": "1",
        "optionalBytesWrapper": "AQI="
      })",
      R"(
        optional_bool_wrapper: {value: true}
        optional_int32_wrapper: {value: 1}
        optional_uint32_wrapper: {value: 1}
        optional_int64_wrapper: {value: 1}
        optional_uint64_wrapper: {value: 1}
        optional_float_wrapper: {value: 1}
        optional_double_wrapper: {value: 1}
        optional_string_wrapper: {value: "1"}
        optional_bytes_wrapper: {value: "\x01\x02"}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1910
      "RepeatedBoolWrapper", REQUIRED,
1911 1912 1913 1914
      R"({"repeatedBoolWrapper": [true, false]})",
      "repeated_bool_wrapper: {value: true}"
      "repeated_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1915
      "RepeatedInt32Wrapper", REQUIRED,
1916 1917 1918 1919
      R"({"repeatedInt32Wrapper": [0, 1]})",
      "repeated_int32_wrapper: {value: 0}"
      "repeated_int32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1920
      "RepeatedUint32Wrapper", REQUIRED,
1921 1922 1923 1924
      R"({"repeatedUint32Wrapper": [0, 1]})",
      "repeated_uint32_wrapper: {value: 0}"
      "repeated_uint32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1925
      "RepeatedInt64Wrapper", REQUIRED,
1926 1927 1928 1929
      R"({"repeatedInt64Wrapper": [0, 1]})",
      "repeated_int64_wrapper: {value: 0}"
      "repeated_int64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1930
      "RepeatedUint64Wrapper", REQUIRED,
1931 1932 1933 1934
      R"({"repeatedUint64Wrapper": [0, 1]})",
      "repeated_uint64_wrapper: {value: 0}"
      "repeated_uint64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1935
      "RepeatedFloatWrapper", REQUIRED,
1936 1937 1938 1939
      R"({"repeatedFloatWrapper": [0, 1]})",
      "repeated_float_wrapper: {value: 0}"
      "repeated_float_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1940
      "RepeatedDoubleWrapper", REQUIRED,
1941 1942 1943 1944
      R"({"repeatedDoubleWrapper": [0, 1]})",
      "repeated_double_wrapper: {value: 0}"
      "repeated_double_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1945
      "RepeatedStringWrapper", REQUIRED,
1946 1947 1948 1949 1950 1951
      R"({"repeatedStringWrapper": ["", "AQI="]})",
      R"(
        repeated_string_wrapper: {value: ""}
        repeated_string_wrapper: {value: "AQI="}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1952
      "RepeatedBytesWrapper", REQUIRED,
1953 1954 1955 1956 1957 1958
      R"({"repeatedBytesWrapper": ["", "AQI="]})",
      R"(
        repeated_bytes_wrapper: {value: ""}
        repeated_bytes_wrapper: {value: "\x01\x02"}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1959
      "WrapperTypesWithNullValue", REQUIRED,
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
      R"({
        "optionalBoolWrapper": null,
        "optionalInt32Wrapper": null,
        "optionalUint32Wrapper": null,
        "optionalInt64Wrapper": null,
        "optionalUint64Wrapper": null,
        "optionalFloatWrapper": null,
        "optionalDoubleWrapper": null,
        "optionalStringWrapper": null,
        "optionalBytesWrapper": null,
        "repeatedBoolWrapper": null,
        "repeatedInt32Wrapper": null,
        "repeatedUint32Wrapper": null,
        "repeatedInt64Wrapper": null,
        "repeatedUint64Wrapper": null,
        "repeatedFloatWrapper": null,
        "repeatedDoubleWrapper": null,
        "repeatedStringWrapper": null,
        "repeatedBytesWrapper": null
      })",
      "");

  // Duration
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1984
      "DurationMinValue", REQUIRED,
1985 1986 1987
      R"({"optionalDuration": "-315576000000.999999999s"})",
      "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1988
      "DurationMaxValue", REQUIRED,
1989 1990 1991
      R"({"optionalDuration": "315576000000.999999999s"})",
      "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1992
      "DurationRepeatedValue", REQUIRED,
1993 1994 1995 1996 1997
      R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
      "repeated_duration: {seconds: 1 nanos: 500000000}"
      "repeated_duration: {seconds: -1 nanos: -500000000}");

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1998
      "DurationMissingS", REQUIRED,
1999 2000
      R"({"optionalDuration": "1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2001
      "DurationJsonInputTooSmall", REQUIRED,
2002 2003
      R"({"optionalDuration": "-315576000001.000000000s"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2004
      "DurationJsonInputTooLarge", REQUIRED,
2005 2006
      R"({"optionalDuration": "315576000001.000000000s"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2007
      "DurationProtoInputTooSmall", REQUIRED,
2008 2009
      "optional_duration: {seconds: -315576000001 nanos: 0}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2010
      "DurationProtoInputTooLarge", REQUIRED,
2011 2012 2013
      "optional_duration: {seconds: 315576000001 nanos: 0}");

  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2014
      "DurationHasZeroFractionalDigit", RECOMMENDED,
2015 2016 2017 2018 2019
      R"({"optionalDuration": "1.000000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2020
      "DurationHas3FractionalDigits", RECOMMENDED,
2021 2022 2023 2024 2025
      R"({"optionalDuration": "1.010000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2026
      "DurationHas6FractionalDigits", RECOMMENDED,
2027 2028 2029 2030 2031
      R"({"optionalDuration": "1.000010000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2032
      "DurationHas9FractionalDigits", RECOMMENDED,
2033 2034 2035 2036 2037 2038 2039
      R"({"optionalDuration": "1.000000010s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000000010s";
      });

  // Timestamp
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2040
      "TimestampMinValue", REQUIRED,
2041 2042 2043
      R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
      "optional_timestamp: {seconds: -62135596800}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2044
      "TimestampMaxValue", REQUIRED,
2045 2046 2047
      R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
      "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2048
      "TimestampRepeatedValue", REQUIRED,
2049 2050 2051 2052 2053 2054 2055 2056 2057
      R"({
        "repeatedTimestamp": [
          "0001-01-01T00:00:00Z",
          "9999-12-31T23:59:59.999999999Z"
        ]
      })",
      "repeated_timestamp: {seconds: -62135596800}"
      "repeated_timestamp: {seconds: 253402300799 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2058
      "TimestampWithPositiveOffset", REQUIRED,
2059 2060 2061
      R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
      "optional_timestamp: {seconds: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2062
      "TimestampWithNegativeOffset", REQUIRED,
2063 2064 2065 2066
      R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
      "optional_timestamp: {seconds: 0}");

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2067
      "TimestampJsonInputTooSmall", REQUIRED,
2068 2069
      R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2070
      "TimestampJsonInputTooLarge", REQUIRED,
2071 2072
      R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2073
      "TimestampJsonInputMissingZ", REQUIRED,
2074 2075
      R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2076
      "TimestampJsonInputMissingT", REQUIRED,
2077 2078
      R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2079
      "TimestampJsonInputLowercaseZ", REQUIRED,
2080 2081
      R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2082
      "TimestampJsonInputLowercaseT", REQUIRED,
2083 2084
      R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2085
      "TimestampProtoInputTooSmall", REQUIRED,
2086 2087
      "optional_timestamp: {seconds: -62135596801}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2088
      "TimestampProtoInputTooLarge", REQUIRED,
2089 2090
      "optional_timestamp: {seconds: 253402300800}");
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2091
      "TimestampZeroNormalized", RECOMMENDED,
2092 2093 2094 2095 2096 2097
      R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
      [](const Json::Value& value) {
        return value["optionalTimestamp"].asString() ==
            "1970-01-01T00:00:00Z";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2098
      "TimestampHasZeroFractionalDigit", RECOMMENDED,
2099 2100 2101 2102 2103 2104
      R"({"optionalTimestamp": "1970-01-01T00:00:00.000000000Z"})",
      [](const Json::Value& value) {
        return value["optionalTimestamp"].asString() ==
            "1970-01-01T00:00:00Z";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2105
      "TimestampHas3FractionalDigits", RECOMMENDED,
2106 2107 2108 2109 2110 2111
      R"({"optionalTimestamp": "1970-01-01T00:00:00.010000000Z"})",
      [](const Json::Value& value) {
        return value["optionalTimestamp"].asString() ==
            "1970-01-01T00:00:00.010Z";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2112
      "TimestampHas6FractionalDigits", RECOMMENDED,
2113 2114 2115 2116 2117 2118
      R"({"optionalTimestamp": "1970-01-01T00:00:00.000010000Z"})",
      [](const Json::Value& value) {
        return value["optionalTimestamp"].asString() ==
            "1970-01-01T00:00:00.000010Z";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2119
      "TimestampHas9FractionalDigits", RECOMMENDED,
2120 2121 2122 2123 2124 2125 2126 2127
      R"({"optionalTimestamp": "1970-01-01T00:00:00.000000010Z"})",
      [](const Json::Value& value) {
        return value["optionalTimestamp"].asString() ==
            "1970-01-01T00:00:00.000000010Z";
      });

  // FieldMask
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2128
      "FieldMask", REQUIRED,
2129 2130 2131
      R"({"optionalFieldMask": "foo,barBaz"})",
      R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2132
      "FieldMaskInvalidCharacter", RECOMMENDED,
2133 2134
      R"({"optionalFieldMask": "foo,bar_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2135
      "FieldMaskPathsDontRoundTrip", RECOMMENDED,
2136 2137
      R"(optional_field_mask: {paths: "fooBar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2138
      "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
2139 2140
      R"(optional_field_mask: {paths: "foo_3_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2141
      "FieldMaskTooManyUnderscore", RECOMMENDED,
2142 2143 2144 2145
      R"(optional_field_mask: {paths: "foo__bar"})");

  // Struct
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2146
      "Struct", REQUIRED,
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211
      R"({
        "optionalStruct": {
          "nullValue": null,
          "intValue": 1234,
          "boolValue": true,
          "doubleValue": 1234.5678,
          "stringValue": "Hello world!",
          "listValue": [1234, "5678"],
          "objectValue": {
            "value": 0
          }
        }
      })",
      R"(
        optional_struct: {
          fields: {
            key: "nullValue"
            value: {null_value: NULL_VALUE}
          }
          fields: {
            key: "intValue"
            value: {number_value: 1234}
          }
          fields: {
            key: "boolValue"
            value: {bool_value: true}
          }
          fields: {
            key: "doubleValue"
            value: {number_value: 1234.5678}
          }
          fields: {
            key: "stringValue"
            value: {string_value: "Hello world!"}
          }
          fields: {
            key: "listValue"
            value: {
              list_value: {
                values: {
                  number_value: 1234
                }
                values: {
                  string_value: "5678"
                }
              }
            }
          }
          fields: {
            key: "objectValue"
            value: {
              struct_value: {
                fields: {
                  key: "value"
                  value: {
                    number_value: 0
                  }
                }
              }
            }
          }
        }
      )");
  // Value
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2212
      "ValueAcceptInteger", REQUIRED,
2213 2214 2215
      R"({"optionalValue": 1})",
      "optional_value: { number_value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2216
      "ValueAcceptFloat", REQUIRED,
2217 2218 2219
      R"({"optionalValue": 1.5})",
      "optional_value: { number_value: 1.5}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2220
      "ValueAcceptBool", REQUIRED,
2221 2222 2223
      R"({"optionalValue": false})",
      "optional_value: { bool_value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2224
      "ValueAcceptNull", REQUIRED,
2225 2226 2227
      R"({"optionalValue": null})",
      "optional_value: { null_value: NULL_VALUE}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2228
      "ValueAcceptString", REQUIRED,
2229 2230 2231
      R"({"optionalValue": "hello"})",
      R"(optional_value: { string_value: "hello"})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2232
      "ValueAcceptList", REQUIRED,
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246
      R"({"optionalValue": [0, "hello"]})",
      R"(
        optional_value: {
          list_value: {
            values: {
              number_value: 0
            }
            values: {
              string_value: "hello"
            }
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2247
      "ValueAcceptObject", REQUIRED,
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
      R"({"optionalValue": {"value": 1}})",
      R"(
        optional_value: {
          struct_value: {
            fields: {
              key: "value"
              value: {
                number_value: 1
              }
            }
          }
        }
      )");

  // Any
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2264
      "Any", REQUIRED,
2265 2266
      R"({
        "optionalAny": {
2267
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
2268 2269 2270 2271 2272
          "optionalInt32": 12345
        }
      })",
      R"(
        optional_any: {
2273
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
2274 2275 2276 2277 2278
            optional_int32: 12345
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2279
      "AnyNested", REQUIRED,
2280 2281 2282 2283
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Any",
          "value": {
2284
            "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes",
2285 2286 2287 2288 2289 2290 2291
            "optionalInt32": 12345
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Any] {
2292
            [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
2293 2294 2295 2296 2297 2298 2299
              optional_int32: 12345
            }
          }
        }
      )");
  // The special "@type" tag is not required to appear first.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2300
      "AnyUnorderedTypeTag", REQUIRED,
2301 2302 2303
      R"({
        "optionalAny": {
          "optionalInt32": 12345,
2304
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes"
2305 2306 2307 2308
        }
      })",
      R"(
        optional_any: {
2309
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypes] {
2310 2311 2312 2313 2314 2315
            optional_int32: 12345
          }
        }
      )");
  // Well-known types in Any.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2316
      "AnyWithInt32ValueWrapper", REQUIRED,
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Int32Value",
          "value": 12345
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Int32Value] {
            value: 12345
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2331
      "AnyWithDuration", REQUIRED,
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Duration",
          "value": "1.5s"
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Duration] {
            seconds: 1
            nanos: 500000000
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2347
      "AnyWithTimestamp", REQUIRED,
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Timestamp",
          "value": "1970-01-01T00:00:00Z"
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Timestamp] {
            seconds: 0
            nanos: 0
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2363
      "AnyWithFieldMask", REQUIRED,
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.FieldMask",
          "value": "foo,barBaz"
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.FieldMask] {
            paths: ["foo", "bar_baz"]
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2378
      "AnyWithStruct", REQUIRED,
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Struct",
          "value": {
            "foo": 1
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Struct] {
            fields: {
              key: "foo"
              value: {
                number_value: 1
              }
            }
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2400
      "AnyWithValueForJsonObject", REQUIRED,
2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Value",
          "value": {
            "foo": 1
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Value] {
            struct_value: {
              fields: {
                key: "foo"
                value: {
                  number_value: 1
                }
              }
            }
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2424
      "AnyWithValueForInteger", REQUIRED,
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Value",
          "value": 1
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Value] {
            number_value: 1
          }
        }
      )");

  bool ok = true;
2440
  if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
2441
                     "These tests were listed in the failure list, but they "
2442 2443 2444 2445
                     "don't exist.  Remove them from the failure list by "
                     "running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --remove nonexistent_tests.txt")) {
2446 2447
    ok = false;
  }
2448
  if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
2449 2450
                     "These tests failed.  If they can't be fixed right now, "
                     "you can add them to the failure list so the overall "
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
                     "suite can succeed.  Add them to the failure list by "
                     "running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --add failing_tests.txt")) {
    ok = false;
  }
  if (!CheckSetEmpty(unexpected_succeeding_tests_, "succeeding_tests.txt",
                     "These tests succeeded, even though they were listed in "
                     "the failure list.  Remove them from the failure list "
                     "by running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --remove succeeding_tests.txt")) {
2463 2464
    ok = false;
  }
2465

2466
  if (verbose_) {
2467
    CheckSetEmpty(skipped_, "",
2468 2469 2470
                  "These tests were skipped (probably because support for some "
                  "features is not implemented)");
  }
2471 2472 2473 2474 2475 2476 2477 2478

  StringAppendF(&output_,
                "CONFORMANCE SUITE %s: %d successes, %d skipped, "
                "%d expected failures, %d unexpected failures.\n",
                ok ? "PASSED" : "FAILED", successes_, skipped_.size(),
                expected_failures_, unexpected_failing_tests_.size());
  StringAppendF(&output_, "\n");

2479
  output->assign(output_);
2480 2481

  return ok;
2482
}
2483 2484 2485

}  // namespace protobuf
}  // namespace google