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

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

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

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

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

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

67
namespace {
68

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

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

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

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

const string empty;

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

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

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

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

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

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

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

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

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

#define UNKNOWN_FIELD 666

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

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

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

189 190 191 192 193
}  // anonymous namespace

namespace google {
namespace protobuf {

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

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

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

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

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

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

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

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

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

275
void ConformanceTestSuite::RunValidInputTest(
Bo Yang's avatar
Bo Yang committed
276 277
    const string& test_name, ConformanceLevel level, const string& input,
    WireFormat input_format, const string& equivalent_text_format,
Jisi Liu's avatar
Jisi Liu committed
278 279 280 281 282 283 284 285 286 287 288
    WireFormat requested_output, bool isProto3) {
  auto newTestMessage = [&isProto3]() {
    Message* newMessage;
    if (isProto3) {
      newMessage = new TestAllTypesProto3;
    } else {
      newMessage = new TestAllTypesProto2;
    }
    return newMessage;
  };
  Message* reference_message = newTestMessage();
289
  GOOGLE_CHECK(
Jisi Liu's avatar
Jisi Liu committed
290
      TextFormat::ParseFromString(equivalent_text_format, reference_message))
291 292
          << "Failed to parse data for test case: " << test_name
          << ", data: " << equivalent_text_format;
293 294 295 296 297

  ConformanceRequest request;
  ConformanceResponse response;

  switch (input_format) {
Jisi Liu's avatar
Jisi Liu committed
298
    case conformance::PROTOBUF: {
299
      request.set_protobuf_payload(input);
Jisi Liu's avatar
Jisi Liu committed
300 301 302 303 304
      if (isProto3) {
        request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
      } else {
        request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2");
      }
305
      break;
Jisi Liu's avatar
Jisi Liu committed
306
    }
307

Jisi Liu's avatar
Jisi Liu committed
308 309
    case conformance::JSON: {
      request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
310 311
      request.set_json_payload(input);
      break;
Jisi Liu's avatar
Jisi Liu committed
312
    }
313

314
    default:
315 316 317 318 319 320 321
      GOOGLE_LOG(FATAL) << "Unspecified input format";
  }

  request.set_requested_output_format(requested_output);

  RunTest(test_name, request, &response);

Jisi Liu's avatar
Jisi Liu committed
322
  Message *test_message = newTestMessage();
323 324

  switch (response.result_case()) {
325
    case ConformanceResponse::RESULT_NOT_SET:
326
      ReportFailure(test_name, level, request, response,
327 328 329
                    "Response didn't have any field in the Response.");
      return;

330 331
    case ConformanceResponse::kParseError:
    case ConformanceResponse::kRuntimeError:
332
    case ConformanceResponse::kSerializeError:
333
      ReportFailure(test_name, level, request, response,
334
                    "Failed to parse input or produce output.");
335 336 337 338 339 340 341 342 343
      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
344
            test_name, level, request, response,
345 346 347 348 349 350 351 352
            "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
353
        ReportFailure(test_name, level, request, response,
354 355 356 357
                      "JSON output we received from test was unparseable.");
        return;
      }

Jisi Liu's avatar
Jisi Liu committed
358
      if (!test_message->ParseFromString(binary_protobuf)) {
Bo Yang's avatar
Bo Yang committed
359
        ReportFailure(test_name, level, request, response,
Jisi Liu's avatar
Jisi Liu committed
360 361
                    "INTERNAL ERROR: internal JSON->protobuf transcode "
                    "yielded unparseable proto.");
362 363 364
        return;
      }

365 366 367 368 369 370
      break;
    }

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

Jisi Liu's avatar
Jisi Liu committed
376
      if (!test_message->ParseFromString(response.protobuf_payload())) {
Bo Yang's avatar
Bo Yang committed
377
        ReportFailure(test_name, level, request, response,
Jisi Liu's avatar
Jisi Liu committed
378
                   "Protobuf output we received from test was unparseable.");
379 380 381 382 383
        return;
      }

      break;
    }
384 385 386 387

    default:
      GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
                        << response.result_case();
388 389 390
  }

  MessageDifferencer differencer;
391 392 393
  DefaultFieldComparator field_comparator;
  field_comparator.set_treat_nan_as_equal(true);
  differencer.set_field_comparator(&field_comparator);
394 395 396
  string differences;
  differencer.ReportDifferencesToString(&differences);

Jisi Liu's avatar
Jisi Liu committed
397 398 399
  bool check;
  check = differencer.Compare(*reference_message, *test_message);
  if (check) {
400 401
    ReportSuccess(test_name);
  } else {
Bo Yang's avatar
Bo Yang committed
402
    ReportFailure(test_name, level, request, response,
403 404 405 406
                  "Output was not equivalent to reference message: %s.",
                  differences.c_str());
  }
}
Jisi Liu's avatar
Jisi Liu committed
407 408 409
void ConformanceTestSuite::ExpectParseFailureForProtoWithProtoVersion (
    const string& proto, const string& test_name, ConformanceLevel level,
    bool isProto3) {
410 411 412
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(proto);
Jisi Liu's avatar
Jisi Liu committed
413 414 415 416 417
  if (isProto3) {
    request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
  } else {
    request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2");
  }
Bo Yang's avatar
Bo Yang committed
418
  string effective_test_name = ConformanceLevelToString(level) +
Jisi Liu's avatar
Jisi Liu committed
419
      (isProto3 ? ".Proto3" : ".Proto2") +
Bo Yang's avatar
Bo Yang committed
420
      ".ProtobufInput." + test_name;
421 422 423

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

426
  RunTest(effective_test_name, request, &response);
427
  if (response.result_case() == ConformanceResponse::kParseError) {
428
    ReportSuccess(effective_test_name);
429 430
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
431
  } else {
Bo Yang's avatar
Bo Yang committed
432
    ReportFailure(effective_test_name, level, request, response,
433
                  "Should have failed to parse, but didn't.");
434 435 436
  }
}

Jisi Liu's avatar
Jisi Liu committed
437 438 439 440 441 442 443
// Expect that this precise protobuf will cause a parse error.
void ConformanceTestSuite::ExpectParseFailureForProto(
    const string& proto, const string& test_name, ConformanceLevel level) {
  ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, true);
  ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level, false);
}

444 445 446 447 448
// 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.
449
void ConformanceTestSuite::ExpectHardParseFailureForProto(
Bo Yang's avatar
Bo Yang committed
450 451
    const string& proto, const string& test_name, ConformanceLevel level) {
  return ExpectParseFailureForProto(proto, test_name, level);
452
}
453

454
void ConformanceTestSuite::RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
455
    const string& test_name, ConformanceLevel level, const string& input_json,
456
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
457
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
458
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
Bo Yang's avatar
Bo Yang committed
459
      ".ProtobufOutput", level, input_json, conformance::JSON,
Jisi Liu's avatar
Jisi Liu committed
460
      equivalent_text_format, conformance::PROTOBUF, true);
