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

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

#include "conformance.pb.h"
36
#include "conformance_test.h"
37
#include <google/protobuf/test_messages_proto3.pb.h>
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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  const string equivalent_wire_format = reference_message->SerializeAsString();
  RunValidBinaryInputTest(test_name, level, input, input_format,
                          equivalent_wire_format, requested_output, isProto3);
}

void ConformanceTestSuite::RunValidBinaryInputTest(
    const string& test_name, ConformanceLevel level, const string& input,
    WireFormat input_format, const string& equivalent_wire_format,
    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();
  GOOGLE_CHECK(
      reference_message->ParseFromString(equivalent_wire_format))
          << "Failed to parse wire data for test case: " << test_name;
315 316 317 318 319

  ConformanceRequest request;
  ConformanceResponse response;

  switch (input_format) {
Jisi Liu's avatar
Jisi Liu committed
320
    case conformance::PROTOBUF: {
321
      request.set_protobuf_payload(input);
Jisi Liu's avatar
Jisi Liu committed
322 323 324 325 326
      if (isProto3) {
        request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
      } else {
        request.set_message_type("protobuf_test_messages.proto2.TestAllTypesProto2");
      }
327
      break;
Jisi Liu's avatar
Jisi Liu committed
328
    }
329

Jisi Liu's avatar
Jisi Liu committed
330 331
    case conformance::JSON: {
      request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
332 333
      request.set_json_payload(input);
      break;
Jisi Liu's avatar
Jisi Liu committed
334
    }
335

336
    default:
337 338 339 340 341 342 343
      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
344
  Message *test_message = newTestMessage();
345 346

  switch (response.result_case()) {
347
    case ConformanceResponse::RESULT_NOT_SET:
348
      ReportFailure(test_name, level, request, response,
349 350 351
                    "Response didn't have any field in the Response.");
      return;

352 353
    case ConformanceResponse::kParseError:
    case ConformanceResponse::kRuntimeError:
354
    case ConformanceResponse::kSerializeError:
355
      ReportFailure(test_name, level, request, response,
356
                    "Failed to parse input or produce output.");
357 358 359 360 361 362 363 364 365
      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
366
            test_name, level, request, response,
367 368 369 370 371 372 373 374
            "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
375
        ReportFailure(test_name, level, request, response,
376 377 378 379
                      "JSON output we received from test was unparseable.");
        return;
      }

Jisi Liu's avatar
Jisi Liu committed
380
      if (!test_message->ParseFromString(binary_protobuf)) {
Bo Yang's avatar
Bo Yang committed
381
        ReportFailure(test_name, level, request, response,
Jisi Liu's avatar
Jisi Liu committed
382 383
                    "INTERNAL ERROR: internal JSON->protobuf transcode "
                    "yielded unparseable proto.");
384 385 386
        return;
      }

387 388 389 390 391 392
      break;
    }

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

Jisi Liu's avatar
Jisi Liu committed
398
      if (!test_message->ParseFromString(response.protobuf_payload())) {
Bo Yang's avatar
Bo Yang committed
399
        ReportFailure(test_name, level, request, response,
Jisi Liu's avatar
Jisi Liu committed
400
                   "Protobuf output we received from test was unparseable.");
401 402 403 404 405
        return;
      }

      break;
    }
406 407 408 409

    default:
      GOOGLE_LOG(FATAL) << test_name << ": unknown payload type: "
                        << response.result_case();
410 411 412
  }

  MessageDifferencer differencer;
413 414 415
  DefaultFieldComparator field_comparator;
  field_comparator.set_treat_nan_as_equal(true);
  differencer.set_field_comparator(&field_comparator);
416 417 418
  string differences;
  differencer.ReportDifferencesToString(&differences);

Jisi Liu's avatar
Jisi Liu committed
419 420 421
  bool check;
  check = differencer.Compare(*reference_message, *test_message);
  if (check) {
422 423
    ReportSuccess(test_name);
  } else {
Bo Yang's avatar
Bo Yang committed
424
    ReportFailure(test_name, level, request, response,
425 426 427 428
                  "Output was not equivalent to reference message: %s.",
                  differences.c_str());
  }
}
Jisi Liu's avatar
Jisi Liu committed
429 430 431
void ConformanceTestSuite::ExpectParseFailureForProtoWithProtoVersion (
    const string& proto, const string& test_name, ConformanceLevel level,
    bool isProto3) {
432 433 434
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_protobuf_payload(proto);
Jisi Liu's avatar
Jisi Liu committed
435 436 437 438 439
  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
440
  string effective_test_name = ConformanceLevelToString(level) +
Jisi Liu's avatar
Jisi Liu committed
441
      (isProto3 ? ".Proto3" : ".Proto2") +
Bo Yang's avatar
Bo Yang committed
442
      ".ProtobufInput." + test_name;
443 444 445

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

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

Jisi Liu's avatar
Jisi Liu committed
459 460 461 462 463 464 465
// 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);
}

466 467 468 469 470
// 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.
471
void ConformanceTestSuite::ExpectHardParseFailureForProto(
Bo Yang's avatar
Bo Yang committed
472 473
    const string& proto, const string& test_name, ConformanceLevel level) {
  return ExpectParseFailureForProto(proto, test_name, level);
474
}
475

476
void ConformanceTestSuite::RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
477
    const string& test_name, ConformanceLevel level, const string& input_json,
478
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
479
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
480
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
Bo Yang's avatar
Bo Yang committed
481
      ".ProtobufOutput", level, input_json, conformance::JSON,
Jisi Liu's avatar
Jisi Liu committed
482
      equivalent_text_format, conformance::PROTOBUF, true);
Bo Yang's avatar
Bo Yang committed
483
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
484
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name +
Bo Yang's avatar
Bo Yang committed
485
      ".JsonOutput", level, input_json, conformance::JSON,
Jisi Liu's avatar
Jisi Liu committed
486
      equivalent_text_format, conformance::JSON, true);
487 488 489
}

void ConformanceTestSuite::RunValidJsonTestWithProtobufInput(
Jisi Liu's avatar
Jisi Liu committed
490
    const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input,
491
    const string& equivalent_text_format) {
Bo Yang's avatar
Bo Yang committed
492
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
493
      ConformanceLevelToString(level) + ".Proto3" + ".ProtobufInput." + test_name +
Bo Yang's avatar
Bo Yang committed
494
      ".JsonOutput", level, input.SerializeAsString(), conformance::PROTOBUF,
Jisi Liu's avatar
Jisi Liu committed
495
      equivalent_text_format, conformance::JSON, true);
496 497
}

498
void ConformanceTestSuite::RunValidProtobufTest(
499
    const string& test_name, ConformanceLevel level,
Jisi Liu's avatar
Jisi Liu committed
500 501 502 503 504 505
    const string& input_protobuf, const string& equivalent_text_format,
    bool isProto3) {
  string rname = ".Proto3";
  if (!isProto3) {
    rname = ".Proto2";
  }
506
  RunValidInputTest(
Jisi Liu's avatar
Jisi Liu committed
507
      ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
508
      ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
Jisi Liu's avatar
Jisi Liu committed
509 510 511 512 513 514 515
      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);
  }
516 517
}

