conformance_test.cc 76.8 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/stubs/common.h>
38
#include <google/protobuf/stubs/stringprintf.h>
39 40
#include <google/protobuf/text_format.h>
#include <google/protobuf/util/json_util.h>
41
#include <google/protobuf/util/field_comparator.h>
42 43
#include <google/protobuf/util/message_differencer.h>
#include <google/protobuf/util/type_resolver_util.h>
44 45
#include <google/protobuf/wire_format_lite.h>

46
#include "third_party/jsoncpp/json.h"
47

48 49 50
using conformance::ConformanceRequest;
using conformance::ConformanceResponse;
using conformance::TestAllTypes;
51
using conformance::WireFormat;
52 53 54
using google::protobuf::Descriptor;
using google::protobuf::FieldDescriptor;
using google::protobuf::internal::WireFormatLite;
55
using google::protobuf::TextFormat;
56
using google::protobuf::util::DefaultFieldComparator;
57 58 59 60
using google::protobuf::util::JsonToBinaryString;
using google::protobuf::util::MessageDifferencer;
using google::protobuf::util::NewTypeResolverForDescriptorPool;
using google::protobuf::util::Status;
61 62
using std::string;

63
namespace {
64

65 66 67 68 69 70
static const char kTypeUrlPrefix[] = "type.googleapis.com";

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

71 72 73 74 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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
/* 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

size_t vencode64(uint64_t val, char *buf) {
  if (val == 0) { buf[0] = 0; return 1; }
  size_t i = 0;
  while (val) {
    uint8_t byte = val & 0x7fU;
    val >>= 7;
    if (val) byte |= 0x80U;
    buf[i++] = byte;
  }
  return i;
}

string varint(uint64_t x) {
  char buf[VARINT_MAX_LEN];
  size_t len = vencode64(x, buf);
  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); }
string uint32(uint32_t u32) { return fixed32(&u32); }
string uint64(uint64_t u64) { return fixed64(&u64); }
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

150
uint32_t GetFieldNumberForType(FieldDescriptor::Type type, bool repeated) {
151 152 153
  const Descriptor* d = TestAllTypes().GetDescriptor();
  for (int i = 0; i < d->field_count(); i++) {
    const FieldDescriptor* f = d->field(i);
154
    if (f->type() == type && f->is_repeated() == repeated) {
155 156 157 158 159 160 161
      return f->number();
    }
  }
  GOOGLE_LOG(FATAL) << "Couldn't find field with type " << (int)type;
  return 0;
}

162 163 164 165 166 167 168
string UpperCase(string str) {
  for (int i = 0; i < str.size(); i++) {
    str[i] = toupper(str[i]);
  }
  return str;
}

169 170 171 172 173
}  // anonymous namespace

namespace google {
namespace protobuf {

174 175 176 177 178 179 180 181
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);
  }
182 183 184
  successes_++;
}

185
void ConformanceTestSuite::ReportFailure(const string& test_name,
Bo Yang's avatar
Bo Yang committed
186
                                         ConformanceLevel level,
187 188
                                         const ConformanceRequest& request,
                                         const ConformanceResponse& response,
189 190
                                         const char* fmt, ...) {
  if (expected_to_fail_.erase(test_name) == 1) {
191 192 193
    expected_failures_++;
    if (!verbose_)
      return;
Bo Yang's avatar
Bo Yang committed
194 195
  } else if (level == RECOMMENDED && !enforce_recommended_) {
    StringAppendF(&output_, "WARNING, test=%s: ", test_name.c_str());
196
  } else {
197
    StringAppendF(&output_, "ERROR, test=%s: ", test_name.c_str());
198 199
    unexpected_failing_tests_.insert(test_name);
  }
200 201 202 203
  va_list args;
  va_start(args, fmt);
  StringAppendV(&output_, fmt, args);
  va_end(args);
204 205 206 207 208 209 210 211 212 213 214 215 216 217
  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);
218 219
}

Bo Yang's avatar
Bo Yang committed
220 221 222 223 224 225 226 227 228
string ConformanceTestSuite::ConformanceLevelToString(ConformanceLevel level) {
  switch (level) {
    case REQUIRED: return "Required";
    case RECOMMENDED: return "Recommended";
  }
  GOOGLE_LOG(FATAL) << "Unknown value: " << level;
  return "";
}

229 230
void ConformanceTestSuite::RunTest(const string& test_name,
                                   const ConformanceRequest& request,
231
                                   ConformanceResponse* response) {
232 233
  if (test_names_.insert(test_name).second == false) {
    GOOGLE_LOG(FATAL) << "Duplicated test name: " << test_name;
234 235
  }

236 237 238 239
  string serialized_request;
  string serialized_response;
  request.SerializeToString(&serialized_request);

240
  runner_->RunTest(test_name, serialized_request, &serialized_response);
241 242 243 244 245 246 247

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

  if (verbose_) {
248 249
    StringAppendF(&output_, "conformance test: name=%s, request=%s, response=%s\n",
                  test_name.c_str(),
250 251 252 253 254
                  request.ShortDebugString().c_str(),
                  response->ShortDebugString().c_str());
  }
}

255
void ConformanceTestSuite::RunValidInputTest(
Bo Yang's avatar
Bo Yang committed
256 257 258
    const string& test_name, ConformanceLevel level, const string& input,
    WireFormat input_format, const string& equivalent_text_format,
    WireFormat requested_output) {
259 260
  TestAllTypes reference_message;
  GOOGLE_CHECK(
261 262 263
      TextFormat::ParseFromString(equivalent_text_format, &reference_message))
          << "Failed to parse data for test case: " << test_name
          << ", data: " << equivalent_text_format;
264 265 266 267 268 269 270 271 272 273 274 275 276

  ConformanceRequest request;
  ConformanceResponse response;

  switch (input_format) {
    case conformance::PROTOBUF:
      request.set_protobuf_payload(input);
      break;

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

277
    default:
278 279 280 281 282 283 284 285 286 287
      GOOGLE_LOG(FATAL) << "Unspecified input format";
  }

  request.set_requested_output_format(requested_output);

  RunTest(test_name, request, &response);

  TestAllTypes test_message;

  switch (response.result_case()) {
288
    case ConformanceResponse::RESULT_NOT_SET:
289
      ReportFailure(test_name, level, request, response,
290 291 292
                    "Response didn't have any field in the Response.");
      return;

293 294
    case ConformanceResponse::kParseError:
    case ConformanceResponse::kRuntimeError:
295
    case ConformanceResponse::kSerializeError:
296
      ReportFailure(test_name, level, request, response,
297
                    "Failed to parse input or produce output.");
298 299 300 301 302 303 304 305 306
      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
307
            test_name, level, request, response,
308 309 310 311 312 313 314 315
            "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
316
        ReportFailure(test_name, level, request, response,
317 318 319 320
                      "JSON output we received from test was unparseable.");
        return;
      }

321
      if (!test_message.ParseFromString(binary_protobuf)) {
Bo Yang's avatar
Bo Yang committed
322
        ReportFailure(test_name, level, request, response,
323 324 325 326 327
                      "INTERNAL ERROR: internal JSON->protobuf transcode "
                      "yielded unparseable proto.");
        return;
      }

328 329 330 331 332 333
      break;
    }

    case ConformanceResponse::kProtobufPayload: {
      if (requested_output != conformance::PROTOBUF) {
        ReportFailure(
Bo Yang's avatar
Bo Yang committed
334
            test_name, level, request, response,
335 336 337 338 339
            "Test was asked for JSON output but provided protobuf instead.");
        return;
      }

      if (!test_message.ParseFromString(response.protobuf_payload())) {
Bo Yang's avatar
Bo Yang committed
340
        ReportFailure(test_name, level, request, response,
341 342 343 344 345 346
                      "Protobuf output we received from test was unparseable.");
        return;
      }

      break;
    }
347 348 349 350

    default:
      GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
                        << response.result_case();
351 352 353
  }

  MessageDifferencer differencer;
354 355 356
  DefaultFieldComparator field_comparator;
  field_comparator.set_treat_nan_as_equal(true);
  differencer.set_field_comparator(&field_comparator);
357 358 359
  string differences;
  differencer.ReportDifferencesToString(&differences);

360
  if (differencer.Compare(reference_message, test_message)) {
361 362
    ReportSuccess(test_name);
  } else {
Bo Yang's avatar
Bo Yang committed
363
    ReportFailure(test_name, level, request, response,
364 365 366 367 368
                  "Output was not equivalent to reference message: %s.",
                  differences.c_str());
  }
}

369 370
// Expect that this precise protobuf will cause a parse error.
void ConformanceTestSuite::ExpectParseFailureForProto(
Bo Yang's avatar
Bo Yang committed
371
    const string& proto, const string& test_name, ConformanceLevel level) {
372 373 374
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(proto);
Bo Yang's avatar
Bo Yang committed
375 376
  string effective_test_name = ConformanceLevelToString(level) +
      ".ProtobufInput." + test_name;
377 378 379

  // 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.
380
  request.set_requested_output_format(conformance::PROTOBUF);
381

382
  RunTest(effective_test_name, request, &response);
383
  if (response.result_case() == ConformanceResponse::kParseError) {
384
    ReportSuccess(effective_test_name);
385 386
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
387
  } else {
Bo Yang's avatar
Bo Yang committed
388
    ReportFailure(effective_test_name, level, request, response,
389
                  "Should have failed to parse, but didn't.");
390 391 392 393 394 395 396 397
  }
}

// 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.
398
void ConformanceTestSuite::ExpectHardParseFailureForProto(
Bo Yang's avatar
Bo Yang committed
399 400
    const string& proto, const string& test_name, ConformanceLevel level) {
  return ExpectParseFailureForProto(proto, test_name, level);
401
}
402

403
void ConformanceTestSuite::RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
404
    const string& test_name, ConformanceLevel level, const string& input_json,
405
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
406 407 408 409 410 411 412 413
  RunValidInputTest(
      ConformanceLevelToString(level) + ".JsonInput." + test_name +
      ".ProtobufOutput", level, input_json, conformance::JSON,
      equivalent_text_format, conformance::PROTOBUF);
  RunValidInputTest(
      ConformanceLevelToString(level) + ".JsonInput." + test_name +
      ".JsonOutput", level, input_json, conformance::JSON,
      equivalent_text_format, conformance::JSON);
414 415 416
}

void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
417
    const string& test_name, ConformanceLevel level, const TestAllTypes& input,
418
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
419 420 421 422
  RunValidInputTest(
      ConformanceLevelToString(level) + ".ProtobufInput." + test_name +
      ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
      equivalent_text_format, conformance::JSON);
423 424
}

425
void ConformanceTestSuite::RunValidProtobufTest(
426
    const string& test_name, ConformanceLevel level, const TestAllTypes& input,
427
    const string& equivalent_text_format) {
428
  RunValidInputTest("ProtobufInput." + test_name + ".ProtobufOutput", level,
429 430
                    input.SerializeAsString(), conformance::PROTOBUF,
                    equivalent_text_format, conformance::PROTOBUF);
431
  RunValidInputTest("ProtobufInput." + test_name + ".JsonOutput", level,
432 433 434 435
                    input.SerializeAsString(), conformance::PROTOBUF,
                    equivalent_text_format, conformance::JSON);
}

436 437 438 439 440 441
// 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
442
    const string& test_name, ConformanceLevel level, const string& input_json,
443 444 445 446 447 448
    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
449 450
  string effective_test_name = ConformanceLevelToString(level) +
      ".JsonInput." + test_name + ".Validator";
451 452 453

  RunTest(effective_test_name, request, &response);

454 455 456 457 458
  if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
    return;
  }

459
  if (response.result_case() != ConformanceResponse::kJsonPayload) {
Bo Yang's avatar
Bo Yang committed
460
    ReportFailure(effective_test_name, level, request, response,
461 462 463 464 465 466 467
                  "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
468
    ReportFailure(effective_test_name, level, request, response,
469 470 471 472 473
                  "JSON payload cannot be parsed as valid JSON: %s",
                  reader.getFormattedErrorMessages().c_str());
    return;
  }
  if (!validator(value)) {
Bo Yang's avatar
Bo Yang committed
474
    ReportFailure(effective_test_name, level, request, response,
475 476 477 478 479 480 481
                  "JSON payload validation failed.");
    return;
  }
  ReportSuccess(effective_test_name);
}

void ConformanceTestSuite::ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
482
    const string& test_name, ConformanceLevel level, const string& input_json) {
483 484 485
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
Bo Yang's avatar
Bo Yang committed
486 487
  string effective_test_name =
      ConformanceLevelToString(level) + ".JsonInput." + test_name;
488 489 490 491 492 493 494 495

  // 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);
496 497
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
498
  } else {
Bo Yang's avatar
Bo Yang committed
499
    ReportFailure(effective_test_name, level, request, response,
500 501 502 503 504
                  "Should have failed to parse, but didn't.");
  }
}

void ConformanceTestSuite::ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
505
    const string& test_name, ConformanceLevel level, const string& text_format) {
506 507 508 509 510 511 512 513
  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());
Bo Yang's avatar
Bo Yang committed
514 515
  string effective_test_name =
      ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
516 517 518 519 520
  request.set_requested_output_format(conformance::JSON);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kSerializeError) {
    ReportSuccess(effective_test_name);
521 522
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
523
  } else {
Bo Yang's avatar
Bo Yang committed
524
    ReportFailure(effective_test_name, level, request, response,
525 526 527 528
                  "Should have failed to serialize, but didn't.");
  }
}

529
void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
530 531 532 533 534 535 536 537 538 539 540 541
  // 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
  };

  uint32_t fieldnum = GetFieldNumberForType(type, false);
  uint32_t rep_fieldnum = GetFieldNumberForType(type, true);
542 543
  WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
      static_cast<WireFormatLite::FieldType>(type));
544
  const string& incomplete = incompletes[wire_type];
545 546
  const string type_name =
      UpperCase(string(".") + FieldDescriptor::TypeName(type));
547

548 549
  ExpectParseFailureForProto(
      tag(fieldnum, wire_type),
Bo Yang's avatar
Bo Yang committed
550
      "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
551

552 553
  ExpectParseFailureForProto(
      tag(rep_fieldnum, wire_type),
Bo Yang's avatar
Bo Yang committed
554
      "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
555

556 557
  ExpectParseFailureForProto(
      tag(UNKNOWN_FIELD, wire_type),
Bo Yang's avatar
Bo Yang committed
558
      "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
559 560

  ExpectParseFailureForProto(
561
      cat( tag(fieldnum, wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
562
      "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
563 564

  ExpectParseFailureForProto(
565
      cat( tag(rep_fieldnum, wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
566
      "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
567 568

  ExpectParseFailureForProto(
569
      cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
570
      "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
571 572 573

  if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
    ExpectParseFailureForProto(
574
        cat( tag(fieldnum, wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
575 576
        "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
        REQUIRED);
577 578

    ExpectParseFailureForProto(
579
        cat( tag(rep_fieldnum, wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
580 581
        "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
        REQUIRED);
582 583 584

    // EOF in the middle of delimited data for unknown value.
    ExpectParseFailureForProto(
585
        cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
586
        "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED);
587

588
    if (type == FieldDescriptor::TYPE_MESSAGE) {
589 590 591 592 593 594 595
      // Submessage ends in the middle of a value.
      string incomplete_submsg =
          cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
                incompletes[WireFormatLite::WIRETYPE_VARINT] );
      ExpectHardParseFailureForProto(
          cat( tag(fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
               varint(incomplete_submsg.size()),
596
               incomplete_submsg ),
Bo Yang's avatar
Bo Yang committed
597
          "PrematureEofInSubmessageValue" + type_name, REQUIRED);
598
    }
599
  } else if (type != FieldDescriptor::TYPE_GROUP) {
600 601 602 603 604 605
    // Non-delimited, non-group: eligible for packing.

    // Packed region ends in the middle of a value.
    ExpectHardParseFailureForProto(
        cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
             varint(incomplete.size()),
606
             incomplete ),
Bo Yang's avatar
Bo Yang committed
607
        "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
608 609 610 611

    // EOF in the middle of packed region.
    ExpectParseFailureForProto(
        cat( tag(rep_fieldnum, WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
612
             varint(1) ),
Bo Yang's avatar
Bo Yang committed
613
        "PrematureEofInPackedField" + type_name, REQUIRED);
614 615 616
  }
}

617 618 619
void ConformanceTestSuite::SetFailureList(const string& filename,
                                          const vector<string>& failure_list) {
  failure_list_filename_ = filename;
620 621 622 623 624 625
  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,
626 627
                                         const std::string& write_to_file,
                                         const std::string& msg) {
628 629 630 631
  if (set_to_check.empty()) {
    return true;
  } else {
    StringAppendF(&output_, "\n");
632
    StringAppendF(&output_, "%s\n\n", msg.c_str());
633 634
    for (set<string>::const_iterator iter = set_to_check.begin();
         iter != set_to_check.end(); ++iter) {
635
      StringAppendF(&output_, "  %s\n", iter->c_str());
636
    }
637
    StringAppendF(&output_, "\n");
638 639 640 641 642 643 644 645 646 647 648 649 650 651

    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());
      }
    }

652 653 654 655 656
    return false;
  }
}

bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
657 658 659
                                    std::string* output) {
  runner_ = runner;
  successes_ = 0;
660 661
  expected_failures_ = 0;
  skipped_.clear();
662 663 664
  test_names_.clear();
  unexpected_failing_tests_.clear();
  unexpected_succeeding_tests_.clear();
665 666 667 668 669
  type_resolver_.reset(NewTypeResolverForDescriptorPool(
      kTypeUrlPrefix, DescriptorPool::generated_pool()));
  type_url_ = GetTypeUrl(TestAllTypes::descriptor());

  output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
670 671

  for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
672
    if (i == FieldDescriptor::TYPE_GROUP) continue;
673
    TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
674 675
  }

Bo Yang's avatar
Bo Yang committed
676 677
  RunValidJsonTest("HelloWorld", REQUIRED,
                   "{\"optionalString\":\"Hello, World!\"}",
678
                   "optional_string: 'Hello, World!'");
679

680 681
  // NOTE: The spec for JSON support is still being sorted out, these may not
  // all be correct.
682 683
  // Test field name conventions.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
684
      "FieldNameInSnakeCase", REQUIRED,
685 686 687
      R"({
        "fieldname1": 1,
        "fieldName2": 2,
688
        "FieldName3": 3,
689
        "fieldName4": 4
690 691 692 693 694
      })",
      R"(
        fieldname1: 1
        field_name2: 2
        _field_name3: 3
695
        field__name4_: 4
696 697
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
698
      "FieldNameWithNumbers", REQUIRED,
699 700 701 702 703 704 705 706 707
      R"({
        "field0name5": 5,
        "field0Name6": 6
      })",
      R"(
        field0name5: 5
        field_0_name6: 6
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
708
      "FieldNameWithMixedCases", REQUIRED,
709 710
      R"({
        "fieldName7": 7,
Bo Yang's avatar
Bo Yang committed
711
        "FieldName8": 8,
712
        "fieldName9": 9,
Bo Yang's avatar
Bo Yang committed
713 714 715
        "FieldName10": 10,
        "FIELDNAME11": 11,
        "FIELDName12": 12
716 717 718 719 720 721 722 723 724
      })",
      R"(
        fieldName7: 7
        FieldName8: 8
        field_Name9: 9
        Field_Name10: 10
        FIELD_NAME11: 11
        FIELD_name12: 12
      )");
725
  RunValidJsonTest(
726
      "FieldNameWithDoubleUnderscores", RECOMMENDED,
727
      R"({
728 729
        "FieldName13": 13,
        "FieldName14": 14,
730 731 732
        "fieldName15": 15,
        "fieldName16": 16,
        "fieldName17": 17,
733
        "FieldName18": 18
734 735 736 737 738 739 740 741 742
      })",
      R"(
        __field_name13: 13
        __Field_name14: 14
        field__name15: 15
        field__Name16: 16
        field_name17__: 17
        Field_name18__: 18
      )");
743 744
  // Using the original proto field name in JSON is also allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
745
      "OriginalProtoFieldName", REQUIRED,
746 747 748 749
      R"({
        "fieldname1": 1,
        "field_name2": 2,
        "_field_name3": 3,
750
        "field__name4_": 4,
751 752 753 754 755 756 757
        "field0name5": 5,
        "field_0_name6": 6,
        "fieldName7": 7,
        "FieldName8": 8,
        "field_Name9": 9,
        "Field_Name10": 10,
        "FIELD_NAME11": 11,
758 759 760 761 762 763 764
        "FIELD_name12": 12,
        "__field_name13": 13,
        "__Field_name14": 14,
        "field__name15": 15,
        "field__Name16": 16,
        "field_name17__": 17,
        "Field_name18__": 18
765 766 767 768 769
      })",
      R"(
        fieldname1: 1
        field_name2: 2
        _field_name3: 3
770
        field__name4_: 4
771 772 773 774 775 776 777 778
        field0name5: 5
        field_0_name6: 6
        fieldName7: 7
        FieldName8: 8
        field_Name9: 9
        Field_Name10: 10
        FIELD_NAME11: 11
        FIELD_name12: 12
779 780 781 782 783 784
        __field_name13: 13
        __Field_name14: 14
        field__name15: 15
        field__Name16: 16
        field_name17__: 17
        Field_name18__: 18
785 786 787
      )");
  // Field names can be escaped.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
788
      "FieldNameEscaped", REQUIRED,
789 790
      R"({"fieldn\u0061me1": 1})",
      "fieldname1: 1");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
791 792
  // String ends with escape character.
  ExpectParseFailureForJson(
793
      "StringEndsWithEscapeChar", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
794
      "{\"optionalString\": \"abc\\");
795 796
  // Field names must be quoted (or it's not valid JSON).
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
797
      "FieldNameNotQuoted", RECOMMENDED,
798 799 800
      "{fieldname1: 1}");
  // Trailing comma is not allowed (not valid JSON).
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
801
      "TrailingCommaInAnObject", RECOMMENDED,
802
      R"({"fieldname1":1,})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
803
  ExpectParseFailureForJson(
804
      "TrailingCommaInAnObjectWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
805 806
      R"({"fieldname1":1 ,})");
  ExpectParseFailureForJson(
807
      "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
808 809
      R"({"fieldname1":1 , })");
  ExpectParseFailureForJson(
810
      "TrailingCommaInAnObjectWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
811 812 813
      R"({
        "fieldname1":1,
      })");
814 815
  // JSON doesn't support comments.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
816
      "JsonWithComments", RECOMMENDED,
817 818 819 820
      R"({
        // This is a comment.
        "fieldname1": 1
      })");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
821 822
  // JSON spec says whitespace doesn't matter, so try a few spacings to be sure.
  RunValidJsonTest(
823
      "OneLineNoSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
824 825 826 827 828 829
      "{\"optionalInt32\":1,\"optionalInt64\":2}",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
830
      "OneLineWithSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
831 832 833 834 835 836
      "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
837
      "MultilineNoSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
838 839 840 841 842 843
      "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  RunValidJsonTest(
844
      "MultilineWithSpaces", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
845 846 847 848 849 850 851
      "{\n  \"optionalInt32\"  :  1\n  ,\n  \"optionalInt64\"  :  2\n}\n",
      R"(
        optional_int32: 1
        optional_int64: 2
      )");
  // Missing comma between key/value pairs.
  ExpectParseFailureForJson(
852
      "MissingCommaOneLine", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
853 854
      "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }");
  ExpectParseFailureForJson(
855
      "MissingCommaMultiline", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
856
      "{\n  \"optionalInt32\": 1\n  \"optionalInt64\": 2\n}");
857 858
  // Duplicated field names are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
859
      "FieldNameDuplicate", RECOMMENDED,
860 861 862 863 864
      R"({
        "optionalNestedMessage": {a: 1},
        "optionalNestedMessage": {}
      })");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
865
      "FieldNameDuplicateDifferentCasing1", RECOMMENDED,
866 867 868 869 870
      R"({
        "optional_nested_message": {a: 1},
        "optionalNestedMessage": {}
      })");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
871
      "FieldNameDuplicateDifferentCasing2", RECOMMENDED,
872 873 874 875 876 877
      R"({
        "optionalNestedMessage": {a: 1},
        "optional_nested_message": {}
      })");
  // Serializers should use lowerCamelCase by default.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
878
      "FieldNameInLowerCamelCase", REQUIRED,
879 880 881
      R"({
        "fieldname1": 1,
        "fieldName2": 2,
882
        "FieldName3": 3,
883
        "fieldName4": 4
884 885 886 887
      })",
      [](const Json::Value& value) {
        return value.isMember("fieldname1") &&
            value.isMember("fieldName2") &&
888
            value.isMember("FieldName3") &&
889
            value.isMember("fieldName4");
890 891
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
892
      "FieldNameWithNumbers", REQUIRED,
893 894 895 896 897 898 899 900 901
      R"({
        "field0name5": 5,
        "field0Name6": 6
      })",
      [](const Json::Value& value) {
        return value.isMember("field0name5") &&
            value.isMember("field0Name6");
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
902
      "FieldNameWithMixedCases", REQUIRED,
903 904
      R"({
        "fieldName7": 7,
Bo Yang's avatar
Bo Yang committed
905
        "FieldName8": 8,
906
        "fieldName9": 9,
Bo Yang's avatar
Bo Yang committed
907 908 909
        "FieldName10": 10,
        "FIELDNAME11": 11,
        "FIELDName12": 12
910 911 912
      })",
      [](const Json::Value& value) {
        return value.isMember("fieldName7") &&
Bo Yang's avatar
Bo Yang committed
913
            value.isMember("FieldName8") &&
914
            value.isMember("fieldName9") &&
Bo Yang's avatar
Bo Yang committed
915 916 917
            value.isMember("FieldName10") &&
            value.isMember("FIELDNAME11") &&
            value.isMember("FIELDName12");
918
      });
919
  RunValidJsonTestWithValidator(
920
      "FieldNameWithDoubleUnderscores", RECOMMENDED,
921
      R"({
922 923
        "FieldName13": 13,
        "FieldName14": 14,
924 925 926
        "fieldName15": 15,
        "fieldName16": 16,
        "fieldName17": 17,
927
        "FieldName18": 18
928 929
      })",
      [](const Json::Value& value) {
930 931
        return value.isMember("FieldName13") &&
            value.isMember("FieldName14") &&
932 933 934
            value.isMember("fieldName15") &&
            value.isMember("fieldName16") &&
            value.isMember("fieldName17") &&
935
            value.isMember("FieldName18");
936
      });
937 938 939

  // Integer fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
940
      "Int32FieldMaxValue", REQUIRED,
941 942 943
      R"({"optionalInt32": 2147483647})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
944
      "Int32FieldMinValue", REQUIRED,
945 946 947
      R"({"optionalInt32": -2147483648})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
948
      "Uint32FieldMaxValue", REQUIRED,
949 950 951
      R"({"optionalUint32": 4294967295})",
      "optional_uint32: 4294967295");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
952
      "Int64FieldMaxValue", REQUIRED,
953 954 955
      R"({"optionalInt64": "9223372036854775807"})",
      "optional_int64: 9223372036854775807");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
956
      "Int64FieldMinValue", REQUIRED,
957 958 959
      R"({"optionalInt64": "-9223372036854775808"})",
      "optional_int64: -9223372036854775808");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
960
      "Uint64FieldMaxValue", REQUIRED,
961 962
      R"({"optionalUint64": "18446744073709551615"})",
      "optional_uint64: 18446744073709551615");
963 964 965 966 967 968
  // 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.
969
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
970
      "Int64FieldMaxValueNotQuoted", REQUIRED,
971 972
      R"({"optionalInt64": 9223372036854774784})",
      "optional_int64: 9223372036854774784");
973
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
974
      "Int64FieldMinValueNotQuoted", REQUIRED,
975 976
      R"({"optionalInt64": -9223372036854775808})",
      "optional_int64: -9223372036854775808");
977 978
  // Largest interoperable Uint64; see comment above
  // for Int64FieldMaxValueNotQuoted.
979
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
980
      "Uint64FieldMaxValueNotQuoted", REQUIRED,
981 982
      R"({"optionalUint64": 18446744073709549568})",
      "optional_uint64: 18446744073709549568");
983 984
  // Values can be represented as JSON strings.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
985
      "Int32FieldStringValue", REQUIRED,
986 987 988
      R"({"optionalInt32": "2147483647"})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
989
      "Int32FieldStringValueEscaped", REQUIRED,
990 991 992 993 994
      R"({"optionalInt32": "2\u003147483647"})",
      "optional_int32: 2147483647");

  // Parsers reject out-of-bound integer values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
995
      "Int32FieldTooLarge", REQUIRED,
996 997
      R"({"optionalInt32": 2147483648})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
998
      "Int32FieldTooSmall", REQUIRED,
999 1000
      R"({"optionalInt32": -2147483649})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1001
      "Uint32FieldTooLarge", REQUIRED,
1002 1003
      R"({"optionalUint32": 4294967296})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1004
      "Int64FieldTooLarge", REQUIRED,
1005 1006
      R"({"optionalInt64": "9223372036854775808"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1007
      "Int64FieldTooSmall", REQUIRED,
1008 1009
      R"({"optionalInt64": "-9223372036854775809"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1010
      "Uint64FieldTooLarge", REQUIRED,
1011 1012 1013
      R"({"optionalUint64": "18446744073709551616"})");
  // Parser reject non-integer numeric values as well.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1014
      "Int32FieldNotInteger", REQUIRED,
1015 1016
      R"({"optionalInt32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1017
      "Uint32FieldNotInteger", REQUIRED,
1018 1019
      R"({"optionalUint32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1020
      "Int64FieldNotInteger", REQUIRED,
1021 1022
      R"({"optionalInt64": "0.5"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1023
      "Uint64FieldNotInteger", REQUIRED,
1024 1025 1026 1027
      R"({"optionalUint64": "0.5"})");

  // Integers but represented as float values are accepted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1028
      "Int32FieldFloatTrailingZero", REQUIRED,
1029 1030 1031
      R"({"optionalInt32": 100000.000})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1032
      "Int32FieldExponentialFormat", REQUIRED,
1033 1034 1035
      R"({"optionalInt32": 1e5})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1036
      "Int32FieldMaxFloatValue", REQUIRED,
1037 1038 1039
      R"({"optionalInt32": 2.147483647e9})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1040
      "Int32FieldMinFloatValue", REQUIRED,
1041 1042 1043
      R"({"optionalInt32": -2.147483648e9})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1044
      "Uint32FieldMaxFloatValue", REQUIRED,
1045 1046 1047 1048 1049
      R"({"optionalUint32": 4.294967295e9})",
      "optional_uint32: 4294967295");

  // Parser reject non-numeric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1050
      "Int32FieldNotNumber", REQUIRED,
1051 1052
      R"({"optionalInt32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1053
      "Uint32FieldNotNumber", REQUIRED,
1054 1055
      R"({"optionalUint32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1056
      "Int64FieldNotNumber", REQUIRED,
1057 1058
      R"({"optionalInt64": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1059
      "Uint64FieldNotNumber", REQUIRED,
1060 1061 1062
      R"({"optionalUint64": "3x3"})");
  // JSON does not allow "+" on numric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1063
      "Int32FieldPlusSign", REQUIRED,
1064 1065 1066
      R"({"optionalInt32": +1})");
  // JSON doesn't allow leading 0s.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1067
      "Int32FieldLeadingZero", REQUIRED,
1068 1069
      R"({"optionalInt32": 01})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1070
      "Int32FieldNegativeWithLeadingZero", REQUIRED,
1071 1072 1073 1074
      R"({"optionalInt32": -01})");
  // String values must follow the same syntax rule. Specifically leading
  // or traling spaces are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1075
      "Int32FieldLeadingSpace", REQUIRED,
1076 1077
      R"({"optionalInt32": " 1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1078
      "Int32FieldTrailingSpace", REQUIRED,
1079 1080 1081 1082
      R"({"optionalInt32": "1 "})");

  // 64-bit values are serialized as strings.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1083
      "Int64FieldBeString", RECOMMENDED,
1084 1085 1086 1087 1088 1089
      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
1090
      "Uint64FieldBeString", RECOMMENDED,
1091 1092 1093 1094 1095 1096 1097 1098
      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
1099
      "BoolFieldTrue", REQUIRED,
1100 1101 1102
      R"({"optionalBool":true})",
      "optional_bool: true");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1103
      "BoolFieldFalse", REQUIRED,
1104 1105 1106 1107 1108
      R"({"optionalBool":false})",
      "optional_bool: false");

  // Other forms are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1109
      "BoolFieldIntegerZero", RECOMMENDED,
1110 1111
      R"({"optionalBool":0})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1112
      "BoolFieldIntegerOne", RECOMMENDED,
1113 1114
      R"({"optionalBool":1})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1115
      "BoolFieldCamelCaseTrue", RECOMMENDED,
1116 1117
      R"({"optionalBool":True})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1118
      "BoolFieldCamelCaseFalse", RECOMMENDED,
1119 1120
      R"({"optionalBool":False})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1121
      "BoolFieldAllCapitalTrue", RECOMMENDED,
1122 1123
      R"({"optionalBool":TRUE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1124
      "BoolFieldAllCapitalFalse", RECOMMENDED,
1125 1126
      R"({"optionalBool":FALSE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1127
      "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1128 1129
      R"({"optionalBool":"true"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1130
      "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1131 1132 1133 1134
      R"({"optionalBool":"false"})");

  // Float fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1135
      "FloatFieldMinPositiveValue", REQUIRED,
1136 1137 1138
      R"({"optionalFloat": 1.175494e-38})",
      "optional_float: 1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1139
      "FloatFieldMaxNegativeValue", REQUIRED,
1140 1141 1142
      R"({"optionalFloat": -1.175494e-38})",
      "optional_float: -1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1143
      "FloatFieldMaxPositiveValue", REQUIRED,
1144 1145 1146
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1147
      "FloatFieldMinNegativeValue", REQUIRED,
1148 1149 1150 1151
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1152
      "FloatFieldQuotedValue", REQUIRED,
1153 1154 1155 1156
      R"({"optionalFloat": "1"})",
      "optional_float: 1");
  // Special values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1157
      "FloatFieldNan", REQUIRED,
1158 1159 1160
      R"({"optionalFloat": "NaN"})",
      "optional_float: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1161
      "FloatFieldInfinity", REQUIRED,
1162 1163 1164
      R"({"optionalFloat": "Infinity"})",
      "optional_float: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1165
      "FloatFieldNegativeInfinity", REQUIRED,
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
      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
1176
        "FloatFieldNormalizeQuietNan", REQUIRED, message,
1177 1178 1179 1180 1181 1182
        "optional_float: nan");
    // 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
1183
        "FloatFieldNormalizeSignalingNan", REQUIRED, message,
1184 1185
        "optional_float: nan");
  }
1186

1187 1188
  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1189
      "FloatFieldNanNotQuoted", RECOMMENDED,
1190 1191
      R"({"optionalFloat": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1192
      "FloatFieldInfinityNotQuoted", RECOMMENDED,
1193 1194
      R"({"optionalFloat": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1195
      "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1196 1197 1198
      R"({"optionalFloat": -Infinity})");
  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1199
      "FloatFieldTooSmall", REQUIRED,
1200 1201
      R"({"optionalFloat": -3.502823e+38})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1202
      "FloatFieldTooLarge", REQUIRED,
1203 1204 1205 1206
      R"({"optionalFloat": 3.502823e+38})");

  // Double fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1207
      "DoubleFieldMinPositiveValue", REQUIRED,
1208 1209 1210
      R"({"optionalDouble": 2.22507e-308})",
      "optional_double: 2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1211
      "DoubleFieldMaxNegativeValue", REQUIRED,
1212 1213 1214
      R"({"optionalDouble": -2.22507e-308})",
      "optional_double: -2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1215
      "DoubleFieldMaxPositiveValue", REQUIRED,
1216 1217 1218
      R"({"optionalDouble": 1.79769e+308})",
      "optional_double: 1.79769e+308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1219
      "DoubleFieldMinNegativeValue", REQUIRED,
1220 1221 1222 1223
      R"({"optionalDouble": -1.79769e+308})",
      "optional_double: -1.79769e+308");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1224
      "DoubleFieldQuotedValue", REQUIRED,
1225 1226 1227 1228
      R"({"optionalDouble": "1"})",
      "optional_double: 1");
  // Speical values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1229
      "DoubleFieldNan", REQUIRED,
1230 1231 1232
      R"({"optionalDouble": "NaN"})",
      "optional_double: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1233
      "DoubleFieldInfinity", REQUIRED,
1234 1235 1236
      R"({"optionalDouble": "Infinity"})",
      "optional_double: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1237
      "DoubleFieldNegativeInfinity", REQUIRED,
1238 1239 1240 1241 1242 1243 1244 1245
      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
1246
        "DoubleFieldNormalizeQuietNan", REQUIRED, message,
1247 1248 1249 1250
        "optional_double: nan");
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1251
        "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
1252 1253 1254 1255 1256
        "optional_double: nan");
  }

  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1257
      "DoubleFieldNanNotQuoted", RECOMMENDED,
1258 1259
      R"({"optionalDouble": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1260
      "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1261 1262
      R"({"optionalDouble": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1263
      "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1264 1265 1266 1267
      R"({"optionalDouble": -Infinity})");

  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1268
      "DoubleFieldTooSmall", REQUIRED,
1269 1270
      R"({"optionalDouble": -1.89769e+308})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1271
      "DoubleFieldTooLarge", REQUIRED,
1272 1273 1274 1275
      R"({"optionalDouble": +1.89769e+308})");

  // Enum fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1276
      "EnumField", REQUIRED,
1277 1278 1279 1280
      R"({"optionalNestedEnum": "FOO"})",
      "optional_nested_enum: FOO");
  // Enum values must be represented as strings.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1281
      "EnumFieldNotQuoted", REQUIRED,
1282 1283 1284
      R"({"optionalNestedEnum": FOO})");
  // Numeric values are allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1285
      "EnumFieldNumericValueZero", REQUIRED,
1286 1287 1288
      R"({"optionalNestedEnum": 0})",
      "optional_nested_enum: FOO");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1289
      "EnumFieldNumericValueNonZero", REQUIRED,
1290 1291 1292 1293
      R"({"optionalNestedEnum": 1})",
      "optional_nested_enum: BAR");
  // Unknown enum values are represented as numeric values.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1294
      "EnumFieldUnknownValue", REQUIRED,
1295 1296 1297 1298 1299 1300 1301 1302
      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
1303
      "StringField", REQUIRED,
1304 1305 1306
      R"({"optionalString": "Hello world!"})",
      "optional_string: \"Hello world!\"");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1307
      "StringFieldUnicode", REQUIRED,
1308 1309 1310 1311
      // Google in Chinese.
      R"({"optionalString": "谷歌"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1312
      "StringFieldEscape", REQUIRED,
1313 1314 1315
      R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
      R"(optional_string: "\"\\/\b\f\n\r\t")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1316
      "StringFieldUnicodeEscape", REQUIRED,
1317 1318 1319
      R"({"optionalString": "\u8C37\u6B4C"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1320
      "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
1321 1322 1323
      R"({"optionalString": "\u8c37\u6b4c"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1324
      "StringFieldSurrogatePair", REQUIRED,
1325 1326 1327 1328 1329 1330
      // 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
1331
      "StringFieldUppercaseEscapeLetter", RECOMMENDED,
1332 1333
      R"({"optionalString": "\U8C37\U6b4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1334
      "StringFieldInvalidEscape", RECOMMENDED,
1335 1336
      R"({"optionalString": "\uXXXX\u6B4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1337
      "StringFieldUnterminatedEscape", RECOMMENDED,
1338 1339
      R"({"optionalString": "\u8C3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1340
      "StringFieldUnpairedHighSurrogate", RECOMMENDED,
1341 1342
      R"({"optionalString": "\uD800"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1343
      "StringFieldUnpairedLowSurrogate", RECOMMENDED,
1344 1345
      R"({"optionalString": "\uDC00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1346
      "StringFieldSurrogateInWrongOrder", RECOMMENDED,
1347 1348
      R"({"optionalString": "\uDE01\uD83D"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1349
      "StringFieldNotAString", REQUIRED,
1350 1351 1352 1353
      R"({"optionalString": 12345})");

  // Bytes fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1354
      "BytesField", REQUIRED,
1355 1356 1357
      R"({"optionalBytes": "AQI="})",
      R"(optional_bytes: "\x01\x02")");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1358
      "BytesFieldInvalidBase64Characters", REQUIRED,
1359 1360 1361 1362
      R"({"optionalBytes": "-_=="})");

  // Message fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1363
      "MessageField", REQUIRED,
1364 1365 1366 1367 1368
      R"({"optionalNestedMessage": {"a": 1234}})",
      "optional_nested_message: {a: 1234}");

  // Oneof fields.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1369
      "OneofFieldDuplicate", REQUIRED,
1370
      R"({"oneofUint32": 1, "oneofString": "test"})");
1371 1372 1373 1374 1375
  // Ensure zero values for oneof make it out/backs.
  {
    TestAllTypes message;
    message.set_oneof_uint32(0);
    RunValidProtobufTest(
1376
        "OneofZeroUint32", RECOMMENDED, message, "oneof_uint32: 0");
1377 1378
    message.mutable_oneof_nested_message()->set_a(0);
    RunValidProtobufTest(
1379
        "OneofZeroMessage", RECOMMENDED, message, "oneof_nested_message: {}");
1380 1381
    message.set_oneof_string("");
    RunValidProtobufTest(
1382
        "OneofZeroString", RECOMMENDED, message, "oneof_string: \"\"");
1383 1384
    message.set_oneof_bytes("");
    RunValidProtobufTest(
1385
        "OneofZeroBytes", RECOMMENDED, message, "oneof_bytes: \"\"");
1386 1387
    message.set_oneof_bool(false);
    RunValidProtobufTest(
1388
        "OneofZeroBool", RECOMMENDED, message, "oneof_bool: false");
1389 1390
    message.set_oneof_uint64(0);
    RunValidProtobufTest(
1391
        "OneofZeroUint64", RECOMMENDED, message, "oneof_uint64: 0");
1392 1393
    message.set_oneof_float(0.0f);
    RunValidProtobufTest(
1394
        "OneofZeroFloat", RECOMMENDED, message, "oneof_float: 0");
1395 1396
    message.set_oneof_double(0.0);
    RunValidProtobufTest(
1397
        "OneofZeroDouble", RECOMMENDED, message, "oneof_double: 0");
1398 1399
    message.set_oneof_enum(TestAllTypes::FOO);
    RunValidProtobufTest(
1400
        "OneofZeroEnum", RECOMMENDED, message, "oneof_enum: FOO");
1401 1402
  }
  RunValidJsonTest(
1403
      "OneofZeroUint32", RECOMMENDED,
1404 1405
      R"({"oneofUint32": 0})", "oneof_uint32: 0");
  RunValidJsonTest(
1406
      "OneofZeroMessage", RECOMMENDED,
1407 1408
      R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  RunValidJsonTest(
1409
      "OneofZeroString", RECOMMENDED,
1410 1411
      R"({"oneofString": ""})", "oneof_string: \"\"");
  RunValidJsonTest(
1412
      "OneofZeroBytes", RECOMMENDED,
1413
      R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
1414
  RunValidJsonTest(
1415
      "OneofZeroBool", RECOMMENDED,
1416 1417
      R"({"oneofBool": false})", "oneof_bool: false");
  RunValidJsonTest(
1418
      "OneofZeroUint64", RECOMMENDED,
1419 1420
      R"({"oneofUint64": 0})", "oneof_uint64: 0");
  RunValidJsonTest(
1421
      "OneofZeroFloat", RECOMMENDED,
1422 1423
      R"({"oneofFloat": 0.0})", "oneof_float: 0");
  RunValidJsonTest(
1424
      "OneofZeroDouble", RECOMMENDED,
1425 1426
      R"({"oneofDouble": 0.0})", "oneof_double: 0");
  RunValidJsonTest(
1427
      "OneofZeroEnum", RECOMMENDED,
1428
      R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
1429 1430 1431

  // Repeated fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1432
      "PrimitiveRepeatedField", REQUIRED,
1433 1434 1435
      R"({"repeatedInt32": [1, 2, 3, 4]})",
      "repeated_int32: [1, 2, 3, 4]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1436
      "EnumRepeatedField", REQUIRED,
1437 1438 1439
      R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
      "repeated_nested_enum: [FOO, BAR, BAZ]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1440
      "StringRepeatedField", REQUIRED,
1441 1442 1443
      R"({"repeatedString": ["Hello", "world"]})",
      R"(repeated_string: ["Hello", "world"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1444
      "BytesRepeatedField", REQUIRED,
1445 1446 1447
      R"({"repeatedBytes": ["AAEC", "AQI="]})",
      R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1448
      "MessageRepeatedField", REQUIRED,
1449 1450 1451 1452 1453 1454
      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
1455
      "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
1456 1457
      R"({"repeatedInt32": [1, false, 3, 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1458
      "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
1459 1460
      R"({"repeatedInt32": [1, 2, "name", 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1461
      "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
1462 1463
      R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1464
      "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
1465 1466
      R"({"repeatedString": ["1", 2, "3", "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1467
      "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
1468 1469
      R"({"repeatedString": ["1", "2", false, "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1470
      "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
1471 1472
      R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1473
      "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
1474 1475
      R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1476
      "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
1477 1478
      R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1479
      "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
1480 1481 1482
      R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  // Trailing comma in the repeated field is not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1483
      "RepeatedFieldTrailingComma", RECOMMENDED,
1484
      R"({"repeatedInt32": [1, 2, 3, 4,]})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1485
  ExpectParseFailureForJson(
1486
      "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1487 1488
      "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  ExpectParseFailureForJson(
1489
      "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1490 1491
      "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  ExpectParseFailureForJson(
1492
      "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1493
      "{\"repeatedInt32\": [\n  1,\n  2,\n  3,\n  4,\n]}");
1494 1495 1496

  // Map fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1497
      "Int32MapField", REQUIRED,
1498 1499 1500 1501
      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
1502
      "Int32MapFieldKeyNotQuoted", RECOMMENDED,
1503 1504
      R"({"mapInt32Int32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1505
      "Uint32MapField", REQUIRED,
1506 1507 1508 1509
      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
1510
      "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
1511 1512
      R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1513
      "Int64MapField", REQUIRED,
1514 1515 1516 1517
      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
1518
      "Int64MapFieldKeyNotQuoted", RECOMMENDED,
1519 1520
      R"({"mapInt64Int64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1521
      "Uint64MapField", REQUIRED,
1522 1523 1524 1525
      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
1526
      "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
1527 1528
      R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1529
      "BoolMapField", REQUIRED,
1530 1531 1532 1533
      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
1534
      "BoolMapFieldKeyNotQuoted", RECOMMENDED,
1535 1536
      R"({"mapBoolBool": {true: true, false: false}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1537
      "MessageMapField", REQUIRED,
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
      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
1556
      "Int32MapEscapedKey", REQUIRED,
1557 1558 1559
      R"({"mapInt32Int32": {"\u0031": 2}})",
      "map_int32_int32: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1560
      "Int64MapEscapedKey", REQUIRED,
1561 1562 1563
      R"({"mapInt64Int64": {"\u0031": 2}})",
      "map_int64_int64: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1564
      "BoolMapEscapedKey", REQUIRED,
1565 1566 1567 1568 1569
      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
1570
      "AllFieldAcceptNull", REQUIRED,
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
      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
1598
      "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
1599 1600
      R"({"repeatedInt32": [1, null, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1601
      "RepeatedFieldMessageElementIsNull", RECOMMENDED,
1602 1603 1604
      R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  // Map field keys cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1605
      "MapFieldKeyIsNull", RECOMMENDED,
1606 1607 1608
      R"({"mapInt32Int32": {null: 1}})");
  // Map field values cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1609
      "MapFieldValueIsNull", RECOMMENDED,
1610 1611
      R"({"mapInt32Int32": {"0": null}})");

Thomas Van Lenten's avatar
Thomas Van Lenten committed
1612 1613 1614
  // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  // quotes.
  ExpectParseFailureForJson(
1615
      "StringFieldSingleQuoteKey", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1616 1617
      R"({'optionalString': "Hello world!"})");
  ExpectParseFailureForJson(
1618
      "StringFieldSingleQuoteValue", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1619 1620
      R"({"optionalString": 'Hello world!'})");
  ExpectParseFailureForJson(
1621
      "StringFieldSingleQuoteBoth", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1622 1623
      R"({'optionalString': 'Hello world!'})");

1624 1625
  // Wrapper types.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1626
      "OptionalBoolWrapper", REQUIRED,
1627 1628 1629
      R"({"optionalBoolWrapper": false})",
      "optional_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1630
      "OptionalInt32Wrapper", REQUIRED,
1631 1632 1633
      R"({"optionalInt32Wrapper": 0})",
      "optional_int32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1634
      "OptionalUint32Wrapper", REQUIRED,
1635 1636 1637
      R"({"optionalUint32Wrapper": 0})",
      "optional_uint32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1638
      "OptionalInt64Wrapper", REQUIRED,
1639 1640 1641
      R"({"optionalInt64Wrapper": 0})",
      "optional_int64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1642
      "OptionalUint64Wrapper", REQUIRED,
1643 1644 1645
      R"({"optionalUint64Wrapper": 0})",
      "optional_uint64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1646
      "OptionalFloatWrapper", REQUIRED,
1647 1648 1649
      R"({"optionalFloatWrapper": 0})",
      "optional_float_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1650
      "OptionalDoubleWrapper", REQUIRED,
1651 1652 1653
      R"({"optionalDoubleWrapper": 0})",
      "optional_double_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1654
      "OptionalStringWrapper", REQUIRED,
1655 1656 1657
      R"({"optionalStringWrapper": ""})",
      R"(optional_string_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1658
      "OptionalBytesWrapper", REQUIRED,
1659 1660 1661
      R"({"optionalBytesWrapper": ""})",
      R"(optional_bytes_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1662
      "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
      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
1686
      "RepeatedBoolWrapper", REQUIRED,
1687 1688 1689 1690
      R"({"repeatedBoolWrapper": [true, false]})",
      "repeated_bool_wrapper: {value: true}"
      "repeated_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1691
      "RepeatedInt32Wrapper", REQUIRED,
1692 1693 1694 1695
      R"({"repeatedInt32Wrapper": [0, 1]})",
      "repeated_int32_wrapper: {value: 0}"
      "repeated_int32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1696
      "RepeatedUint32Wrapper", REQUIRED,
1697 1698 1699 1700
      R"({"repeatedUint32Wrapper": [0, 1]})",
      "repeated_uint32_wrapper: {value: 0}"
      "repeated_uint32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1701
      "RepeatedInt64Wrapper", REQUIRED,
1702 1703 1704 1705
      R"({"repeatedInt64Wrapper": [0, 1]})",
      "repeated_int64_wrapper: {value: 0}"
      "repeated_int64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1706
      "RepeatedUint64Wrapper", REQUIRED,
1707 1708 1709 1710
      R"({"repeatedUint64Wrapper": [0, 1]})",
      "repeated_uint64_wrapper: {value: 0}"
      "repeated_uint64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1711
      "RepeatedFloatWrapper", REQUIRED,
1712 1713 1714 1715
      R"({"repeatedFloatWrapper": [0, 1]})",
      "repeated_float_wrapper: {value: 0}"
      "repeated_float_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1716
      "RepeatedDoubleWrapper", REQUIRED,
1717 1718 1719 1720
      R"({"repeatedDoubleWrapper": [0, 1]})",
      "repeated_double_wrapper: {value: 0}"
      "repeated_double_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1721
      "RepeatedStringWrapper", REQUIRED,
1722 1723 1724 1725 1726 1727
      R"({"repeatedStringWrapper": ["", "AQI="]})",
      R"(
        repeated_string_wrapper: {value: ""}
        repeated_string_wrapper: {value: "AQI="}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1728
      "RepeatedBytesWrapper", REQUIRED,
1729 1730 1731 1732 1733 1734
      R"({"repeatedBytesWrapper": ["", "AQI="]})",
      R"(
        repeated_bytes_wrapper: {value: ""}
        repeated_bytes_wrapper: {value: "\x01\x02"}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1735
      "WrapperTypesWithNullValue", REQUIRED,
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
      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
1760
      "DurationMinValue", REQUIRED,
1761 1762 1763
      R"({"optionalDuration": "-315576000000.999999999s"})",
      "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1764
      "DurationMaxValue", REQUIRED,
1765 1766 1767
      R"({"optionalDuration": "315576000000.999999999s"})",
      "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1768
      "DurationRepeatedValue", REQUIRED,
1769 1770 1771 1772 1773
      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
1774
      "DurationMissingS", REQUIRED,
1775 1776
      R"({"optionalDuration": "1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1777
      "DurationJsonInputTooSmall", REQUIRED,
1778 1779
      R"({"optionalDuration": "-315576000001.000000000s"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1780
      "DurationJsonInputTooLarge", REQUIRED,
1781 1782
      R"({"optionalDuration": "315576000001.000000000s"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1783
      "DurationProtoInputTooSmall", REQUIRED,
1784 1785
      "optional_duration: {seconds: -315576000001 nanos: 0}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1786
      "DurationProtoInputTooLarge", REQUIRED,
1787 1788 1789
      "optional_duration: {seconds: 315576000001 nanos: 0}");

  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1790
      "DurationHasZeroFractionalDigit", RECOMMENDED,
1791 1792 1793 1794 1795
      R"({"optionalDuration": "1.000000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1796
      "DurationHas3FractionalDigits", RECOMMENDED,
1797 1798 1799 1800 1801
      R"({"optionalDuration": "1.010000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1802
      "DurationHas6FractionalDigits", RECOMMENDED,
1803 1804 1805 1806 1807
      R"({"optionalDuration": "1.000010000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1808
      "DurationHas9FractionalDigits", RECOMMENDED,
1809 1810 1811 1812 1813 1814 1815
      R"({"optionalDuration": "1.000000010s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000000010s";
      });

  // Timestamp
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1816
      "TimestampMinValue", REQUIRED,
1817 1818 1819
      R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
      "optional_timestamp: {seconds: -62135596800}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1820
      "TimestampMaxValue", REQUIRED,
1821 1822 1823
      R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
      "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1824
      "TimestampRepeatedValue", REQUIRED,
1825 1826 1827 1828 1829 1830 1831 1832 1833
      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
1834
      "TimestampWithPositiveOffset", REQUIRED,
1835 1836 1837
      R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
      "optional_timestamp: {seconds: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1838
      "TimestampWithNegativeOffset", REQUIRED,
1839 1840 1841 1842
      R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
      "optional_timestamp: {seconds: 0}");

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1843
      "TimestampJsonInputTooSmall", REQUIRED,
1844 1845
      R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1846
      "TimestampJsonInputTooLarge", REQUIRED,
1847 1848
      R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1849
      "TimestampJsonInputMissingZ", REQUIRED,
1850 1851
      R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1852
      "TimestampJsonInputMissingT", REQUIRED,
1853 1854
      R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1855
      "TimestampJsonInputLowercaseZ", REQUIRED,
1856 1857
      R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1858
      "TimestampJsonInputLowercaseT", REQUIRED,
1859 1860
      R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1861
      "TimestampProtoInputTooSmall", REQUIRED,
1862 1863
      "optional_timestamp: {seconds: -62135596801}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1864
      "TimestampProtoInputTooLarge", REQUIRED,
1865 1866
      "optional_timestamp: {seconds: 253402300800}");
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1867
      "TimestampZeroNormalized", RECOMMENDED,
1868 1869 1870 1871 1872 1873
      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
1874
      "TimestampHasZeroFractionalDigit", RECOMMENDED,
1875 1876 1877 1878 1879 1880
      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
1881
      "TimestampHas3FractionalDigits", RECOMMENDED,
1882 1883 1884 1885 1886 1887
      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
1888
      "TimestampHas6FractionalDigits", RECOMMENDED,
1889 1890 1891 1892 1893 1894
      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
1895
      "TimestampHas9FractionalDigits", RECOMMENDED,
1896 1897 1898 1899 1900 1901 1902 1903
      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
1904
      "FieldMask", REQUIRED,
1905 1906 1907
      R"({"optionalFieldMask": "foo,barBaz"})",
      R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1908
      "FieldMaskInvalidCharacter", RECOMMENDED,
1909 1910
      R"({"optionalFieldMask": "foo,bar_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1911
      "FieldMaskPathsDontRoundTrip", RECOMMENDED,
1912 1913
      R"(optional_field_mask: {paths: "fooBar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1914
      "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
1915 1916
      R"(optional_field_mask: {paths: "foo_3_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
1917
      "FieldMaskTooManyUnderscore", RECOMMENDED,
1918 1919 1920 1921
      R"(optional_field_mask: {paths: "foo__bar"})");

  // Struct
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1922
      "Struct", REQUIRED,
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
      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
1988
      "ValueAcceptInteger", REQUIRED,
1989 1990 1991
      R"({"optionalValue": 1})",
      "optional_value: { number_value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1992
      "ValueAcceptFloat", REQUIRED,
1993 1994 1995
      R"({"optionalValue": 1.5})",
      "optional_value: { number_value: 1.5}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1996
      "ValueAcceptBool", REQUIRED,
1997 1998 1999
      R"({"optionalValue": false})",
      "optional_value: { bool_value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2000
      "ValueAcceptNull", REQUIRED,
2001 2002 2003
      R"({"optionalValue": null})",
      "optional_value: { null_value: NULL_VALUE}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2004
      "ValueAcceptString", REQUIRED,
2005 2006 2007
      R"({"optionalValue": "hello"})",
      R"(optional_value: { string_value: "hello"})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2008
      "ValueAcceptList", REQUIRED,
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
      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
2023
      "ValueAcceptObject", REQUIRED,
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
      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
2040
      "Any", REQUIRED,
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/conformance.TestAllTypes",
          "optionalInt32": 12345
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/conformance.TestAllTypes] {
            optional_int32: 12345
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2055
      "AnyNested", REQUIRED,
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Any",
          "value": {
            "@type": "type.googleapis.com/conformance.TestAllTypes",
            "optionalInt32": 12345
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Any] {
            [type.googleapis.com/conformance.TestAllTypes] {
              optional_int32: 12345
            }
          }
        }
      )");
  // The special "@type" tag is not required to appear first.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2076
      "AnyUnorderedTypeTag", REQUIRED,
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
      R"({
        "optionalAny": {
          "optionalInt32": 12345,
          "@type": "type.googleapis.com/conformance.TestAllTypes"
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/conformance.TestAllTypes] {
            optional_int32: 12345
          }
        }
      )");
  // Well-known types in Any.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2092
      "AnyWithInt32ValueWrapper", REQUIRED,
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
      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
2107
      "AnyWithDuration", REQUIRED,
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
      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
2123
      "AnyWithTimestamp", REQUIRED,
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
      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
2139
      "AnyWithFieldMask", REQUIRED,
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
      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
2154
      "AnyWithStruct", REQUIRED,
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
      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
2176
      "AnyWithValueForJsonObject", REQUIRED,
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
      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
2200
      "AnyWithValueForInteger", REQUIRED,
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
      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;
2216
  if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
2217
                     "These tests were listed in the failure list, but they "
2218 2219 2220 2221
                     "don't exist.  Remove them from the failure list by "
                     "running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --remove nonexistent_tests.txt")) {
2222 2223
    ok = false;
  }
2224
  if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
2225 2226
                     "These tests failed.  If they can't be fixed right now, "
                     "you can add them to the failure list so the overall "
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
                     "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")) {
2239 2240
    ok = false;
  }
2241

2242
  if (verbose_) {
2243
    CheckSetEmpty(skipped_, "",
2244 2245 2246
                  "These tests were skipped (probably because support for some "
                  "features is not implemented)");
  }
2247 2248 2249 2250 2251 2252 2253 2254

  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");

2255
  output->assign(output_);
2256 2257

  return ok;
2258
}
2259 2260 2261

}  // namespace protobuf
}  // namespace google