Bo Yang's avatar
Bo Yang committed
461
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
462
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
Bo Yang's avatar
Bo Yang committed
463
      ".JsonOutput", level, input_json, conformance::JSON,
Jisi Liu's avatar
Jisi Liu committed
464
      equivalent_text_format, conformance::JSON, true);
465 466 467
}

void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
Jisi Liu's avatar
Jisi Liu committed
468
    const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
469
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
470
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
471
      ConformanceLevelToString(level) + ".Proto3" + ".ProtobufInput." + test_name +
Bo Yang's avatar
Bo Yang committed
472
      ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
Jisi Liu's avatar
Jisi Liu committed
473
      equivalent_text_format, conformance::JSON, true);
474 475
}

476
void ConformanceTestSuite::RunValidProtobufTest(
477
    const string& test_name, ConformanceLevel level,
Jisi Liu's avatar
Jisi Liu committed
478 479 480 481 482 483
    const string& input_protobuf, const string& equivalent_text_format,
    bool isProto3) {
  string rname = ".Proto3";
  if (!isProto3) {
    rname = ".Proto2";
  }
484
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
485
      ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
486
      ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
Jisi Liu's avatar
Jisi Liu committed
487 488 489 490 491 492 493
      equivalent_text_format, conformance::PROTOBUF, isProto3);
  if (isProto3) {
    RunValidInputTest(
        ConformanceLevelToString(level) + rname + ".ProtobufInput." +  test_name +
        ".JsonOutput", level, input_protobuf, conformance::PROTOBUF,
        equivalent_text_format, conformance::JSON, isProto3);
  }
494 495 496
}

void ConformanceTestSuite::RunValidProtobufTestWithMessage(
Jisi Liu's avatar
Jisi Liu committed
497 498 499
    const string& test_name, ConformanceLevel level, const Message *input,
    const string& equivalent_text_format, bool isProto3) {
  RunValidProtobufTest(test_name, level, input->SerializeAsString(), equivalent_text_format, isProto3);
500 501
}

502 503 504 505 506 507
// 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
508
    const string& test_name, ConformanceLevel level, const string& input_json,
509 510 511 512 513
    const Validator& validator) {
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
  request.set_requested_output_format(conformance::JSON);
Jisi Liu's avatar
Jisi Liu committed
514
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
515

Bo Yang's avatar
Bo Yang committed
516
  string effective_test_name = ConformanceLevelToString(level) +
Jisi Liu's avatar
Jisi Liu committed
517
      ".Proto3.JsonInput." + test_name + ".Validator";
518 519 520

  RunTest(effective_test_name, request, &response);

521 522 523 524 525
  if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
    return;
  }

526
  if (response.result_case() != ConformanceResponse::kJsonPayload) {
Bo Yang's avatar
Bo Yang committed
527
    ReportFailure(effective_test_name, level, request, response,
528 529 530 531 532 533 534
                  "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
535
    ReportFailure(effective_test_name, level, request, response,
536 537 538 539 540
                  "JSON payload cannot be parsed as valid JSON: %s",
                  reader.getFormattedErrorMessages().c_str());
    return;
  }
  if (!validator(value)) {
Bo Yang's avatar
Bo Yang committed
541
    ReportFailure(effective_test_name, level, request, response,
542 543 544 545 546 547 548
                  "JSON payload validation failed.");
    return;
  }
  ReportSuccess(effective_test_name);
}

void ConformanceTestSuite::ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
549
    const string& test_name, ConformanceLevel level, const string& input_json) {
550 551 552
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
Jisi Liu's avatar
Jisi Liu committed
553
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
Bo Yang's avatar
Bo Yang committed
554
  string effective_test_name =
Jisi Liu's avatar
Jisi Liu committed
555
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name;
556 557 558 559 560 561 562 563

  // 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);
564 565
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
566
  } else {
Bo Yang's avatar
Bo Yang committed
567
    ReportFailure(effective_test_name, level, request, response,
568 569 570 571 572
                  "Should have failed to parse, but didn't.");
  }
}

void ConformanceTestSuite::ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
573
    const string& test_name, ConformanceLevel level, const string& text_format) {
Jisi Liu's avatar
Jisi Liu committed
574
  TestAllTypesProto3 payload_message;
575 576 577 578 579 580 581
  GOOGLE_CHECK(
      TextFormat::ParseFromString(text_format, &payload_message))
          << "Failed to parse: " << text_format;

  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(payload_message.SerializeAsString());
Jisi Liu's avatar
Jisi Liu committed
582
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
Bo Yang's avatar
Bo Yang committed
583 584
  string effective_test_name =
      ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
585 586 587 588 589
  request.set_requested_output_format(conformance::JSON);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kSerializeError) {
    ReportSuccess(effective_test_name);
590 591
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
592
  } else {
Bo Yang's avatar
Bo Yang committed
593
    ReportFailure(effective_test_name, level, request, response,
594 595 596 597
                  "Should have failed to serialize, but didn't.");
  }
}

Jisi Liu's avatar
Jisi Liu committed
598
//TODO: proto2?
599
void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
600 601 602 603 604 605 606 607 608 609
  // 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
  };

Jisi Liu's avatar
Jisi Liu committed
610 611
  const FieldDescriptor* field = GetFieldForType(type, false, true);
  const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
612 613
  WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
      static_cast<WireFormatLite::FieldType>(type));
614
  const string& incomplete = incompletes[wire_type];
615 616
  const string type_name =
      UpperCase(string(".") + FieldDescriptor::TypeName(type));
617