518 519 520 521 522 523 524 525 526 527 528 529 530
void ConformanceTestSuite::RunValidBinaryProtobufTest(
    const string& test_name, ConformanceLevel level,
    const string& input_protobuf, bool isProto3) {
  string rname = ".Proto3";
  if (!isProto3) {
    rname = ".Proto2";
  }
  RunValidBinaryInputTest(
      ConformanceLevelToString(level) + rname + ".ProtobufInput." + test_name +
      ".ProtobufOutput", level, input_protobuf, conformance::PROTOBUF,
      input_protobuf, conformance::PROTOBUF, isProto3);
}

531
void ConformanceTestSuite::RunValidProtobufTestWithMessage(
Jisi Liu's avatar
Jisi Liu committed
532 533 534
    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);
535 536
}

537 538 539 540 541 542
// 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
543
    const string& test_name, ConformanceLevel level, const string& input_json,
544 545 546 547 548
    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
549
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
550

Bo Yang's avatar
Bo Yang committed
551
  string effective_test_name = ConformanceLevelToString(level) +
Jisi Liu's avatar
Jisi Liu committed
552
      ".Proto3.JsonInput." + test_name + ".Validator";
553 554 555

  RunTest(effective_test_name, request, &response);

556 557 558 559 560
  if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
    return;
  }

561
  if (response.result_case() != ConformanceResponse::kJsonPayload) {
Bo Yang's avatar
Bo Yang committed
562
    ReportFailure(effective_test_name, level, request, response,
563 564 565 566 567 568 569
                  "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
570
    ReportFailure(effective_test_name, level, request, response,
571 572 573 574 575
                  "JSON payload cannot be parsed as valid JSON: %s",
                  reader.getFormattedErrorMessages().c_str());
    return;
  }
  if (!validator(value)) {
Bo Yang's avatar
Bo Yang committed
576
    ReportFailure(effective_test_name, level, request, response,
577 578 579 580 581 582 583
                  "JSON payload validation failed.");
    return;
  }
  ReportSuccess(effective_test_name);
}

void ConformanceTestSuite::ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
584
    const string& test_name, ConformanceLevel level, const string& input_json) {
585 586 587
  ConformanceRequest request;
  ConformanceResponse response;
  request.set_json_payload(input_json);
Jisi Liu's avatar
Jisi Liu committed
588
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
Bo Yang's avatar
Bo Yang committed
589
  string effective_test_name =
Jisi Liu's avatar
Jisi Liu committed
590
      ConformanceLevelToString(level) + ".Proto3.JsonInput." + test_name;
591 592 593 594 595 596 597 598

  // 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);
599 600
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
601
  } else {
Bo Yang's avatar
Bo Yang committed
602
    ReportFailure(effective_test_name, level, request, response,
603 604 605 606 607
                  "Should have failed to parse, but didn't.");
  }
}

void ConformanceTestSuite::ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
608
    const string& test_name, ConformanceLevel level, const string& text_format) {
Jisi Liu's avatar
Jisi Liu committed
609
  TestAllTypesProto3 payload_message;
610 611 612 613 614 615 616
  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
617
  request.set_message_type("protobuf_test_messages.proto3.TestAllTypesProto3");
Bo Yang's avatar
Bo Yang committed
618 619
  string effective_test_name =
      ConformanceLevelToString(level) + "." + test_name + ".JsonOutput";
620 621 622 623 624
  request.set_requested_output_format(conformance::JSON);

  RunTest(effective_test_name, request, &response);
  if (response.result_case() == ConformanceResponse::kSerializeError) {
    ReportSuccess(effective_test_name);
625 626
  } else if (response.result_case() == ConformanceResponse::kSkipped) {
    ReportSkip(effective_test_name, request, response);
627
  } else {
Bo Yang's avatar
Bo Yang committed
628
    ReportFailure(effective_test_name, level, request, response,
629 630 631 632
                  "Should have failed to serialize, but didn't.");
  }
}

Jisi Liu's avatar
Jisi Liu committed
633
//TODO: proto2?
634
void ConformanceTestSuite::TestPrematureEOFForType(FieldDescriptor::Type type) {
635 636 637 638 639 640 641 642 643 644
  // 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
645 646
  const FieldDescriptor* field = GetFieldForType(type, false, true);
  const FieldDescriptor* rep_field = GetFieldForType(type, true, true);
647 648
  WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType(
      static_cast<WireFormatLite::FieldType>(type));
649
  const string& incomplete = incompletes[wire_type];
650 651
  const string type_name =
      UpperCase(string(".") + FieldDescriptor::TypeName(type));
652

653
  ExpectParseFailureForProto(
654
      tag(field->number(), wire_type),
Bo Yang's avatar
Bo Yang committed
655
      "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED);
656

657
  ExpectParseFailureForProto(
658
      tag(rep_field->number(), wire_type),
Bo Yang's avatar
Bo Yang committed
659
      "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED);
660

661 662
  ExpectParseFailureForProto(
      tag(UNKNOWN_FIELD, wire_type),
Bo Yang's avatar
Bo Yang committed
663
      "PrematureEofBeforeUnknownValue" + type_name, REQUIRED);
664 665

  ExpectParseFailureForProto(
666
      cat( tag(field->number(), wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
667
      "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED);
668 669

  ExpectParseFailureForProto(
670
      cat( tag(rep_field->number(), wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
671
      "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED);
672 673

  ExpectParseFailureForProto(
674
      cat( tag(UNKNOWN_FIELD, wire_type), incomplete ),
Bo Yang's avatar
Bo Yang committed
675
      "PrematureEofInsideUnknownValue" + type_name, REQUIRED);
676 677 678

  if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
    ExpectParseFailureForProto(
679
        cat( tag(field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
680 681
        "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name,
        REQUIRED);
682 683

    ExpectParseFailureForProto(
684
        cat( tag(rep_field->number(), wire_type), varint(1) ),
Bo Yang's avatar
Bo Yang committed
685 686
        "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name,
        REQUIRED);
687 688 689

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

693
    if (type == FieldDescriptor::TYPE_MESSAGE) {
694 695 696 697 698
      // Submessage ends in the middle of a value.
      string incomplete_submsg =
          cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT),
                incompletes[WireFormatLite::WIRETYPE_VARINT] );
      ExpectHardParseFailureForProto(
699
          cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
700
               varint(incomplete_submsg.size()),
701
               incomplete_submsg ),
Bo Yang's avatar
Bo Yang committed
702
          "PrematureEofInSubmessageValue" + type_name, REQUIRED);
703
    }
704
  } else if (type != FieldDescriptor::TYPE_GROUP) {
705 706 707 708
    // Non-delimited, non-group: eligible for packing.

    // Packed region ends in the middle of a value.
    ExpectHardParseFailureForProto(
709 710
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(incomplete.size()), incomplete),
Bo Yang's avatar
Bo Yang committed
711
        "PrematureEofInPackedFieldValue" + type_name, REQUIRED);
712 713 714

    // EOF in the middle of packed region.
    ExpectParseFailureForProto(
715 716
        cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED),
            varint(1)),
Bo Yang's avatar
Bo Yang committed
717
        "PrematureEofInPackedField" + type_name, REQUIRED);
718 719 720
  }
}

721 722 723
void ConformanceTestSuite::TestValidDataForType(
    FieldDescriptor::Type type,
    std::vector<std::pair<std::string, std::string>> values) {
Jisi Liu's avatar
Jisi Liu committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
  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);
743

Jisi Liu's avatar
Jisi Liu committed
744 745
    proto.clear();
    text.clear();
746

Jisi Liu's avatar
Jisi Liu committed
747 748 749 750 751 752
    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);
753 754 755
  }
}