618
  ExpectParseFailureForProto(
619
      tag(field->number(), wire_type),
Bo Yang's avatar
Bo Yang committed
620
      "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
621

622
  ExpectParseFailureForProto(
623
      tag(rep_field->number(), wire_type),
Bo Yang's avatar
Bo Yang committed
624
      "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
625

626 627
  ExpectParseFailureForProto(
      tag(UNKNOWN_FIELD, wire_type),
Bo Yang's avatar
Bo Yang committed
628
      "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
629 630

  ExpectParseFailureForProto(
631
      cat( tag(field->number(), wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
632
      "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
633 634

  ExpectParseFailureForProto(
635
      cat( tag(rep_field->number(), wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
636
      "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
637 638

  ExpectParseFailureForProto(
639
      cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
640
      "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
641 642 643

  if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
    ExpectParseFailureForProto(
644
        cat( tag(field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
645 646
        "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
        REQUIRED);
647 648

    ExpectParseFailureForProto(
649
        cat( tag(rep_field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
650 651
        "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
        REQUIRED);
652 653 654

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

658
    if (type == FieldDescriptor::TYPE_MESSAGE) {
659 660 661 662 663
      // Submessage ends in the middle of a value.
      string incomplete_submsg =
          cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
                incompletes[WireFormatLite::WIRETYPE_VARINT] );
      ExpectHardParseFailureForProto(
664
          cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
665
               varint(incomplete_submsg.size()),
666
               incomplete_submsg ),
Bo Yang's avatar
Bo Yang committed
667
          "PrematureEofInSubmessageValue" + type_name, REQUIRED);
668
    }
669
  } else if (type != FieldDescriptor::TYPE_GROUP) {
670 671 672 673
    // Non-delimited, non-group: eligible for packing.

    // Packed region ends in the middle of a value.
    ExpectHardParseFailureForProto(
674 675
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(incomplete.size()), incomplete),
Bo Yang's avatar
Bo Yang committed
676
        "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
677 678 679

    // EOF in the middle of packed region.
    ExpectParseFailureForProto(
680 681
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(1)),
Bo Yang's avatar
Bo Yang committed
682
        "PrematureEofInPackedField" + type_name, REQUIRED);
683 684 685
  }
}

686 687 688
void ConformanceTestSuite::TestValidDataForType(
    FieldDescriptor::Type type,
    std::vector<std::pair<std::string, std::string>> values) {
Jisi Liu's avatar
Jisi Liu committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
  for (int isProto3 = 0; isProto3 < 2; isProto3++) {
    const string type_name =
        UpperCase(string(".") + FieldDescriptor::TypeName(type));
    WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
        static_cast<WireFormatLite::FieldType>(type));
    const FieldDescriptor* field = GetFieldForType(type, false, isProto3);
    const FieldDescriptor* rep_field = GetFieldForType(type, true, isProto3);

    RunValidProtobufTest("ValidDataScalar" + type_name, REQUIRED,
                         cat(tag(field->number(), wire_type), values[0].first),
                         field->name() + ": " + values[0].second, isProto3);

    string proto;
    string text = field->name() + ": " + values.back().second;
    for (size_t i = 0; i < values.size(); i++) {
      proto += cat(tag(field->number(), wire_type), values[i].first);
    }
    RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED,
                         proto, text, isProto3);
708

Jisi Liu's avatar
Jisi Liu committed
709 710
    proto.clear();
    text.clear();
711

Jisi Liu's avatar
Jisi Liu committed
712 713 714 715 716 717
    for (size_t i = 0; i < values.size(); i++) {
      proto += cat(tag(rep_field->number(), wire_type), values[i].first);
      text += rep_field->name() + ": " + values[i].second + " ";
    }
    RunValidProtobufTest("ValidDataRepeated" + type_name, REQUIRED,
                         proto, text, isProto3);
718 719 720
  }
}

721 722 723
void ConformanceTestSuite::SetFailureList(const string& filename,
                                          const vector<string>& failure_list) {
  failure_list_filename_ = filename;
724 725 726 727 728
  expected_to_fail_.clear();
  std::copy(failure_list.begin(), failure_list.end(),
            std::inserter(expected_to_fail_, expected_to_fail_.end()));
}

729
bool ConformanceTestSuite::CheckSetEmpty(const std::set<string>& set_to_check,
730 731
                                         const std::string& write_to_file,
                                         const std::string& msg) {
732 733 734 735
  if (set_to_check.empty()) {
    return true;
  } else {
    StringAppendF(&output_, "\n");
736
    StringAppendF(&output_, "%s\n\n", msg.c_str());
737
    for (std::set<string>::const_iterator iter = set_to_check.begin();
738
         iter != set_to_check.end(); ++iter) {
739
      StringAppendF(&output_, "  %s\n", iter->c_str());
740
    }
741
    StringAppendF(&output_, "\n");
742 743 744 745

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

756 757 758 759
    return false;
  }
}

Jisi Liu's avatar
Jisi Liu committed
760
// TODO: proto2?
761 762 763 764 765 766 767 768 769 770 771 772 773 774
void ConformanceTestSuite::TestIllegalTags() {
  // field num 0 is illegal
  string nullfield[] = {
    "\1DEADBEEF",
    "\2\1\1",
    "\3\4",
    "\5DEAD"
  };
  for (int i = 0; i < 4; i++) {
    string name = "IllegalZeroFieldNum_Case_0";
    name.back() += i;
    ExpectParseFailureForProto(nullfield[i], name, REQUIRED);
  }
}
Jisi Liu's avatar
Jisi Liu committed
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
template <class MessageType>
void ConformanceTestSuite::TestOneofMessage (MessageType &message,
                                             bool isProto3) {
  message.set_oneof_uint32(0);
  RunValidProtobufTestWithMessage(
      "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", isProto3);
  message.mutable_oneof_nested_message()->set_a(0);
  RunValidProtobufTestWithMessage(
      "OneofZeroMessage", RECOMMENDED, &message,
      isProto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}",
      isProto3);
  message.mutable_oneof_nested_message()->set_a(1);
  RunValidProtobufTestWithMessage(
      "OneofZeroMessageSetTwice", RECOMMENDED, &message,
      "oneof_nested_message: {a: 1}",
      isProto3);
  message.set_oneof_string("");
  RunValidProtobufTestWithMessage(
      "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", isProto3);
  message.set_oneof_bytes("");
  RunValidProtobufTestWithMessage(
      "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", isProto3);
  message.set_oneof_bool(false);
  RunValidProtobufTestWithMessage(
      "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", isProto3);
  message.set_oneof_uint64(0);
  RunValidProtobufTestWithMessage(
      "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", isProto3);
  message.set_oneof_float(0.0f);
  RunValidProtobufTestWithMessage(
      "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", isProto3);
  message.set_oneof_double(0.0);
  RunValidProtobufTestWithMessage(
      "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", isProto3);
  message.set_oneof_enum(MessageType::FOO);
  RunValidProtobufTestWithMessage(
      "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", isProto3);
}
813

814
bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
815 816 817
                                    std::string* output) {
  runner_ = runner;
  successes_ = 0;
818 819
  expected_failures_ = 0;
  skipped_.clear();
820 821 822
  test_names_.clear();
  unexpected_failing_tests_.clear();
  unexpected_succeeding_tests_.clear();
823 824
  type_resolver_.reset(NewTypeResolverForDescriptorPool(
      kTypeUrlPrefix, DescriptorPool::generated_pool()));
Jisi Liu's avatar
Jisi Liu committed
825
  type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
826 827

  output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
828 829

  for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
830
    if (i == FieldDescriptor::TYPE_GROUP) continue;
831
    TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
832 833
  }

834 835
  TestIllegalTags();

836 837 838 839 840 841 842 843 844 845 846 847 848 849
  int64 kInt64Min = -9223372036854775808ULL;
  int64 kInt64Max = 9223372036854775807ULL;
  uint64 kUint64Max = 18446744073709551615ULL;
  int32 kInt32Max = 2147483647;
  int32 kInt32Min = -2147483648;
  uint32 kUint32Max = 4294967295UL;

  TestValidDataForType(FieldDescriptor::TYPE_DOUBLE, {
    {dbl(0.1), "0.1"},
    {dbl(1.7976931348623157e+308), "1.7976931348623157e+308"},
    {dbl(2.22507385850720138309e-308), "2.22507385850720138309e-308"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_FLOAT, {
    {flt(0.1), "0.1"},
850
    {flt(1.00000075e-36), "1.00000075e-36"},
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
    {flt(3.402823e+38), "3.402823e+38"},  // 3.40282347e+38
    {flt(1.17549435e-38f), "1.17549435e-38"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_INT64, {
    {varint(12345), "12345"},
    {varint(kInt64Max), std::to_string(kInt64Max)},
    {varint(kInt64Min), std::to_string(kInt64Min)}
  });
  TestValidDataForType(FieldDescriptor::TYPE_UINT64, {
    {varint(12345), "12345"},
    {varint(kUint64Max), std::to_string(kUint64Max)},
    {varint(0), "0"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_INT32, {
    {varint(12345), "12345"},
866 867
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
868 869
    {varint(kInt32Max), std::to_string(kInt32Max)},
    {varint(kInt32Min), std::to_string(kInt32Min)},
870 871 872
    {varint(1LL << 33), std::to_string(static_cast<int32>(1LL << 33))},
    {varint((1LL << 33) - 1),
     std::to_string(static_cast<int32>((1LL << 33) - 1))},
873 874 875
  });
  TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
    {varint(12345), "12345"},
876 877
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
878
    {varint(kUint32Max), std::to_string(kUint32Max)},  // UINT32_MAX
879 880 881 882
    {varint(0), "0"},
    {varint(1LL << 33), std::to_string(static_cast<uint32>(1LL << 33))},
    {varint((1LL << 33) - 1),
     std::to_string(static_cast<uint32>((1LL << 33) - 1))},
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
  });
  TestValidDataForType(FieldDescriptor::TYPE_FIXED64, {
    {u64(12345), "12345"},
    {u64(kUint64Max), std::to_string(kUint64Max)},
    {u64(0), "0"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_FIXED32, {
    {u32(12345), "12345"},
    {u32(kUint32Max), std::to_string(kUint32Max)},  // UINT32_MAX
    {u32(0), "0"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_SFIXED64, {
    {u64(12345), "12345"},
    {u64(kInt64Max), std::to_string(kInt64Max)},
    {u64(kInt64Min), std::to_string(kInt64Min)}
  });
  TestValidDataForType(FieldDescriptor::TYPE_SFIXED32, {
    {u32(12345), "12345"},
    {u32(kInt32Max), std::to_string(kInt32Max)},
    {u32(kInt32Min), std::to_string(kInt32Min)}
  });
  TestValidDataForType(FieldDescriptor::TYPE_BOOL, {
    {varint(1), "true"},
    {varint(0), "false"},
    {varint(12345678), "true"}
  });
  TestValidDataForType(FieldDescriptor::TYPE_SINT32, {
    {zz32(12345), "12345"},
    {zz32(kInt32Max), std::to_string(kInt32Max)},
    {zz32(kInt32Min), std::to_string(kInt32Min)}
  });
  TestValidDataForType(FieldDescriptor::TYPE_SINT64, {
    {zz64(12345), "12345"},
    {zz64(kInt64Max), std::to_string(kInt64Max)},
    {zz64(kInt64Min), std::to_string(kInt64Min)}
  });

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

Bo Yang's avatar
Bo Yang committed
927 928
  RunValidJsonTest("HelloWorld", REQUIRED,
                   "{\"optionalString\":\"Hello, World!\"}",
929
                   "optional_string: 'Hello, World!'");
930

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

  // Integer fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1191
      "Int32FieldMaxValue", REQUIRED,
1192 1193 1194
      R"({"optionalInt32": 2147483647})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1195
      "Int32FieldMinValue", REQUIRED,
1196 1197 1198
      R"({"optionalInt32": -2147483648})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1199
      "Uint32FieldMaxValue", REQUIRED,
1200 1201 1202
      R"({"optionalUint32": 4294967295})",
      "optional_uint32: 4294967295");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1203
      "Int64FieldMaxValue", REQUIRED,
1204 1205 1206
      R"({"optionalInt64": "9223372036854775807"})",
      "optional_int64: 9223372036854775807");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1207
      "Int64FieldMinValue", REQUIRED,
1208 1209 1210
      R"({"optionalInt64": "-9223372036854775808"})",
      "optional_int64: -9223372036854775808");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1211
      "Uint64FieldMaxValue", REQUIRED,
1212 1213
      R"({"optionalUint64": "18446744073709551615"})",
      "optional_uint64: 18446744073709551615");
1214 1215 1216 1217 1218 1219
  // 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.
1220
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1221
      "Int64FieldMaxValueNotQuoted", REQUIRED,
1222 1223
      R"({"optionalInt64": 9223372036854774784})",
      "optional_int64: 9223372036854774784");
1224
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1225
      "Int64FieldMinValueNotQuoted", REQUIRED,
1226 1227
      R"({"optionalInt64": -9223372036854775808})",
      "optional_int64: -9223372036854775808");
1228 1229
  // Largest interoperable Uint64; see comment above
  // for Int64FieldMaxValueNotQuoted.
1230
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1231
      "Uint64FieldMaxValueNotQuoted", REQUIRED,
1232 1233
      R"({"optionalUint64": 18446744073709549568})",
      "optional_uint64: 18446744073709549568");
1234 1235
  // Values can be represented as JSON strings.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1236
      "Int32FieldStringValue", REQUIRED,
1237 1238 1239
      R"({"optionalInt32": "2147483647"})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1240
      "Int32FieldStringValueEscaped", REQUIRED,
1241 1242 1243 1244 1245
      R"({"optionalInt32": "2\u003147483647"})",
      "optional_int32: 2147483647");

  // Parsers reject out-of-bound integer values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1246
      "Int32FieldTooLarge", REQUIRED,
1247 1248
      R"({"optionalInt32": 2147483648})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1249
      "Int32FieldTooSmall", REQUIRED,
1250 1251
      R"({"optionalInt32": -2147483649})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1252
      "Uint32FieldTooLarge", REQUIRED,
1253 1254
      R"({"optionalUint32": 4294967296})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1255
      "Int64FieldTooLarge", REQUIRED,
1256 1257
      R"({"optionalInt64": "9223372036854775808"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1258
      "Int64FieldTooSmall", REQUIRED,
1259 1260
      R"({"optionalInt64": "-9223372036854775809"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1261
      "Uint64FieldTooLarge", REQUIRED,
1262 1263 1264
      R"({"optionalUint64": "18446744073709551616"})");
  // Parser reject non-integer numeric values as well.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1265
      "Int32FieldNotInteger", REQUIRED,
1266 1267
      R"({"optionalInt32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1268
      "Uint32FieldNotInteger", REQUIRED,
1269 1270
      R"({"optionalUint32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1271
      "Int64FieldNotInteger", REQUIRED,
1272 1273
      R"({"optionalInt64": "0.5"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1274
      "Uint64FieldNotInteger", REQUIRED,
1275 1276 1277 1278
      R"({"optionalUint64": "0.5"})");

  // Integers but represented as float values are accepted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1279
      "Int32FieldFloatTrailingZero", REQUIRED,
1280 1281 1282
      R"({"optionalInt32": 100000.000})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1283
      "Int32FieldExponentialFormat", REQUIRED,
1284 1285 1286
      R"({"optionalInt32": 1e5})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1287
      "Int32FieldMaxFloatValue", REQUIRED,
1288 1289 1290
      R"({"optionalInt32": 2.147483647e9})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1291
      "Int32FieldMinFloatValue", REQUIRED,
1292 1293 1294
      R"({"optionalInt32": -2.147483648e9})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1295
      "Uint32FieldMaxFloatValue", REQUIRED,
1296 1297 1298 1299 1300
      R"({"optionalUint32": 4.294967295e9})",
      "optional_uint32: 4294967295");

  // Parser reject non-numeric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1301
      "Int32FieldNotNumber", REQUIRED,
1302 1303
      R"({"optionalInt32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1304
      "Uint32FieldNotNumber", REQUIRED,
1305 1306
      R"({"optionalUint32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1307
      "Int64FieldNotNumber", REQUIRED,
1308 1309
      R"({"optionalInt64": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1310
      "Uint64FieldNotNumber", REQUIRED,
1311 1312 1313
      R"({"optionalUint64": "3x3"})");
  // JSON does not allow "+" on numric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1314
      "Int32FieldPlusSign", REQUIRED,
1315 1316 1317
      R"({"optionalInt32": +1})");
  // JSON doesn't allow leading 0s.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1318
      "Int32FieldLeadingZero", REQUIRED,