756
void ConformanceTestSuite::SetFailureList(const string& filename,
757
                                          const std::vector<string>& failure_list) {
758
  failure_list_filename_ = filename;
759 760 761 762 763
  expected_to_fail_.clear();
  std::copy(failure_list.begin(), failure_list.end(),
            std::inserter(expected_to_fail_, expected_to_fail_.end()));
}

764
bool ConformanceTestSuite::CheckSetEmpty(const std::set<string>& set_to_check,
765 766
                                         const std::string& write_to_file,
                                         const std::string& msg) {
767 768 769 770
  if (set_to_check.empty()) {
    return true;
  } else {
    StringAppendF(&output_, "\n");
771
    StringAppendF(&output_, "%s\n\n", msg.c_str());
772
    for (std::set<string>::const_iterator iter = set_to_check.begin();
773
         iter != set_to_check.end(); ++iter) {
774
      StringAppendF(&output_, "  %s\n", iter->c_str());
775
    }
776
    StringAppendF(&output_, "\n");
777 778 779 780

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

791 792 793 794
    return false;
  }
}

Jisi Liu's avatar
Jisi Liu committed
795
// TODO: proto2?
796 797 798 799 800 801 802 803 804 805 806 807 808 809
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
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
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);
}
848

849 850 851 852 853 854 855 856
template <class MessageType>
void ConformanceTestSuite::TestUnknownMessage(MessageType& message,
                                              bool isProto3) {
  message.ParseFromString("\xA8\x1F\x01");
  RunValidBinaryProtobufTest("UnknownVarint", REQUIRED,
                             message.SerializeAsString(), isProto3);
}

857
bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner,
858 859 860
                                    std::string* output) {
  runner_ = runner;
  successes_ = 0;
861 862
  expected_failures_ = 0;
  skipped_.clear();
863 864 865
  test_names_.clear();
  unexpected_failing_tests_.clear();
  unexpected_succeeding_tests_.clear();
866 867
  type_resolver_.reset(NewTypeResolverForDescriptorPool(
      kTypeUrlPrefix, DescriptorPool::generated_pool()));
Jisi Liu's avatar
Jisi Liu committed
868
  type_url_ = GetTypeUrl(TestAllTypesProto3::descriptor());
869 870

  output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n";
871 872

  for (int i = 1; i <= FieldDescriptor::MAX_TYPE; i++) {
873
    if (i == FieldDescriptor::TYPE_GROUP) continue;
874
    TestPrematureEOFForType(static_cast<FieldDescriptor::Type>(i));
875 876
  }

877 878
  TestIllegalTags();

879 880 881 882 883 884 885 886 887 888 889 890 891 892
  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"},
893
    {flt(1.00000075e-36), "1.00000075e-36"},
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    {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"},
909 910
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
911 912
    {varint(kInt32Max), std::to_string(kInt32Max)},
    {varint(kInt32Min), std::to_string(kInt32Min)},
913 914 915
    {varint(1LL << 33), std::to_string(static_cast<int32>(1LL << 33))},
    {varint((1LL << 33) - 1),
     std::to_string(static_cast<int32>((1LL << 33) - 1))},
916 917 918
  });
  TestValidDataForType(FieldDescriptor::TYPE_UINT32, {
    {varint(12345), "12345"},
919 920
    {longvarint(12345, 2), "12345"},
    {longvarint(12345, 7), "12345"},
921
    {varint(kUint32Max), std::to_string(kUint32Max)},  // UINT32_MAX
922 923 924 925
    {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))},
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
  });
  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
970 971
  RunValidJsonTest("HelloWorld", REQUIRED,
                   "{\"optionalString\":\"Hello, World!\"}",
972
                   "optional_string: 'Hello, World!'");
973

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

  // Integer fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1234
      "Int32FieldMaxValue", REQUIRED,
1235 1236 1237
      R"({"optionalInt32": 2147483647})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1238
      "Int32FieldMinValue", REQUIRED,
1239 1240 1241
      R"({"optionalInt32": -2147483648})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1242
      "Uint32FieldMaxValue", REQUIRED,
1243 1244 1245
      R"({"optionalUint32": 4294967295})",
      "optional_uint32: 4294967295");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1246
      "Int64FieldMaxValue", REQUIRED,
1247 1248 1249
      R"({"optionalInt64": "9223372036854775807"})",
      "optional_int64: 9223372036854775807");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1250
      "Int64FieldMinValue", REQUIRED,
1251 1252 1253
      R"({"optionalInt64": "-9223372036854775808"})",
      "optional_int64: -9223372036854775808");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1254
      "Uint64FieldMaxValue", REQUIRED,
1255 1256
      R"({"optionalUint64": "18446744073709551615"})",
      "optional_uint64: 18446744073709551615");
1257 1258 1259 1260 1261 1262
  // 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.
1263
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1264
      "Int64FieldMaxValueNotQuoted", REQUIRED,
1265 1266
      R"({"optionalInt64": 9223372036854774784})",
      "optional_int64: 9223372036854774784");
1267
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1268
      "Int64FieldMinValueNotQuoted", REQUIRED,
1269 1270
      R"({"optionalInt64": -9223372036854775808})",
      "optional_int64: -9223372036854775808");
1271 1272
  // Largest interoperable Uint64; see comment above
  // for Int64FieldMaxValueNotQuoted.
1273
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1274
      "Uint64FieldMaxValueNotQuoted", REQUIRED,
1275 1276
      R"({"optionalUint64": 18446744073709549568})",
      "optional_uint64: 18446744073709549568");
1277 1278
  // Values can be represented as JSON strings.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1279
      "Int32FieldStringValue", REQUIRED,
1280 1281 1282
      R"({"optionalInt32": "2147483647"})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1283
      "Int32FieldStringValueEscaped", REQUIRED,
1284 1285 1286 1287 1288
      R"({"optionalInt32": "2\u003147483647"})",
      "optional_int32: 2147483647");

  // Parsers reject out-of-bound integer values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1289
      "Int32FieldTooLarge", REQUIRED,
1290 1291
      R"({"optionalInt32": 2147483648})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1292
      "Int32FieldTooSmall", REQUIRED,
1293 1294
      R"({"optionalInt32": -2147483649})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1295
      "Uint32FieldTooLarge", REQUIRED,
1296 1297
      R"({"optionalUint32": 4294967296})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1298
      "Int64FieldTooLarge", REQUIRED,
1299 1300
      R"({"optionalInt64": "9223372036854775808"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1301
      "Int64FieldTooSmall", REQUIRED,
1302 1303
      R"({"optionalInt64": "-9223372036854775809"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1304
      "Uint64FieldTooLarge", REQUIRED,
1305 1306 1307
      R"({"optionalUint64": "18446744073709551616"})");
  // Parser reject non-integer numeric values as well.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1308
      "Int32FieldNotInteger", REQUIRED,
1309 1310
      R"({"optionalInt32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1311
      "Uint32FieldNotInteger", REQUIRED,
1312 1313
      R"({"optionalUint32": 0.5})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1314
      "Int64FieldNotInteger", REQUIRED,
1315 1316
      R"({"optionalInt64": "0.5"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1317
      "Uint64FieldNotInteger", REQUIRED,
1318 1319 1320 1321
      R"({"optionalUint64": "0.5"})");

  // Integers but represented as float values are accepted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1322
      "Int32FieldFloatTrailingZero", REQUIRED,
1323 1324 1325
      R"({"optionalInt32": 100000.000})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1326
      "Int32FieldExponentialFormat", REQUIRED,