1319 1320
      R"({"optionalInt32": 01})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1321
      "Int32FieldNegativeWithLeadingZero", REQUIRED,
1322 1323
      R"({"optionalInt32": -01})");
  // String values must follow the same syntax rule. Specifically leading
1324
  // or trailing spaces are not allowed.
1325
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1326
      "Int32FieldLeadingSpace", REQUIRED,
1327 1328
      R"({"optionalInt32": " 1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1329
      "Int32FieldTrailingSpace", REQUIRED,
1330 1331 1332 1333
      R"({"optionalInt32": "1 "})");

  // 64-bit values are serialized as strings.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1334
      "Int64FieldBeString", RECOMMENDED,
1335 1336 1337 1338 1339 1340
      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
1341
      "Uint64FieldBeString", RECOMMENDED,
1342 1343 1344 1345 1346 1347 1348 1349
      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
1350
      "BoolFieldTrue", REQUIRED,
1351 1352 1353
      R"({"optionalBool":true})",
      "optional_bool: true");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1354
      "BoolFieldFalse", REQUIRED,
1355 1356 1357 1358 1359
      R"({"optionalBool":false})",
      "optional_bool: false");

  // Other forms are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1360
      "BoolFieldIntegerZero", RECOMMENDED,
1361 1362
      R"({"optionalBool":0})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1363
      "BoolFieldIntegerOne", RECOMMENDED,