1327 1328 1329
      R"({"optionalInt32": 1e5})",
      "optional_int32: 100000");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1330
      "Int32FieldMaxFloatValue", REQUIRED,
1331 1332 1333
      R"({"optionalInt32": 2.147483647e9})",
      "optional_int32: 2147483647");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1334
      "Int32FieldMinFloatValue", REQUIRED,
1335 1336 1337
      R"({"optionalInt32": -2.147483648e9})",
      "optional_int32: -2147483648");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1338
      "Uint32FieldMaxFloatValue", REQUIRED,
1339 1340 1341 1342 1343
      R"({"optionalUint32": 4.294967295e9})",
      "optional_uint32: 4294967295");

  // Parser reject non-numeric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1344
      "Int32FieldNotNumber", REQUIRED,
1345 1346
      R"({"optionalInt32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1347
      "Uint32FieldNotNumber", REQUIRED,
1348 1349
      R"({"optionalUint32": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1350
      "Int64FieldNotNumber", REQUIRED,
1351 1352
      R"({"optionalInt64": "3x3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1353
      "Uint64FieldNotNumber", REQUIRED,
1354 1355 1356
      R"({"optionalUint64": "3x3"})");
  // JSON does not allow "+" on numric values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1357
      "Int32FieldPlusSign", REQUIRED,
1358 1359 1360
      R"({"optionalInt32": +1})");
  // JSON doesn't allow leading 0s.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1361
      "Int32FieldLeadingZero", REQUIRED,
1362 1363
      R"({"optionalInt32": 01})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1364
      "Int32FieldNegativeWithLeadingZero", REQUIRED,
1365 1366
      R"({"optionalInt32": -01})");
  // String values must follow the same syntax rule. Specifically leading
1367
  // or trailing spaces are not allowed.
1368
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1369
      "Int32FieldLeadingSpace", REQUIRED,
1370 1371
      R"({"optionalInt32": " 1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1372
      "Int32FieldTrailingSpace", REQUIRED,
1373 1374 1375 1376
      R"({"optionalInt32": "1 "})");

  // 64-bit values are serialized as strings.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1377
      "Int64FieldBeString", RECOMMENDED,
1378 1379 1380 1381 1382 1383
      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
1384
      "Uint64FieldBeString", RECOMMENDED,
1385 1386 1387 1388 1389 1390 1391 1392
      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
1393
      "BoolFieldTrue", REQUIRED,
1394 1395 1396
      R"({"optionalBool":true})",
      "optional_bool: true");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1397
      "BoolFieldFalse", REQUIRED,
1398 1399 1400 1401 1402
      R"({"optionalBool":false})",
      "optional_bool: false");

  // Other forms are not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1403
      "BoolFieldIntegerZero", RECOMMENDED,
1404 1405
      R"({"optionalBool":0})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1406
      "BoolFieldIntegerOne", RECOMMENDED,
1407 1408
      R"({"optionalBool":1})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1409
      "BoolFieldCamelCaseTrue", RECOMMENDED,
1410 1411
      R"({"optionalBool":True})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1412
      "BoolFieldCamelCaseFalse", RECOMMENDED,
1413 1414
      R"({"optionalBool":False})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1415
      "BoolFieldAllCapitalTrue", RECOMMENDED,
1416 1417
      R"({"optionalBool":TRUE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1418
      "BoolFieldAllCapitalFalse", RECOMMENDED,
1419 1420
      R"({"optionalBool":FALSE})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1421
      "BoolFieldDoubleQuotedTrue", RECOMMENDED,
1422 1423
      R"({"optionalBool":"true"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1424
      "BoolFieldDoubleQuotedFalse", RECOMMENDED,
1425 1426 1427 1428
      R"({"optionalBool":"false"})");

  // Float fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1429
      "FloatFieldMinPositiveValue", REQUIRED,
1430 1431 1432
      R"({"optionalFloat": 1.175494e-38})",
      "optional_float: 1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1433
      "FloatFieldMaxNegativeValue", REQUIRED,
1434 1435 1436
      R"({"optionalFloat": -1.175494e-38})",
      "optional_float: -1.175494e-38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1437
      "FloatFieldMaxPositiveValue", REQUIRED,
1438 1439 1440
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1441
      "FloatFieldMinNegativeValue", REQUIRED,
1442 1443 1444 1445
      R"({"optionalFloat": 3.402823e+38})",
      "optional_float: 3.402823e+38");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1446
      "FloatFieldQuotedValue", REQUIRED,
1447 1448 1449 1450
      R"({"optionalFloat": "1"})",
      "optional_float: 1");
  // Special values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1451
      "FloatFieldNan", REQUIRED,
1452 1453 1454
      R"({"optionalFloat": "NaN"})",
      "optional_float: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1455
      "FloatFieldInfinity", REQUIRED,
1456 1457 1458
      R"({"optionalFloat": "Infinity"})",
      "optional_float: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1459
      "FloatFieldNegativeInfinity", REQUIRED,
1460 1461 1462 1463
      R"({"optionalFloat": "-Infinity"})",
      "optional_float: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
Jisi Liu's avatar
Jisi Liu committed
1464
    TestAllTypesProto3 message;
1465 1466 1467 1468 1469
    // 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
1470
        "FloatFieldNormalizeQuietNan", REQUIRED, message,
1471 1472 1473 1474 1475 1476
        "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
1477
        "FloatFieldNormalizeSignalingNan", REQUIRED, message,
1478 1479
        "optional_float: nan");
  }
1480

1481 1482
  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1483
      "FloatFieldNanNotQuoted", RECOMMENDED,
1484 1485
      R"({"optionalFloat": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1486
      "FloatFieldInfinityNotQuoted", RECOMMENDED,
1487 1488
      R"({"optionalFloat": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1489
      "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED,
1490 1491 1492
      R"({"optionalFloat": -Infinity})");
  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1493
      "FloatFieldTooSmall", REQUIRED,
1494 1495
      R"({"optionalFloat": -3.502823e+38})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1496
      "FloatFieldTooLarge", REQUIRED,
1497 1498 1499 1500
      R"({"optionalFloat": 3.502823e+38})");

  // Double fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1501
      "DoubleFieldMinPositiveValue", REQUIRED,
1502 1503 1504
      R"({"optionalDouble": 2.22507e-308})",
      "optional_double: 2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1505
      "DoubleFieldMaxNegativeValue", REQUIRED,
1506 1507 1508
      R"({"optionalDouble": -2.22507e-308})",
      "optional_double: -2.22507e-308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1509
      "DoubleFieldMaxPositiveValue", REQUIRED,
1510 1511 1512
      R"({"optionalDouble": 1.79769e+308})",
      "optional_double: 1.79769e+308");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1513
      "DoubleFieldMinNegativeValue", REQUIRED,
1514 1515 1516 1517
      R"({"optionalDouble": -1.79769e+308})",
      "optional_double: -1.79769e+308");
  // Values can be quoted.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1518
      "DoubleFieldQuotedValue", REQUIRED,
1519 1520 1521 1522
      R"({"optionalDouble": "1"})",
      "optional_double: 1");
  // Speical values.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1523
      "DoubleFieldNan", REQUIRED,
1524 1525 1526
      R"({"optionalDouble": "NaN"})",
      "optional_double: nan");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1527
      "DoubleFieldInfinity", REQUIRED,
1528 1529 1530
      R"({"optionalDouble": "Infinity"})",
      "optional_double: inf");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1531
      "DoubleFieldNegativeInfinity", REQUIRED,
1532 1533 1534 1535
      R"({"optionalDouble": "-Infinity"})",
      "optional_double: -inf");
  // Non-cannonical Nan will be correctly normalized.
  {
Jisi Liu's avatar
Jisi Liu committed
1536
    TestAllTypesProto3 message;
1537 1538 1539
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0x7FFA123456789ABCLL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1540
        "DoubleFieldNormalizeQuietNan", REQUIRED, message,
1541 1542 1543 1544
        "optional_double: nan");
    message.set_optional_double(
        WireFormatLite::DecodeDouble(0xFFFBCBA987654321LL));
    RunValidJsonTestWithProtobufInput(
Bo Yang's avatar
Bo Yang committed
1545
        "DoubleFieldNormalizeSignalingNan", REQUIRED, message,
1546 1547 1548 1549 1550
        "optional_double: nan");
  }

  // Special values must be quoted.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1551
      "DoubleFieldNanNotQuoted", RECOMMENDED,
1552 1553
      R"({"optionalDouble": NaN})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1554
      "DoubleFieldInfinityNotQuoted", RECOMMENDED,
1555 1556
      R"({"optionalDouble": Infinity})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1557
      "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED,
1558 1559 1560 1561
      R"({"optionalDouble": -Infinity})");

  // Parsers should reject out-of-bound values.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1562
      "DoubleFieldTooSmall", REQUIRED,
1563 1564
      R"({"optionalDouble": -1.89769e+308})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1565
      "DoubleFieldTooLarge", REQUIRED,
1566 1567 1568 1569
      R"({"optionalDouble": +1.89769e+308})");

  // Enum fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1570
      "EnumField", REQUIRED,
1571 1572 1573 1574
      R"({"optionalNestedEnum": "FOO"})",
      "optional_nested_enum: FOO");
  // Enum values must be represented as strings.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1575
      "EnumFieldNotQuoted", REQUIRED,
1576 1577 1578
      R"({"optionalNestedEnum": FOO})");
  // Numeric values are allowed.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1579
      "EnumFieldNumericValueZero", REQUIRED,
1580 1581 1582
      R"({"optionalNestedEnum": 0})",
      "optional_nested_enum: FOO");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1583
      "EnumFieldNumericValueNonZero", REQUIRED,
1584 1585 1586 1587
      R"({"optionalNestedEnum": 1})",
      "optional_nested_enum: BAR");
  // Unknown enum values are represented as numeric values.
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
1588
      "EnumFieldUnknownValue", REQUIRED,
1589 1590 1591 1592 1593 1594 1595 1596
      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
1597
      "StringField", REQUIRED,
1598 1599 1600
      R"({"optionalString": "Hello world!"})",
      "optional_string: \"Hello world!\"");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1601
      "StringFieldUnicode", REQUIRED,
1602 1603 1604 1605
      // Google in Chinese.
      R"({"optionalString": "谷歌"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1606
      "StringFieldEscape", REQUIRED,
1607 1608 1609
      R"({"optionalString": "\"\\\/\b\f\n\r\t"})",
      R"(optional_string: "\"\\/\b\f\n\r\t")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1610
      "StringFieldUnicodeEscape", REQUIRED,
1611 1612 1613
      R"({"optionalString": "\u8C37\u6B4C"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1614
      "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED,
1615 1616 1617
      R"({"optionalString": "\u8c37\u6b4c"})",
      R"(optional_string: "谷歌")");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1618
      "StringFieldSurrogatePair", REQUIRED,
1619 1620 1621 1622 1623 1624
      // 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
1625
      "StringFieldUppercaseEscapeLetter", RECOMMENDED,
1626 1627
      R"({"optionalString": "\U8C37\U6b4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1628
      "StringFieldInvalidEscape", RECOMMENDED,
1629 1630
      R"({"optionalString": "\uXXXX\u6B4C"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1631
      "StringFieldUnterminatedEscape", RECOMMENDED,
1632 1633
      R"({"optionalString": "\u8C3"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1634
      "StringFieldUnpairedHighSurrogate", RECOMMENDED,
1635 1636
      R"({"optionalString": "\uD800"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1637
      "StringFieldUnpairedLowSurrogate", RECOMMENDED,
1638 1639
      R"({"optionalString": "\uDC00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1640
      "StringFieldSurrogateInWrongOrder", RECOMMENDED,
1641 1642
      R"({"optionalString": "\uDE01\uD83D"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1643
      "StringFieldNotAString", REQUIRED,
1644 1645 1646 1647
      R"({"optionalString": 12345})");

  // Bytes fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1648
      "BytesField", REQUIRED,
1649 1650
      R"({"optionalBytes": "AQI="})",
      R"(optional_bytes: "\x01\x02")");
1651 1652 1653 1654
  RunValidJsonTest(
      "BytesFieldBase64Url", RECOMMENDED,
      R"({"optionalBytes": "-_"})",
      R"(optional_bytes: "\xfb")");
1655 1656 1657

  // Message fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1658
      "MessageField", REQUIRED,
1659 1660 1661 1662 1663
      R"({"optionalNestedMessage": {"a": 1234}})",
      "optional_nested_message: {a: 1234}");

  // Oneof fields.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1664
      "OneofFieldDuplicate", REQUIRED,
1665
      R"({"oneofUint32": 1, "oneofString": "test"})");
1666
  // Ensure zero values for oneof make it out/backs.
Jisi Liu's avatar
Jisi Liu committed
1667 1668 1669 1670
  TestAllTypesProto3 messageProto3;
  TestAllTypesProto2 messageProto2;
  TestOneofMessage(messageProto3, true);
  TestOneofMessage(messageProto2, false);
1671
  RunValidJsonTest(
1672
      "OneofZeroUint32", RECOMMENDED,
1673 1674
      R"({"oneofUint32": 0})", "oneof_uint32: 0");
  RunValidJsonTest(
1675
      "OneofZeroMessage", RECOMMENDED,
1676 1677
      R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}");
  RunValidJsonTest(
1678
      "OneofZeroString", RECOMMENDED,
1679 1680
      R"({"oneofString": ""})", "oneof_string: \"\"");
  RunValidJsonTest(
1681
      "OneofZeroBytes", RECOMMENDED,
1682
      R"({"oneofBytes": ""})", "oneof_bytes: \"\"");
1683
  RunValidJsonTest(
1684
      "OneofZeroBool", RECOMMENDED,
1685 1686
      R"({"oneofBool": false})", "oneof_bool: false");
  RunValidJsonTest(
1687
      "OneofZeroUint64", RECOMMENDED,
1688 1689
      R"({"oneofUint64": 0})", "oneof_uint64: 0");
  RunValidJsonTest(
1690
      "OneofZeroFloat", RECOMMENDED,
1691 1692
      R"({"oneofFloat": 0.0})", "oneof_float: 0");
  RunValidJsonTest(
1693
      "OneofZeroDouble", RECOMMENDED,
1694 1695
      R"({"oneofDouble": 0.0})", "oneof_double: 0");
  RunValidJsonTest(
1696
      "OneofZeroEnum", RECOMMENDED,
1697
      R"({"oneofEnum":"FOO"})", "oneof_enum: FOO");
1698 1699 1700

  // Repeated fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1701
      "PrimitiveRepeatedField", REQUIRED,
1702 1703 1704
      R"({"repeatedInt32": [1, 2, 3, 4]})",
      "repeated_int32: [1, 2, 3, 4]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1705
      "EnumRepeatedField", REQUIRED,