1364 1365
      R"({"optionalBool":1})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1366
      "BoolFieldCamelCaseTrue", RECOMMENDED,
1367 1368
      R"({"optionalBool":True})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1369
      "BoolFieldCamelCaseFalse", RECOMMENDED,
1370 1371
      R"({"optionalBool":False})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1372
      "BoolFieldAllCapitalTrue", RECOMMENDED,
1373 1374
      R"({"optionalBool":TRUE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1375
      "BoolFieldAllCapitalFalse", RECOMMENDED,
1376 1377
      R"({"optionalBool":FALSE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1378
      "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1379 1380
      R"({"optionalBool":"true"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1381
      "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1382 1383 1384 1385
      R"({"optionalBool":"false"})");

  // Float fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1386
      "FloatFieldMinPositiveValue", REQUIRED,
1387 1388 1389
      R"({"optionalFloat": 1.175494e-38})",
      "optional_float: 1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1390
      "FloatFieldMaxNegativeValue", REQUIRED,
1391 1392 1393
      R"({"optionalFloat": -1.175494e-38})",
      "optional_float: -1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1394
      "FloatFieldMaxPositiveValue", REQUIRED,
1395 1396 1397
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1398
      "FloatFieldMinNegativeValue", REQUIRED,
1399 1400 1401 1402
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1403
      "FloatFieldQuotedValue", REQUIRED,
1404 1405 1406 1407
      R"({"optionalFloat": "1"})",
      "optional_float: 1");
  // Special values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1408
      "FloatFieldNan", REQUIRED,
1409 1410 1411
      R"({"optionalFloat": "NaN"})",
      "optional_float: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1412
      "FloatFieldInfinity", REQUIRED,
1413 1414 1415
      R"({"optionalFloat": "Infinity"})",
      "optional_float: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1416
      "FloatFieldNegativeInfinity", REQUIRED,
1417 1418 1419 1420
      R"({"optionalFloat": "-Infinity"})",
      "optional_float: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
Jisi Liu's avatar
Jisi Liu committed
1421
    TestAllTypesProto3 message;
1422 1423 1424 1425 1426
    // 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
1427
        "FloatFieldNormalizeQuietNan", REQUIRED, message,
1428 1429 1430 1431 1432 1433
        "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
1434
        "FloatFieldNormalizeSignalingNan", REQUIRED, message,
1435 1436
        "optional_float: nan");
  }
1437

1438 1439
  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1440
      "FloatFieldNanNotQuoted", RECOMMENDED,
1441 1442
      R"({"optionalFloat": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1443
      "FloatFieldInfinityNotQuoted", RECOMMENDED,
1444 1445
      R"({"optionalFloat": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1446
      "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1447 1448 1449
      R"({"optionalFloat": -Infinity})");
  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1450
      "FloatFieldTooSmall", REQUIRED,
1451 1452
      R"({"optionalFloat": -3.502823e+38})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1453
      "FloatFieldTooLarge", REQUIRED,
1454 1455 1456 1457
      R"({"optionalFloat": 3.502823e+38})");

  // Double fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1458
      "DoubleFieldMinPositiveValue", REQUIRED,
1459 1460 1461
      R"({"optionalDouble": 2.22507e-308})",
      "optional_double: 2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1462
      "DoubleFieldMaxNegativeValue", REQUIRED,
1463 1464 1465
      R"({"optionalDouble": -2.22507e-308})",
      "optional_double: -2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1466
      "DoubleFieldMaxPositiveValue", REQUIRED,
1467 1468 1469
      R"({"optionalDouble": 1.79769e+308})",
      "optional_double: 1.79769e+308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1470
      "DoubleFieldMinNegativeValue", REQUIRED,
1471 1472 1473 1474
      R"({"optionalDouble": -1.79769e+308})",
      "optional_double: -1.79769e+308");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1475
      "DoubleFieldQuotedValue", REQUIRED,
1476 1477 1478 1479
      R"({"optionalDouble": "1"})",
      "optional_double: 1");
  // Speical values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1480
      "DoubleFieldNan", REQUIRED,
1481 1482 1483
      R"({"optionalDouble": "NaN"})",
      "optional_double: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1484
      "DoubleFieldInfinity", REQUIRED,
1485 1486 1487
      R"({"optionalDouble": "Infinity"})",
      "optional_double: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1488
      "DoubleFieldNegativeInfinity", REQUIRED,
1489 1490 1491 1492
      R"({"optionalDouble": "-Infinity"})",
      "optional_double: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
Jisi Liu's avatar
Jisi Liu committed
1493
    TestAllTypesProto3 message;
1494 1495 1496
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1497
        "DoubleFieldNormalizeQuietNan", REQUIRED, message,
1498 1499 1500 1501
        "optional_double: nan");
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1502
        "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
1503 1504 1505 1506 1507
        "optional_double: nan");
  }

  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1508
      "DoubleFieldNanNotQuoted", RECOMMENDED,
1509 1510
      R"({"optionalDouble": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1511
      "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1512 1513
      R"({"optionalDouble": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1514
      "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1515 1516 1517 1518
      R"({"optionalDouble": -Infinity})");

  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1519
      "DoubleFieldTooSmall", REQUIRED,
1520 1521
      R"({"optionalDouble": -1.89769e+308})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1522
      "DoubleFieldTooLarge", REQUIRED,
1523 1524 1525 1526
      R"({"optionalDouble": +1.89769e+308})");

  // Enum fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1527
      "EnumField", REQUIRED,
1528 1529 1530 1531
      R"({"optionalNestedEnum": "FOO"})",
      "optional_nested_enum: FOO");
  // Enum values must be represented as strings.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1532
      "EnumFieldNotQuoted", REQUIRED,
1533 1534 1535
      R"({"optionalNestedEnum": FOO})");
  // Numeric values are allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1536
      "EnumFieldNumericValueZero", REQUIRED,
1537 1538 1539
      R"({"optionalNestedEnum": 0})",
      "optional_nested_enum: FOO");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1540
      "EnumFieldNumericValueNonZero", REQUIRED,
1541 1542 1543 1544
      R"({"optionalNestedEnum": 1})",
      "optional_nested_enum: BAR");
  // Unknown enum values are represented as numeric values.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1545
      "EnumFieldUnknownValue", REQUIRED,
1546 1547 1548 1549 1550 1551 1552 1553
      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
1554
      "StringField", REQUIRED,
1555 1556 1557
      R"({"optionalString": "Hello world!"})",
      "optional_string: \"Hello world!\"");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1558
      "StringFieldUnicode", REQUIRED,
1559 1560 1561 1562
      // Google in Chinese.
      R"({"optionalString": "谷歌"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1563
      "StringFieldEscape", REQUIRED,
1564 1565 1566
      R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
      R"(optional_string: "\"\\/\b\f\n\r\t")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1567
      "StringFieldUnicodeEscape", REQUIRED,
1568 1569 1570
      R"({"optionalString": "\u8C37\u6B4C"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1571
      "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
1572 1573 1574
      R"({"optionalString": "\u8c37\u6b4c"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1575
      "StringFieldSurrogatePair", REQUIRED,
1576 1577 1578 1579 1580 1581
      // 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
1582
      "StringFieldUppercaseEscapeLetter", RECOMMENDED,
1583 1584
      R"({"optionalString": "\U8C37\U6b4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1585
      "StringFieldInvalidEscape", RECOMMENDED,
1586 1587
      R"({"optionalString": "\uXXXX\u6B4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1588
      "StringFieldUnterminatedEscape", RECOMMENDED,
1589 1590
      R"({"optionalString": "\u8C3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1591
      "StringFieldUnpairedHighSurrogate", RECOMMENDED,
1592 1593
      R"({"optionalString": "\uD800"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1594
      "StringFieldUnpairedLowSurrogate", RECOMMENDED,
1595 1596
      R"({"optionalString": "\uDC00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1597
      "StringFieldSurrogateInWrongOrder", RECOMMENDED,
1598 1599
      R"({"optionalString": "\uDE01\uD83D"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1600
      "StringFieldNotAString", REQUIRED,
1601 1602 1603 1604
      R"({"optionalString": 12345})");

  // Bytes fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1605
      "BytesField", REQUIRED,
1606 1607
      R"({"optionalBytes": "AQI="})",
      R"(optional_bytes: "\x01\x02")");
1608 1609 1610 1611
  RunValidJsonTest(
      "BytesFieldBase64Url", RECOMMENDED,
      R"({"optionalBytes": "-_"})",
      R"(optional_bytes: "\xfb")");
1612 1613 1614

  // Message fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1615
      "MessageField", REQUIRED,
1616 1617 1618 1619 1620
      R"({"optionalNestedMessage": {"a": 1234}})",
      "optional_nested_message: {a: 1234}");

  // Oneof fields.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1621
      "OneofFieldDuplicate", REQUIRED,
1622
      R"({"oneofUint32": 1, "oneofString": "test"})");
1623
  // Ensure zero values for oneof make it out/backs.
Jisi Liu's avatar
Jisi Liu committed
1624 1625 1626 1627
  TestAllTypesProto3 messageProto3;
  TestAllTypesProto2 messageProto2;
  TestOneofMessage(messageProto3, true);
  TestOneofMessage(messageProto2, false);