1706 1707 1708
      R"({"repeatedNestedEnum": ["FOO", "BAR", "BAZ"]})",
      "repeated_nested_enum: [FOO, BAR, BAZ]");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1709
      "StringRepeatedField", REQUIRED,
1710 1711 1712
      R"({"repeatedString": ["Hello", "world"]})",
      R"(repeated_string: ["Hello", "world"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1713
      "BytesRepeatedField", REQUIRED,
1714 1715 1716
      R"({"repeatedBytes": ["AAEC", "AQI="]})",
      R"(repeated_bytes: ["\x00\x01\x02", "\x01\x02"])");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1717
      "MessageRepeatedField", REQUIRED,
1718 1719 1720 1721 1722 1723
      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
1724
      "RepeatedFieldWrongElementTypeExpectingIntegersGotBool", REQUIRED,
1725 1726
      R"({"repeatedInt32": [1, false, 3, 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1727
      "RepeatedFieldWrongElementTypeExpectingIntegersGotString", REQUIRED,
1728 1729
      R"({"repeatedInt32": [1, 2, "name", 4]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1730
      "RepeatedFieldWrongElementTypeExpectingIntegersGotMessage", REQUIRED,
1731 1732
      R"({"repeatedInt32": [1, 2, 3, {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1733
      "RepeatedFieldWrongElementTypeExpectingStringsGotInt", REQUIRED,
1734 1735
      R"({"repeatedString": ["1", 2, "3", "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1736
      "RepeatedFieldWrongElementTypeExpectingStringsGotBool", REQUIRED,
1737 1738
      R"({"repeatedString": ["1", "2", false, "4"]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1739
      "RepeatedFieldWrongElementTypeExpectingStringsGotMessage", REQUIRED,
1740 1741
      R"({"repeatedString": ["1", 2, "3", {"a": 4}]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1742
      "RepeatedFieldWrongElementTypeExpectingMessagesGotInt", REQUIRED,
1743 1744
      R"({"repeatedNestedMessage": [{"a": 1}, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1745
      "RepeatedFieldWrongElementTypeExpectingMessagesGotBool", REQUIRED,
1746 1747
      R"({"repeatedNestedMessage": [{"a": 1}, false]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1748
      "RepeatedFieldWrongElementTypeExpectingMessagesGotString", REQUIRED,
1749 1750 1751
      R"({"repeatedNestedMessage": [{"a": 1}, "2"]})");
  // Trailing comma in the repeated field is not allowed.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1752
      "RepeatedFieldTrailingComma", RECOMMENDED,
1753
      R"({"repeatedInt32": [1, 2, 3, 4,]})");
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1754
  ExpectParseFailureForJson(
1755
      "RepeatedFieldTrailingCommaWithSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1756 1757
      "{\"repeatedInt32\": [1, 2, 3, 4 ,]}");
  ExpectParseFailureForJson(
1758
      "RepeatedFieldTrailingCommaWithSpaceCommaSpace", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1759 1760
      "{\"repeatedInt32\": [1, 2, 3, 4 , ]}");
  ExpectParseFailureForJson(
1761
      "RepeatedFieldTrailingCommaWithNewlines", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1762
      "{\"repeatedInt32\": [\n  1,\n  2,\n  3,\n  4,\n]}");
1763 1764 1765

  // Map fields.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1766
      "Int32MapField", REQUIRED,
1767 1768 1769 1770
      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
1771
      "Int32MapFieldKeyNotQuoted", RECOMMENDED,
1772 1773
      R"({"mapInt32Int32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1774
      "Uint32MapField", REQUIRED,
1775 1776 1777 1778
      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
1779
      "Uint32MapFieldKeyNotQuoted", RECOMMENDED,
1780 1781
      R"({"mapUint32Uint32": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1782
      "Int64MapField", REQUIRED,
1783 1784 1785 1786
      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
1787
      "Int64MapFieldKeyNotQuoted", RECOMMENDED,
1788 1789
      R"({"mapInt64Int64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1790
      "Uint64MapField", REQUIRED,
1791 1792 1793 1794
      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
1795
      "Uint64MapFieldKeyNotQuoted", RECOMMENDED,
1796 1797
      R"({"mapUint64Uint64": {1: 2, 3: 4}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1798
      "BoolMapField", REQUIRED,
1799 1800 1801 1802
      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
1803
      "BoolMapFieldKeyNotQuoted", RECOMMENDED,
1804 1805
      R"({"mapBoolBool": {true: true, false: false}})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1806
      "MessageMapField", REQUIRED,
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
      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
1825
      "Int32MapEscapedKey", REQUIRED,
1826 1827 1828
      R"({"mapInt32Int32": {"\u0031": 2}})",
      "map_int32_int32: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1829
      "Int64MapEscapedKey", REQUIRED,
1830 1831 1832
      R"({"mapInt64Int64": {"\u0031": 2}})",
      "map_int64_int64: {key: 1 value: 2}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1833
      "BoolMapEscapedKey", REQUIRED,
1834 1835 1836 1837 1838
      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
1839
      "AllFieldAcceptNull", REQUIRED,
1840 1841 1842 1843 1844
      R"({
        "optionalInt32": null,
        "optionalInt64": null,
        "optionalUint32": null,
        "optionalUint64": null,
1845 1846 1847 1848 1849 1850 1851 1852
        "optionalSint32": null,
        "optionalSint64": null,
        "optionalFixed32": null,
        "optionalFixed64": null,
        "optionalSfixed32": null,
        "optionalSfixed64": null,
        "optionalFloat": null,
        "optionalDouble": null,
1853 1854 1855 1856 1857 1858 1859 1860 1861
        "optionalBool": null,
        "optionalString": null,
        "optionalBytes": null,
        "optionalNestedEnum": null,
        "optionalNestedMessage": null,
        "repeatedInt32": null,
        "repeatedInt64": null,
        "repeatedUint32": null,
        "repeatedUint64": null,
1862 1863 1864 1865 1866 1867 1868 1869
        "repeatedSint32": null,
        "repeatedSint64": null,
        "repeatedFixed32": null,
        "repeatedFixed64": null,
        "repeatedSfixed32": null,
        "repeatedSfixed64": null,
        "repeatedFloat": null,
        "repeatedDouble": null,
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
        "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
1883
      "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED,
1884 1885
      R"({"repeatedInt32": [1, null, 2]})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1886
      "RepeatedFieldMessageElementIsNull", RECOMMENDED,
1887 1888 1889
      R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})");
  // Map field keys cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1890
      "MapFieldKeyIsNull", RECOMMENDED,
1891 1892 1893
      R"({"mapInt32Int32": {null: 1}})");
  // Map field values cannot be null.
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
1894
      "MapFieldValueIsNull", RECOMMENDED,
1895 1896
      R"({"mapInt32Int32": {"0": null}})");

Thomas Van Lenten's avatar
Thomas Van Lenten committed
1897 1898 1899
  // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double
  // quotes.
  ExpectParseFailureForJson(
1900
      "StringFieldSingleQuoteKey", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1901 1902
      R"({'optionalString': "Hello world!"})");
  ExpectParseFailureForJson(
1903
      "StringFieldSingleQuoteValue", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1904 1905
      R"({"optionalString": 'Hello world!'})");
  ExpectParseFailureForJson(
1906
      "StringFieldSingleQuoteBoth", RECOMMENDED,
Thomas Van Lenten's avatar
Thomas Van Lenten committed
1907 1908
      R"({'optionalString': 'Hello world!'})");