1628
  RunValidJsonTest(
1629
      "OneofZeroUint32", RECOMMENDED,
1630 1631
      R"({"oneofUint32": 0})", "oneof_uint32: 0");
  RunValidJsonTest(
1632
      "OneofZeroMessage", RECOMMENDED,
1633 1634
      R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  RunValidJsonTest(
1635
      "OneofZeroString", RECOMMENDED,
1636 1637
      R"({"oneofString": ""})", "oneof_string: \"\"");
  RunValidJsonTest(
1638
      "OneofZeroBytes", RECOMMENDED,
1639
      R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
1640
  RunValidJsonTest(
1641
      "OneofZeroBool", RECOMMENDED,
1642 1643
      R"({"oneofBool": false})", "oneof_bool: false");
  RunValidJsonTest(
1644
      "OneofZeroUint64", RECOMMENDED,
1645 1646
      R"({"oneofUint64": 0})", "oneof_uint64: 0");
  RunValidJsonTest(
1647
      "OneofZeroFloat", RECOMMENDED,
1648 1649
      R"({"oneofFloat": 0.0})", "oneof_float: 0");
  RunValidJsonTest(
1650
      "OneofZeroDouble", RECOMMENDED,
1651 1652
      R"({"oneofDouble": 0.0})", "oneof_double: 0");
  RunValidJsonTest(
1653
      "OneofZeroEnum", RECOMMENDED,
1654
      R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
1655 1656 1657

  // Repeated fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1658
      "PrimitiveRepeatedField", REQUIRED,
1659 1660 1661
      R"({"repeatedInt32": [1, 2, 3, 4]})",
      "repeated_int32: [1, 2, 3, 4]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1662
      "EnumRepeatedField", REQUIRED,
1663 1664 1665
      R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
      "repeated_nested_enum: [FOO, BAR, BAZ]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1666
      "StringRepeatedField", REQUIRED,
1667 1668 1669
      R"({"repeatedString": ["Hello", "world"]})",
      R"(repeated_string: ["Hello", "world"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1670
      "BytesRepeatedField", REQUIRED,
1671 1672 1673
      R"({"repeatedBytes": ["AAEC", "AQI="]})",
      R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1674
      "MessageRepeatedField", REQUIRED,
1675 1676 1677 1678 1679 1680
      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
1681
      "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
1682 1683
      R"({"repeatedInt32": [1, false, 3, 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1684
      "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
1685 1686
      R"({"repeatedInt32": [1, 2, "name", 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1687
      "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
1688 1689
      R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1690
      "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
1691 1692
      R"({"repeatedString": ["1", 2, "3", "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1693
      "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
1694 1695
      R"({"repeatedString": ["1", "2", false, "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1696
      "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
1697 1698
      R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1699
      "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
1700 1701
      R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1702
      "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
1703 1704
      R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1705
      "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
1706 1707 1708
      R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  // Trailing comma in the repeated field is not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1709
      "RepeatedFieldTrailingComma", RECOMMENDED,
1710
      R"({"repeatedInt32": [1, 2, 3, 4,]})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1711
  ExpectParseFailureForJson(
1712
      "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1713 1714
      "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  ExpectParseFailureForJson(
1715
      "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1716 1717
      "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  ExpectParseFailureForJson(
1718
      "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1719
      "{\"repeatedInt32\": [\n  1,\n  2,\n  3,\n  4,\n]}");
1720 1721 1722

  // Map fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1723
      "Int32MapField", REQUIRED,
1724 1725 1726 1727
      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
1728
      "Int32MapFieldKeyNotQuoted", RECOMMENDED,
1729 1730
      R"({"mapInt32Int32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1731
      "Uint32MapField", REQUIRED,
1732 1733 1734 1735
      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
1736
      "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
1737 1738
      R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1739
      "Int64MapField", REQUIRED,
1740 1741 1742 1743
      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
1744
      "Int64MapFieldKeyNotQuoted", RECOMMENDED,
1745 1746
      R"({"mapInt64Int64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1747
      "Uint64MapField", REQUIRED,
1748 1749 1750 1751
      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
1752
      "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
1753 1754
      R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1755
      "BoolMapField", REQUIRED,
1756 1757 1758 1759
      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
1760
      "BoolMapFieldKeyNotQuoted", RECOMMENDED,
1761 1762
      R"({"mapBoolBool": {true: true, false: false}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1763
      "MessageMapField", REQUIRED,
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
      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
1782
      "Int32MapEscapedKey", REQUIRED,
1783 1784 1785
      R"({"mapInt32Int32": {"\u0031": 2}})",
      "map_int32_int32: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1786
      "Int64MapEscapedKey", REQUIRED,
1787 1788 1789
      R"({"mapInt64Int64": {"\u0031": 2}})",
      "map_int64_int64: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1790
      "BoolMapEscapedKey", REQUIRED,
1791 1792 1793 1794 1795
      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
1796
      "AllFieldAcceptNull", REQUIRED,
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
      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
1824
      "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
1825 1826
      R"({"repeatedInt32": [1, null, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1827
      "RepeatedFieldMessageElementIsNull", RECOMMENDED,
1828 1829 1830
      R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  // Map field keys cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1831
      "MapFieldKeyIsNull", RECOMMENDED,
1832 1833 1834
      R"({"mapInt32Int32": {null: 1}})");
  // Map field values cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1835
      "MapFieldValueIsNull", RECOMMENDED,
1836 1837
      R"({"mapInt32Int32": {"0": null}})");

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

1850 1851
  // Wrapper types.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1852
      "OptionalBoolWrapper", REQUIRED,
1853 1854 1855
      R"({"optionalBoolWrapper": false})",
      "optional_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1856
      "OptionalInt32Wrapper", REQUIRED,
1857 1858 1859
      R"({"optionalInt32Wrapper": 0})",
      "optional_int32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1860
      "OptionalUint32Wrapper", REQUIRED,
1861 1862 1863
      R"({"optionalUint32Wrapper": 0})",
      "optional_uint32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1864
      "OptionalInt64Wrapper", REQUIRED,
1865 1866 1867
      R"({"optionalInt64Wrapper": 0})",
      "optional_int64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1868
      "OptionalUint64Wrapper", REQUIRED,
1869 1870 1871
      R"({"optionalUint64Wrapper": 0})",
      "optional_uint64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1872
      "OptionalFloatWrapper", REQUIRED,
1873 1874 1875
      R"({"optionalFloatWrapper": 0})",
      "optional_float_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1876
      "OptionalDoubleWrapper", REQUIRED,
1877 1878 1879
      R"({"optionalDoubleWrapper": 0})",
      "optional_double_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1880
      "OptionalStringWrapper", REQUIRED,
1881 1882 1883
      R"({"optionalStringWrapper": ""})",
      R"(optional_string_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1884
      "OptionalBytesWrapper", REQUIRED,
1885 1886 1887
      R"({"optionalBytesWrapper": ""})",
      R"(optional_bytes_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1888
      "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
      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
1912
      "RepeatedBoolWrapper", REQUIRED,
1913 1914 1915 1916
      R"({"repeatedBoolWrapper": [true, false]})",
      "repeated_bool_wrapper: {value: true}"
      "repeated_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1917
      "RepeatedInt32Wrapper", REQUIRED,
1918 1919 1920 1921
      R"({"repeatedInt32Wrapper": [0, 1]})",
      "repeated_int32_wrapper: {value: 0}"
      "repeated_int32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1922
      "RepeatedUint32Wrapper", REQUIRED,
1923 1924 1925 1926
      R"({"repeatedUint32Wrapper": [0, 1]})",
      "repeated_uint32_wrapper: {value: 0}"
      "repeated_uint32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1927
      "RepeatedInt64Wrapper", REQUIRED,
1928 1929 1930 1931
      R"({"repeatedInt64Wrapper": [0, 1]})",
      "repeated_int64_wrapper: {value: 0}"
      "repeated_int64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1932
      "RepeatedUint64Wrapper", REQUIRED,
1933 1934 1935 1936
      R"({"repeatedUint64Wrapper": [0, 1]})",
      "repeated_uint64_wrapper: {value: 0}"
      "repeated_uint64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1937
      "RepeatedFloatWrapper", REQUIRED,
1938 1939 1940 1941
      R"({"repeatedFloatWrapper": [0, 1]})",
      "repeated_float_wrapper: {value: 0}"
      "repeated_float_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1942
      "RepeatedDoubleWrapper", REQUIRED,
1943 1944 1945 1946
      R"({"repeatedDoubleWrapper": [0, 1]})",
      "repeated_double_wrapper: {value: 0}"
      "repeated_double_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1947
      "RepeatedStringWrapper", REQUIRED,
1948 1949 1950 1951 1952 1953
      R"({"repeatedStringWrapper": ["", "AQI="]})",
      R"(
        repeated_string_wrapper: {value: ""}
        repeated_string_wrapper: {value: "AQI="}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1954
      "RepeatedBytesWrapper", REQUIRED,
1955 1956 1957 1958 1959 1960
      R"({"repeatedBytesWrapper": ["", "AQI="]})",
      R"(
        repeated_bytes_wrapper: {value: ""}
        repeated_bytes_wrapper: {value: "\x01\x02"}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1961
      "WrapperTypesWithNullValue", REQUIRED,
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
      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
1986
      "DurationMinValue", REQUIRED,
1987 1988 1989
      R"({"optionalDuration": "-315576000000.999999999s"})",
      "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1990
      "DurationMaxValue", REQUIRED,
1991 1992 1993
      R"({"optionalDuration": "315576000000.999999999s"})",
      "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1994
      "DurationRepeatedValue", REQUIRED,
1995 1996 1997 1998 1999
      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
2000
      "DurationMissingS", REQUIRED,
2001 2002
      R"({"optionalDuration": "1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2003
      "DurationJsonInputTooSmall", REQUIRED,
2004 2005
      R"({"optionalDuration": "-315576000001.000000000s"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2006
      "DurationJsonInputTooLarge", REQUIRED,
2007 2008
      R"({"optionalDuration": "315576000001.000000000s"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2009
      "DurationProtoInputTooSmall", REQUIRED,
2010 2011
      "optional_duration: {seconds: -315576000001 nanos: 0}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2012
      "DurationProtoInputTooLarge", REQUIRED,
2013 2014 2015
      "optional_duration: {seconds: 315576000001 nanos: 0}");

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

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

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2069
      "TimestampJsonInputTooSmall", REQUIRED,
2070 2071
      R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2072
      "TimestampJsonInputTooLarge", REQUIRED,
2073 2074
      R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2075
      "TimestampJsonInputMissingZ", REQUIRED,
2076 2077
      R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2078
      "TimestampJsonInputMissingT", REQUIRED,
2079 2080
      R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2081
      "TimestampJsonInputLowercaseZ", REQUIRED,
2082 2083
      R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2084
      "TimestampJsonInputLowercaseT", REQUIRED,
2085 2086
      R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2087
      "TimestampProtoInputTooSmall", REQUIRED,
2088 2089
      "optional_timestamp: {seconds: -62135596801}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2090
      "TimestampProtoInputTooLarge", REQUIRED,
2091 2092
      "optional_timestamp: {seconds: 253402300800}");
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2093
      "TimestampZeroNormalized", RECOMMENDED,
2094 2095 2096 2097 2098 2099
      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
2100
      "TimestampHasZeroFractionalDigit", RECOMMENDED,
2101 2102 2103 2104 2105 2106
      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
2107
      "TimestampHas3FractionalDigits", RECOMMENDED,
2108 2109 2110 2111 2112 2113
      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
2114
      "TimestampHas6FractionalDigits", RECOMMENDED,
2115 2116 2117 2118 2119 2120
      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
2121
      "TimestampHas9FractionalDigits", RECOMMENDED,
2122 2123 2124 2125 2126 2127 2128 2129
      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
2130
      "FieldMask", REQUIRED,
2131 2132 2133
      R"({"optionalFieldMask": "foo,barBaz"})",
      R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2134
      "FieldMaskInvalidCharacter", RECOMMENDED,
2135 2136
      R"({"optionalFieldMask": "foo,bar_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2137
      "FieldMaskPathsDontRoundTrip", RECOMMENDED,
2138 2139
      R"(optional_field_mask: {paths: "fooBar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2140
      "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
2141 2142
      R"(optional_field_mask: {paths: "foo_3_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2143
      "FieldMaskTooManyUnderscore", RECOMMENDED,
2144 2145 2146 2147
      R"(optional_field_mask: {paths: "foo__bar"})");

  // Struct
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2148
      "Struct", REQUIRED,
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
      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
2214
      "ValueAcceptInteger", REQUIRED,
2215 2216 2217
      R"({"optionalValue": 1})",
      "optional_value: { number_value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2218
      "ValueAcceptFloat", REQUIRED,
2219 2220 2221
      R"({"optionalValue": 1.5})",
      "optional_value: { number_value: 1.5}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2222
      "ValueAcceptBool", REQUIRED,
2223 2224 2225
      R"({"optionalValue": false})",
      "optional_value: { bool_value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2226
      "ValueAcceptNull", REQUIRED,
2227 2228 2229
      R"({"optionalValue": null})",
      "optional_value: { null_value: NULL_VALUE}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2230
      "ValueAcceptString", REQUIRED,
2231 2232 2233
      R"({"optionalValue": "hello"})",
      R"(optional_value: { string_value: "hello"})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2234
      "ValueAcceptList", REQUIRED,
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
      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
2249
      "ValueAcceptObject", REQUIRED,
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
      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
2266
      "Any", REQUIRED,
2267 2268
      R"({
        "optionalAny": {
Jisi Liu's avatar
Jisi Liu committed
2269
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2270 2271 2272 2273 2274
          "optionalInt32": 12345
        }
      })",
      R"(
        optional_any: {
Jisi Liu's avatar
Jisi Liu committed
2275
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2276 2277 2278 2279 2280
            optional_int32: 12345
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2281
      "AnyNested", REQUIRED,
2282 2283 2284 2285
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Any",
          "value": {
Jisi Liu's avatar
Jisi Liu committed
2286
            "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2287 2288 2289 2290 2291 2292 2293
            "optionalInt32": 12345
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Any] {
Jisi Liu's avatar
Jisi Liu committed
2294
            [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2295 2296 2297 2298 2299 2300 2301
              optional_int32: 12345
            }
          }
        }
      )");
  // The special "@type" tag is not required to appear first.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2302
      "AnyUnorderedTypeTag", REQUIRED,
2303 2304 2305
      R"({
        "optionalAny": {
          "optionalInt32": 12345,
Jisi Liu's avatar
Jisi Liu committed
2306
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
2307 2308 2309 2310
        }
      })",
      R"(
        optional_any: {
Jisi Liu's avatar
Jisi Liu committed
2311
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2312 2313 2314 2315 2316 2317
            optional_int32: 12345
          }
        }
      )");
  // Well-known types in Any.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2318
      "AnyWithInt32ValueWrapper", REQUIRED,
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
      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
2333
      "AnyWithDuration", REQUIRED,
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
      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
2349
      "AnyWithTimestamp", REQUIRED,
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
      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
2365
      "AnyWithFieldMask", REQUIRED,
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
      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
2380
      "AnyWithStruct", REQUIRED,
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
      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
2402
      "AnyWithValueForJsonObject", REQUIRED,
2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
      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
2426
      "AnyWithValueForInteger", REQUIRED,
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
      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;
2442
  if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
2443
                     "These tests were listed in the failure list, but they "
2444 2445 2446 2447
                     "don't exist.  Remove them from the failure list by "
                     "running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --remove nonexistent_tests.txt")) {
2448 2449
    ok = false;
  }
2450
  if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
2451 2452
                     "These tests failed.  If they can't be fixed right now, "
                     "you can add them to the failure list so the overall "
2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
                     "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")) {
2465 2466
    ok = false;
  }
2467

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

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

2481
  output->assign(output_);
2482 2483

  return ok;
2484
}
2485 2486 2487

}  // namespace protobuf
}  // namespace google