1909 1910 1911 1912 1913 1914 1915 1916
  // Unknown fields.
  {
    TestAllTypesProto3 messageProto3;
    TestAllTypesProto2 messageProto2;
    TestUnknownMessage(messageProto3, true);
    TestUnknownMessage(messageProto2, false);
  }

1917 1918
  // Wrapper types.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1919
      "OptionalBoolWrapper", REQUIRED,
1920 1921 1922
      R"({"optionalBoolWrapper": false})",
      "optional_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1923
      "OptionalInt32Wrapper", REQUIRED,
1924 1925 1926
      R"({"optionalInt32Wrapper": 0})",
      "optional_int32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1927
      "OptionalUint32Wrapper", REQUIRED,
1928 1929 1930
      R"({"optionalUint32Wrapper": 0})",
      "optional_uint32_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1931
      "OptionalInt64Wrapper", REQUIRED,
1932 1933 1934
      R"({"optionalInt64Wrapper": 0})",
      "optional_int64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1935
      "OptionalUint64Wrapper", REQUIRED,
1936 1937 1938
      R"({"optionalUint64Wrapper": 0})",
      "optional_uint64_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1939
      "OptionalFloatWrapper", REQUIRED,
1940 1941 1942
      R"({"optionalFloatWrapper": 0})",
      "optional_float_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1943
      "OptionalDoubleWrapper", REQUIRED,
1944 1945 1946
      R"({"optionalDoubleWrapper": 0})",
      "optional_double_wrapper: {value: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1947
      "OptionalStringWrapper", REQUIRED,
1948 1949 1950
      R"({"optionalStringWrapper": ""})",
      R"(optional_string_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1951
      "OptionalBytesWrapper", REQUIRED,
1952 1953 1954
      R"({"optionalBytesWrapper": ""})",
      R"(optional_bytes_wrapper: {value: ""})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1955
      "OptionalWrapperTypesWithNonDefaultValue", REQUIRED,
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
      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
1979
      "RepeatedBoolWrapper", REQUIRED,
1980 1981 1982 1983
      R"({"repeatedBoolWrapper": [true, false]})",
      "repeated_bool_wrapper: {value: true}"
      "repeated_bool_wrapper: {value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1984
      "RepeatedInt32Wrapper", REQUIRED,
1985 1986 1987 1988
      R"({"repeatedInt32Wrapper": [0, 1]})",
      "repeated_int32_wrapper: {value: 0}"
      "repeated_int32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1989
      "RepeatedUint32Wrapper", REQUIRED,
1990 1991 1992 1993
      R"({"repeatedUint32Wrapper": [0, 1]})",
      "repeated_uint32_wrapper: {value: 0}"
      "repeated_uint32_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1994
      "RepeatedInt64Wrapper", REQUIRED,
1995 1996 1997 1998
      R"({"repeatedInt64Wrapper": [0, 1]})",
      "repeated_int64_wrapper: {value: 0}"
      "repeated_int64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
1999
      "RepeatedUint64Wrapper", REQUIRED,
2000 2001 2002 2003
      R"({"repeatedUint64Wrapper": [0, 1]})",
      "repeated_uint64_wrapper: {value: 0}"
      "repeated_uint64_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2004
      "RepeatedFloatWrapper", REQUIRED,
2005 2006 2007 2008
      R"({"repeatedFloatWrapper": [0, 1]})",
      "repeated_float_wrapper: {value: 0}"
      "repeated_float_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2009
      "RepeatedDoubleWrapper", REQUIRED,
2010 2011 2012 2013
      R"({"repeatedDoubleWrapper": [0, 1]})",
      "repeated_double_wrapper: {value: 0}"
      "repeated_double_wrapper: {value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2014
      "RepeatedStringWrapper", REQUIRED,
2015 2016 2017 2018 2019 2020
      R"({"repeatedStringWrapper": ["", "AQI="]})",
      R"(
        repeated_string_wrapper: {value: ""}
        repeated_string_wrapper: {value: "AQI="}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2021
      "RepeatedBytesWrapper", REQUIRED,
2022 2023 2024 2025 2026 2027
      R"({"repeatedBytesWrapper": ["", "AQI="]})",
      R"(
        repeated_bytes_wrapper: {value: ""}
        repeated_bytes_wrapper: {value: "\x01\x02"}
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2028
      "WrapperTypesWithNullValue", REQUIRED,
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
      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
2053
      "DurationMinValue", REQUIRED,
2054 2055 2056
      R"({"optionalDuration": "-315576000000.999999999s"})",
      "optional_duration: {seconds: -315576000000 nanos: -999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2057
      "DurationMaxValue", REQUIRED,
2058 2059 2060
      R"({"optionalDuration": "315576000000.999999999s"})",
      "optional_duration: {seconds: 315576000000 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2061
      "DurationRepeatedValue", REQUIRED,
2062 2063 2064
      R"({"repeatedDuration": ["1.5s", "-1.5s"]})",
      "repeated_duration: {seconds: 1 nanos: 500000000}"
      "repeated_duration: {seconds: -1 nanos: -500000000}");
2065 2066 2067 2068
  RunValidJsonTest(
      "DurationNull", REQUIRED,
      R"({"optionalDuration": null})",
      "");
2069 2070

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2071
      "DurationMissingS", REQUIRED,
2072 2073
      R"({"optionalDuration": "1"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2074
      "DurationJsonInputTooSmall", REQUIRED,
2075 2076
      R"({"optionalDuration": "-315576000001.000000000s"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2077
      "DurationJsonInputTooLarge", REQUIRED,
2078 2079
      R"({"optionalDuration": "315576000001.000000000s"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2080
      "DurationProtoInputTooSmall", REQUIRED,
2081 2082
      "optional_duration: {seconds: -315576000001 nanos: 0}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2083
      "DurationProtoInputTooLarge", REQUIRED,
2084 2085 2086
      "optional_duration: {seconds: 315576000001 nanos: 0}");

  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2087
      "DurationHasZeroFractionalDigit", RECOMMENDED,
2088 2089 2090 2091 2092
      R"({"optionalDuration": "1.000000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2093
      "DurationHas3FractionalDigits", RECOMMENDED,
2094 2095 2096 2097 2098
      R"({"optionalDuration": "1.010000000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2099
      "DurationHas6FractionalDigits", RECOMMENDED,
2100 2101 2102 2103 2104
      R"({"optionalDuration": "1.000010000s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000010s";
      });
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2105
      "DurationHas9FractionalDigits", RECOMMENDED,
2106 2107 2108 2109 2110 2111 2112
      R"({"optionalDuration": "1.000000010s"})",
      [](const Json::Value& value) {
        return value["optionalDuration"].asString() == "1.000000010s";
      });

  // Timestamp
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2113
      "TimestampMinValue", REQUIRED,
2114 2115 2116
      R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})",
      "optional_timestamp: {seconds: -62135596800}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2117
      "TimestampMaxValue", REQUIRED,
2118 2119 2120
      R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})",
      "optional_timestamp: {seconds: 253402300799 nanos: 999999999}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2121
      "TimestampRepeatedValue", REQUIRED,
2122 2123 2124 2125 2126 2127 2128 2129 2130
      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
2131
      "TimestampWithPositiveOffset", REQUIRED,
2132 2133 2134
      R"({"optionalTimestamp": "1970-01-01T08:00:00+08:00"})",
      "optional_timestamp: {seconds: 0}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2135
      "TimestampWithNegativeOffset", REQUIRED,
2136 2137
      R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})",
      "optional_timestamp: {seconds: 0}");
2138 2139 2140 2141
  RunValidJsonTest(
      "TimestampNull", REQUIRED,
      R"({"optionalTimestamp": null})",
      "");
2142 2143

  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2144
      "TimestampJsonInputTooSmall", REQUIRED,
2145 2146
      R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2147
      "TimestampJsonInputTooLarge", REQUIRED,
2148 2149
      R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2150
      "TimestampJsonInputMissingZ", REQUIRED,
2151 2152
      R"({"optionalTimestamp": "0001-01-01T00:00:00"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2153
      "TimestampJsonInputMissingT", REQUIRED,
2154 2155
      R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2156
      "TimestampJsonInputLowercaseZ", REQUIRED,
2157 2158
      R"({"optionalTimestamp": "0001-01-01T00:00:00z"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2159
      "TimestampJsonInputLowercaseT", REQUIRED,
2160 2161
      R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2162
      "TimestampProtoInputTooSmall", REQUIRED,
2163 2164
      "optional_timestamp: {seconds: -62135596801}");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2165
      "TimestampProtoInputTooLarge", REQUIRED,
2166 2167
      "optional_timestamp: {seconds: 253402300800}");
  RunValidJsonTestWithValidator(
Bo Yang's avatar
Bo Yang committed
2168
      "TimestampZeroNormalized", RECOMMENDED,
2169 2170 2171 2172 2173 2174
      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
2175
      "TimestampHasZeroFractionalDigit", RECOMMENDED,
2176 2177 2178 2179 2180 2181
      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
2182
      "TimestampHas3FractionalDigits", RECOMMENDED,
2183 2184 2185 2186 2187 2188
      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
2189
      "TimestampHas6FractionalDigits", RECOMMENDED,
2190 2191 2192 2193 2194 2195
      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
2196
      "TimestampHas9FractionalDigits", RECOMMENDED,
2197 2198 2199 2200 2201 2202 2203 2204
      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
2205
      "FieldMask", REQUIRED,
2206 2207 2208
      R"({"optionalFieldMask": "foo,barBaz"})",
      R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})");
  ExpectParseFailureForJson(
Bo Yang's avatar
Bo Yang committed
2209
      "FieldMaskInvalidCharacter", RECOMMENDED,
2210 2211
      R"({"optionalFieldMask": "foo,bar_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2212
      "FieldMaskPathsDontRoundTrip", RECOMMENDED,
2213 2214
      R"(optional_field_mask: {paths: "fooBar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2215
      "FieldMaskNumbersDontRoundTrip", RECOMMENDED,
2216 2217
      R"(optional_field_mask: {paths: "foo_3_bar"})");
  ExpectSerializeFailureForJson(
Bo Yang's avatar
Bo Yang committed
2218
      "FieldMaskTooManyUnderscore", RECOMMENDED,
2219 2220 2221 2222
      R"(optional_field_mask: {paths: "foo__bar"})");

  // Struct
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2223
      "Struct", REQUIRED,
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
      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
2289
      "ValueAcceptInteger", REQUIRED,
2290 2291 2292
      R"({"optionalValue": 1})",
      "optional_value: { number_value: 1}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2293
      "ValueAcceptFloat", REQUIRED,
2294 2295 2296
      R"({"optionalValue": 1.5})",
      "optional_value: { number_value: 1.5}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2297
      "ValueAcceptBool", REQUIRED,
2298 2299 2300
      R"({"optionalValue": false})",
      "optional_value: { bool_value: false}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2301
      "ValueAcceptNull", REQUIRED,
2302 2303 2304
      R"({"optionalValue": null})",
      "optional_value: { null_value: NULL_VALUE}");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2305
      "ValueAcceptString", REQUIRED,
2306 2307 2308
      R"({"optionalValue": "hello"})",
      R"(optional_value: { string_value: "hello"})");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2309
      "ValueAcceptList", REQUIRED,
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
      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
2324
      "ValueAcceptObject", REQUIRED,
2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340
      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
2341
      "Any", REQUIRED,
2342 2343
      R"({
        "optionalAny": {
Jisi Liu's avatar
Jisi Liu committed
2344
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2345 2346 2347 2348 2349
          "optionalInt32": 12345
        }
      })",
      R"(
        optional_any: {
Jisi Liu's avatar
Jisi Liu committed
2350
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2351 2352 2353 2354 2355
            optional_int32: 12345
          }
        }
      )");
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2356
      "AnyNested", REQUIRED,
2357 2358 2359 2360
      R"({
        "optionalAny": {
          "@type": "type.googleapis.com/google.protobuf.Any",
          "value": {
Jisi Liu's avatar
Jisi Liu committed
2361
            "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3",
2362 2363 2364 2365 2366 2367 2368
            "optionalInt32": 12345
          }
        }
      })",
      R"(
        optional_any: {
          [type.googleapis.com/google.protobuf.Any] {
Jisi Liu's avatar
Jisi Liu committed
2369
            [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2370 2371 2372 2373 2374 2375 2376
              optional_int32: 12345
            }
          }
        }
      )");
  // The special "@type" tag is not required to appear first.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2377
      "AnyUnorderedTypeTag", REQUIRED,
2378 2379 2380
      R"({
        "optionalAny": {
          "optionalInt32": 12345,
Jisi Liu's avatar
Jisi Liu committed
2381
          "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3"
2382 2383 2384 2385
        }
      })",
      R"(
        optional_any: {
Jisi Liu's avatar
Jisi Liu committed
2386
          [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] {
2387 2388 2389 2390 2391 2392
            optional_int32: 12345
          }
        }
      )");
  // Well-known types in Any.
  RunValidJsonTest(
Bo Yang's avatar
Bo Yang committed
2393
      "AnyWithInt32ValueWrapper", REQUIRED,
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
      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
2408
      "AnyWithDuration", REQUIRED,
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
      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
2424
      "AnyWithTimestamp", REQUIRED,
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
      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
2440
      "AnyWithFieldMask", REQUIRED,
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
      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
2455
      "AnyWithStruct", REQUIRED,
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
      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
2477
      "AnyWithValueForJsonObject", REQUIRED,
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
      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
2501
      "AnyWithValueForInteger", REQUIRED,
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
      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;
2517
  if (!CheckSetEmpty(expected_to_fail_, "nonexistent_tests.txt",
2518
                     "These tests were listed in the failure list, but they "
2519 2520 2521 2522
                     "don't exist.  Remove them from the failure list by "
                     "running:\n"
                     "  ./update_failure_list.py " + failure_list_filename_ +
                     " --remove nonexistent_tests.txt")) {
2523 2524
    ok = false;
  }
2525
  if (!CheckSetEmpty(unexpected_failing_tests_, "failing_tests.txt",
2526 2527
                     "These tests failed.  If they can't be fixed right now, "
                     "you can add them to the failure list so the overall "
2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
                     "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")) {
2540 2541
    ok = false;
  }
2542

2543
  if (verbose_) {
2544
    CheckSetEmpty(skipped_, "",
2545 2546 2547
                  "These tests were skipped (probably because support for some "
                  "features is not implemented)");
  }
2548 2549 2550 2551 2552 2553 2554 2555

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

2556
  output->assign(output_);
2557 2558

  return ok;
2559
}
2560 2561 2562

}  // namespace protobuf
}  // namespace google