PageRenderTime 123ms CodeModel.GetById 15ms app.highlight 99ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/third_party/protobuf/protobuf/src/google/protobuf/text_format_unittest.cc

http://github.com/tomahawk-player/tomahawk
C++ | 1141 lines | 826 code | 173 blank | 142 comment | 1 complexity | dd983dd2fb2bd33d6203ad596bb7eaab MD5 | raw file
   1// Protocol Buffers - Google's data interchange format
   2// Copyright 2008 Google Inc.  All rights reserved.
   3// http://code.google.com/p/protobuf/
   4//
   5// Redistribution and use in source and binary forms, with or without
   6// modification, are permitted provided that the following conditions are
   7// met:
   8//
   9//     * Redistributions of source code must retain the above copyright
  10// notice, this list of conditions and the following disclaimer.
  11//     * Redistributions in binary form must reproduce the above
  12// copyright notice, this list of conditions and the following disclaimer
  13// in the documentation and/or other materials provided with the
  14// distribution.
  15//     * Neither the name of Google Inc. nor the names of its
  16// contributors may be used to endorse or promote products derived from
  17// this software without specific prior written permission.
  18//
  19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30
  31// Author: jschorr@google.com (Joseph Schorr)
  32//  Based on original Protocol Buffers design by
  33//  Sanjay Ghemawat, Jeff Dean, and others.
  34
  35#include <math.h>
  36#include <stdlib.h>
  37#include <limits>
  38
  39#include <google/protobuf/text_format.h>
  40#include <google/protobuf/io/zero_copy_stream_impl.h>
  41#include <google/protobuf/io/tokenizer.h>
  42#include <google/protobuf/unittest.pb.h>
  43#include <google/protobuf/unittest_mset.pb.h>
  44#include <google/protobuf/test_util.h>
  45
  46#include <google/protobuf/stubs/common.h>
  47#include <google/protobuf/testing/file.h>
  48#include <google/protobuf/testing/googletest.h>
  49#include <gtest/gtest.h>
  50#include <google/protobuf/stubs/strutil.h>
  51#include <google/protobuf/stubs/substitute.h>
  52
  53namespace google {
  54namespace protobuf {
  55
  56// Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
  57namespace text_format_unittest {
  58
  59inline bool IsNaN(double value) {
  60  // NaN is never equal to anything, even itself.
  61  return value != value;
  62}
  63
  64// A basic string with different escapable characters for testing.
  65const string kEscapeTestString =
  66  "\"A string with ' characters \n and \r newlines and \t tabs and \001 "
  67  "slashes \\ and  multiple   spaces";
  68
  69// A representation of the above string with all the characters escaped.
  70const string kEscapeTestStringEscaped =
  71  "\"\\\"A string with \\' characters \\n and \\r newlines "
  72  "and \\t tabs and \\001 slashes \\\\ and  multiple   spaces\"";
  73
  74class TextFormatTest : public testing::Test {
  75 public:
  76  static void SetUpTestCase() {
  77    File::ReadFileToStringOrDie(
  78        TestSourceDir()
  79        + "/google/protobuf/testdata/text_format_unittest_data.txt",
  80        &static_proto_debug_string_);
  81  }
  82
  83  TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {}
  84
  85 protected:
  86  // Debug string read from text_format_unittest_data.txt.
  87  const string proto_debug_string_;
  88  unittest::TestAllTypes proto_;
  89
  90 private:
  91  static string static_proto_debug_string_;
  92};
  93string TextFormatTest::static_proto_debug_string_;
  94
  95class TextFormatExtensionsTest : public testing::Test {
  96 public:
  97  static void SetUpTestCase() {
  98    File::ReadFileToStringOrDie(
  99        TestSourceDir()
 100        + "/google/protobuf/testdata/"
 101          "text_format_unittest_extensions_data.txt",
 102        &static_proto_debug_string_);
 103  }
 104
 105  TextFormatExtensionsTest()
 106      : proto_debug_string_(static_proto_debug_string_) {}
 107
 108 protected:
 109  // Debug string read from text_format_unittest_data.txt.
 110  const string proto_debug_string_;
 111  unittest::TestAllExtensions proto_;
 112
 113 private:
 114  static string static_proto_debug_string_;
 115};
 116string TextFormatExtensionsTest::static_proto_debug_string_;
 117
 118
 119TEST_F(TextFormatTest, Basic) {
 120  TestUtil::SetAllFields(&proto_);
 121  EXPECT_EQ(proto_debug_string_, proto_.DebugString());
 122}
 123
 124TEST_F(TextFormatExtensionsTest, Extensions) {
 125  TestUtil::SetAllExtensions(&proto_);
 126  EXPECT_EQ(proto_debug_string_, proto_.DebugString());
 127}
 128
 129TEST_F(TextFormatTest, ShortDebugString) {
 130  proto_.set_optional_int32(1);
 131  proto_.set_optional_string("hello");
 132  proto_.mutable_optional_nested_message()->set_bb(2);
 133  proto_.mutable_optional_foreign_message();
 134
 135  EXPECT_EQ("optional_int32: 1 optional_string: \"hello\" "
 136            "optional_nested_message { bb: 2 } "
 137            "optional_foreign_message { }",
 138            proto_.ShortDebugString());
 139}
 140
 141TEST_F(TextFormatTest, ShortPrimitiveRepeateds) {
 142  proto_.set_optional_int32(123);
 143  proto_.add_repeated_int32(456);
 144  proto_.add_repeated_int32(789);
 145  proto_.add_repeated_string("foo");
 146  proto_.add_repeated_string("bar");
 147  proto_.add_repeated_nested_message()->set_bb(2);
 148  proto_.add_repeated_nested_message()->set_bb(3);
 149  proto_.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
 150  proto_.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
 151
 152  TextFormat::Printer printer;
 153  printer.SetUseShortRepeatedPrimitives(true);
 154  string text;
 155  printer.PrintToString(proto_, &text);
 156
 157  EXPECT_EQ("optional_int32: 123\n"
 158            "repeated_int32: [456, 789]\n"
 159            "repeated_string: \"foo\"\n"
 160            "repeated_string: \"bar\"\n"
 161            "repeated_nested_message {\n  bb: 2\n}\n"
 162            "repeated_nested_message {\n  bb: 3\n}\n"
 163            "repeated_nested_enum: [FOO, BAR]\n",
 164            text);
 165
 166  // Try in single-line mode.
 167  printer.SetSingleLineMode(true);
 168  printer.PrintToString(proto_, &text);
 169
 170  EXPECT_EQ("optional_int32: 123 "
 171            "repeated_int32: [456, 789] "
 172            "repeated_string: \"foo\" "
 173            "repeated_string: \"bar\" "
 174            "repeated_nested_message { bb: 2 } "
 175            "repeated_nested_message { bb: 3 } "
 176            "repeated_nested_enum: [FOO, BAR] ",
 177            text);
 178}
 179
 180
 181TEST_F(TextFormatTest, StringEscape) {
 182  // Set the string value to test.
 183  proto_.set_optional_string(kEscapeTestString);
 184
 185  // Get the DebugString from the proto.
 186  string debug_string = proto_.DebugString();
 187  string utf8_debug_string = proto_.Utf8DebugString();
 188
 189  // Hardcode a correct value to test against.
 190  string correct_string = "optional_string: "
 191      + kEscapeTestStringEscaped
 192       + "\n";
 193
 194  // Compare.
 195  EXPECT_EQ(correct_string, debug_string);
 196  // UTF-8 string is the same as non-UTF-8 because
 197  // the protocol buffer contains no UTF-8 text.
 198  EXPECT_EQ(correct_string, utf8_debug_string);
 199
 200  string expected_short_debug_string = "optional_string: "
 201      + kEscapeTestStringEscaped;
 202  EXPECT_EQ(expected_short_debug_string, proto_.ShortDebugString());
 203}
 204
 205TEST_F(TextFormatTest, Utf8DebugString) {
 206  // Set the string value to test.
 207  proto_.set_optional_string("\350\260\267\346\255\214");
 208
 209  // Get the DebugString from the proto.
 210  string debug_string = proto_.DebugString();
 211  string utf8_debug_string = proto_.Utf8DebugString();
 212
 213  // Hardcode a correct value to test against.
 214  string correct_utf8_string = "optional_string: "
 215      "\"\350\260\267\346\255\214\""
 216      "\n";
 217  string correct_string = "optional_string: "
 218      "\"\\350\\260\\267\\346\\255\\214\""
 219      "\n";
 220
 221  // Compare.
 222  EXPECT_EQ(correct_utf8_string, utf8_debug_string);
 223  EXPECT_EQ(correct_string, debug_string);
 224}
 225
 226TEST_F(TextFormatTest, PrintUnknownFields) {
 227  // Test printing of unknown fields in a message.
 228
 229  unittest::TestEmptyMessage message;
 230  UnknownFieldSet* unknown_fields = message.mutable_unknown_fields();
 231
 232  unknown_fields->AddVarint(5, 1);
 233  unknown_fields->AddFixed32(5, 2);
 234  unknown_fields->AddFixed64(5, 3);
 235  unknown_fields->AddLengthDelimited(5, "4");
 236  unknown_fields->AddGroup(5)->AddVarint(10, 5);
 237
 238  unknown_fields->AddVarint(8, 1);
 239  unknown_fields->AddVarint(8, 2);
 240  unknown_fields->AddVarint(8, 3);
 241
 242  EXPECT_EQ(
 243    "5: 1\n"
 244    "5: 0x00000002\n"
 245    "5: 0x0000000000000003\n"
 246    "5: \"4\"\n"
 247    "5 {\n"
 248    "  10: 5\n"
 249    "}\n"
 250    "8: 1\n"
 251    "8: 2\n"
 252    "8: 3\n",
 253    message.DebugString());
 254}
 255
 256TEST_F(TextFormatTest, PrintUnknownMessage) {
 257  // Test heuristic printing of messages in an UnknownFieldSet.
 258
 259  protobuf_unittest::TestAllTypes message;
 260
 261  // Cases which should not be interpreted as sub-messages.
 262
 263  // 'a' is a valid FIXED64 tag, so for the string to be parseable as a message
 264  // it should be followed by 8 bytes.  Since this string only has two
 265  // subsequent bytes, it should be treated as a string.
 266  message.add_repeated_string("abc");
 267
 268  // 'd' happens to be a valid ENDGROUP tag.  So,
 269  // UnknownFieldSet::MergeFromCodedStream() will successfully parse "def", but
 270  // the ConsumedEntireMessage() check should fail.
 271  message.add_repeated_string("def");
 272
 273  // A zero-length string should never be interpreted as a message even though
 274  // it is technically valid as one.
 275  message.add_repeated_string("");
 276
 277  // Case which should be interpreted as a sub-message.
 278
 279  // An actual nested message with content should always be interpreted as a
 280  // nested message.
 281  message.add_repeated_nested_message()->set_bb(123);
 282
 283  string data;
 284  message.SerializeToString(&data);
 285
 286  string text;
 287  UnknownFieldSet unknown_fields;
 288  EXPECT_TRUE(unknown_fields.ParseFromString(data));
 289  EXPECT_TRUE(TextFormat::PrintUnknownFieldsToString(unknown_fields, &text));
 290  EXPECT_EQ(
 291    "44: \"abc\"\n"
 292    "44: \"def\"\n"
 293    "44: \"\"\n"
 294    "48 {\n"
 295    "  1: 123\n"
 296    "}\n",
 297    text);
 298}
 299
 300TEST_F(TextFormatTest, PrintMessageWithIndent) {
 301  // Test adding an initial indent to printing.
 302
 303  protobuf_unittest::TestAllTypes message;
 304
 305  message.add_repeated_string("abc");
 306  message.add_repeated_string("def");
 307  message.add_repeated_nested_message()->set_bb(123);
 308
 309  string text;
 310  TextFormat::Printer printer;
 311  printer.SetInitialIndentLevel(1);
 312  EXPECT_TRUE(printer.PrintToString(message, &text));
 313  EXPECT_EQ(
 314    "  repeated_string: \"abc\"\n"
 315    "  repeated_string: \"def\"\n"
 316    "  repeated_nested_message {\n"
 317    "    bb: 123\n"
 318    "  }\n",
 319    text);
 320}
 321
 322TEST_F(TextFormatTest, PrintMessageSingleLine) {
 323  // Test printing a message on a single line.
 324
 325  protobuf_unittest::TestAllTypes message;
 326
 327  message.add_repeated_string("abc");
 328  message.add_repeated_string("def");
 329  message.add_repeated_nested_message()->set_bb(123);
 330
 331  string text;
 332  TextFormat::Printer printer;
 333  printer.SetInitialIndentLevel(1);
 334  printer.SetSingleLineMode(true);
 335  EXPECT_TRUE(printer.PrintToString(message, &text));
 336  EXPECT_EQ(
 337    "  repeated_string: \"abc\" repeated_string: \"def\" "
 338    "repeated_nested_message { bb: 123 } ",
 339    text);
 340}
 341
 342TEST_F(TextFormatTest, ParseBasic) {
 343  io::ArrayInputStream input_stream(proto_debug_string_.data(),
 344                                    proto_debug_string_.size());
 345  TextFormat::Parse(&input_stream, &proto_);
 346  TestUtil::ExpectAllFieldsSet(proto_);
 347}
 348
 349TEST_F(TextFormatExtensionsTest, ParseExtensions) {
 350  io::ArrayInputStream input_stream(proto_debug_string_.data(),
 351                                    proto_debug_string_.size());
 352  TextFormat::Parse(&input_stream, &proto_);
 353  TestUtil::ExpectAllExtensionsSet(proto_);
 354}
 355
 356TEST_F(TextFormatTest, ParseEnumFieldFromNumber) {
 357  // Create a parse string with a numerical value for an enum field.
 358  string parse_string = strings::Substitute("optional_nested_enum: $0",
 359                                            unittest::TestAllTypes::BAZ);
 360  EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
 361  EXPECT_TRUE(proto_.has_optional_nested_enum());
 362  EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.optional_nested_enum());
 363}
 364
 365TEST_F(TextFormatTest, ParseEnumFieldFromNegativeNumber) {
 366  ASSERT_LT(unittest::SPARSE_E, 0);
 367  string parse_string = strings::Substitute("sparse_enum: $0",
 368                                            unittest::SPARSE_E);
 369  unittest::SparseEnumMessage proto;
 370  EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto));
 371  EXPECT_TRUE(proto.has_sparse_enum());
 372  EXPECT_EQ(unittest::SPARSE_E, proto.sparse_enum());
 373}
 374
 375TEST_F(TextFormatTest, ParseStringEscape) {
 376  // Create a parse string with escpaed characters in it.
 377  string parse_string = "optional_string: "
 378      + kEscapeTestStringEscaped
 379      + "\n";
 380
 381  io::ArrayInputStream input_stream(parse_string.data(),
 382                                    parse_string.size());
 383  TextFormat::Parse(&input_stream, &proto_);
 384
 385  // Compare.
 386  EXPECT_EQ(kEscapeTestString, proto_.optional_string());
 387}
 388
 389TEST_F(TextFormatTest, ParseConcatenatedString) {
 390  // Create a parse string with multiple parts on one line.
 391  string parse_string = "optional_string: \"foo\" \"bar\"\n";
 392
 393  io::ArrayInputStream input_stream1(parse_string.data(),
 394                                    parse_string.size());
 395  TextFormat::Parse(&input_stream1, &proto_);
 396
 397  // Compare.
 398  EXPECT_EQ("foobar", proto_.optional_string());
 399
 400  // Create a parse string with multiple parts on seperate lines.
 401  parse_string = "optional_string: \"foo\"\n"
 402                 "\"bar\"\n";
 403
 404  io::ArrayInputStream input_stream2(parse_string.data(),
 405                                    parse_string.size());
 406  TextFormat::Parse(&input_stream2, &proto_);
 407
 408  // Compare.
 409  EXPECT_EQ("foobar", proto_.optional_string());
 410}
 411
 412TEST_F(TextFormatTest, ParseFloatWithSuffix) {
 413  // Test that we can parse a floating-point value with 'f' appended to the
 414  // end.  This is needed for backwards-compatibility with proto1.
 415
 416  // Have it parse a float with the 'f' suffix.
 417  string parse_string = "optional_float: 1.0f\n";
 418
 419  io::ArrayInputStream input_stream(parse_string.data(),
 420                                    parse_string.size());
 421
 422  TextFormat::Parse(&input_stream, &proto_);
 423
 424  // Compare.
 425  EXPECT_EQ(1.0, proto_.optional_float());
 426}
 427
 428TEST_F(TextFormatTest, ParseShortRepeatedForm) {
 429  string parse_string =
 430      // Mixed short-form and long-form are simply concatenated.
 431      "repeated_int32: 1\n"
 432      "repeated_int32: [456, 789]\n"
 433      "repeated_nested_enum: [  FOO ,BAR, # comment\n"
 434      "                         3]\n"
 435      // Note that while the printer won't print repeated strings in short-form,
 436      // the parser will accept them.
 437      "repeated_string: [ \"foo\", 'bar' ]\n";
 438
 439  ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
 440
 441  ASSERT_EQ(3, proto_.repeated_int32_size());
 442  EXPECT_EQ(1, proto_.repeated_int32(0));
 443  EXPECT_EQ(456, proto_.repeated_int32(1));
 444  EXPECT_EQ(789, proto_.repeated_int32(2));
 445
 446  ASSERT_EQ(3, proto_.repeated_nested_enum_size());
 447  EXPECT_EQ(unittest::TestAllTypes::FOO, proto_.repeated_nested_enum(0));
 448  EXPECT_EQ(unittest::TestAllTypes::BAR, proto_.repeated_nested_enum(1));
 449  EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.repeated_nested_enum(2));
 450
 451  ASSERT_EQ(2, proto_.repeated_string_size());
 452  EXPECT_EQ("foo", proto_.repeated_string(0));
 453  EXPECT_EQ("bar", proto_.repeated_string(1));
 454}
 455
 456TEST_F(TextFormatTest, Comments) {
 457  // Test that comments are ignored.
 458
 459  string parse_string = "optional_int32: 1  # a comment\n"
 460                        "optional_int64: 2  # another comment";
 461
 462  io::ArrayInputStream input_stream(parse_string.data(),
 463                                    parse_string.size());
 464
 465  TextFormat::Parse(&input_stream, &proto_);
 466
 467  // Compare.
 468  EXPECT_EQ(1, proto_.optional_int32());
 469  EXPECT_EQ(2, proto_.optional_int64());
 470}
 471
 472TEST_F(TextFormatTest, OptionalColon) {
 473  // Test that we can place a ':' after the field name of a nested message,
 474  // even though we don't have to.
 475
 476  string parse_string = "optional_nested_message: { bb: 1}\n";
 477
 478  io::ArrayInputStream input_stream(parse_string.data(),
 479                                    parse_string.size());
 480
 481  TextFormat::Parse(&input_stream, &proto_);
 482
 483  // Compare.
 484  EXPECT_TRUE(proto_.has_optional_nested_message());
 485  EXPECT_EQ(1, proto_.optional_nested_message().bb());
 486}
 487
 488// Some platforms (e.g. Windows) insist on padding the exponent to three
 489// digits when one or two would be just fine.
 490static string RemoveRedundantZeros(string text) {
 491  text = StringReplace(text, "e+0", "e+", true);
 492  text = StringReplace(text, "e-0", "e-", true);
 493  return text;
 494}
 495
 496TEST_F(TextFormatTest, PrintExotic) {
 497  unittest::TestAllTypes message;
 498
 499  // Note:  In C, a negative integer literal is actually the unary negation
 500  //   operator being applied to a positive integer literal, and
 501  //   9223372036854775808 is outside the range of int64.  However, it is not
 502  //   outside the range of uint64.  Confusingly, this means that everything
 503  //   works if we make the literal unsigned, even though we are negating it.
 504  message.add_repeated_int64(-GOOGLE_ULONGLONG(9223372036854775808));
 505  message.add_repeated_uint64(GOOGLE_ULONGLONG(18446744073709551615));
 506  message.add_repeated_double(123.456);
 507  message.add_repeated_double(1.23e21);
 508  message.add_repeated_double(1.23e-18);
 509  message.add_repeated_double(std::numeric_limits<double>::infinity());
 510  message.add_repeated_double(-std::numeric_limits<double>::infinity());
 511  message.add_repeated_double(std::numeric_limits<double>::quiet_NaN());
 512  message.add_repeated_string(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12));
 513
 514  // Fun story:  We used to use 1.23e22 instead of 1.23e21 above, but this
 515  //   seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of
 516  //   the value differed from strtod()'s parsing.  That is to say, the
 517  //   following assertion fails on MinGW:
 518  //     assert(1.23e22 == strtod("1.23e22", NULL));
 519  //   As a result, SimpleDtoa() would print the value as
 520  //   "1.2300000000000001e+22" to make sure strtod() produce the exact same
 521  //   result.  Our goal is to test runtime parsing, not compile-time parsing,
 522  //   so this wasn't our problem.  It was found that using 1.23e21 did not
 523  //   have this problem, so we switched to that instead.
 524
 525  EXPECT_EQ(
 526    "repeated_int64: -9223372036854775808\n"
 527    "repeated_uint64: 18446744073709551615\n"
 528    "repeated_double: 123.456\n"
 529    "repeated_double: 1.23e+21\n"
 530    "repeated_double: 1.23e-18\n"
 531    "repeated_double: inf\n"
 532    "repeated_double: -inf\n"
 533    "repeated_double: nan\n"
 534    "repeated_string: \"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n",
 535    RemoveRedundantZeros(message.DebugString()));
 536}
 537
 538TEST_F(TextFormatTest, PrintFloatPrecision) {
 539  unittest::TestAllTypes message;
 540
 541  message.add_repeated_float(1.2);
 542  message.add_repeated_float(1.23);
 543  message.add_repeated_float(1.234);
 544  message.add_repeated_float(1.2345);
 545  message.add_repeated_float(1.23456);
 546  message.add_repeated_float(1.2e10);
 547  message.add_repeated_float(1.23e10);
 548  message.add_repeated_float(1.234e10);
 549  message.add_repeated_float(1.2345e10);
 550  message.add_repeated_float(1.23456e10);
 551  message.add_repeated_double(1.2);
 552  message.add_repeated_double(1.23);
 553  message.add_repeated_double(1.234);
 554  message.add_repeated_double(1.2345);
 555  message.add_repeated_double(1.23456);
 556  message.add_repeated_double(1.234567);
 557  message.add_repeated_double(1.2345678);
 558  message.add_repeated_double(1.23456789);
 559  message.add_repeated_double(1.234567898);
 560  message.add_repeated_double(1.2345678987);
 561  message.add_repeated_double(1.23456789876);
 562  message.add_repeated_double(1.234567898765);
 563  message.add_repeated_double(1.2345678987654);
 564  message.add_repeated_double(1.23456789876543);
 565  message.add_repeated_double(1.2e100);
 566  message.add_repeated_double(1.23e100);
 567  message.add_repeated_double(1.234e100);
 568  message.add_repeated_double(1.2345e100);
 569  message.add_repeated_double(1.23456e100);
 570  message.add_repeated_double(1.234567e100);
 571  message.add_repeated_double(1.2345678e100);
 572  message.add_repeated_double(1.23456789e100);
 573  message.add_repeated_double(1.234567898e100);
 574  message.add_repeated_double(1.2345678987e100);
 575  message.add_repeated_double(1.23456789876e100);
 576  message.add_repeated_double(1.234567898765e100);
 577  message.add_repeated_double(1.2345678987654e100);
 578  message.add_repeated_double(1.23456789876543e100);
 579
 580  EXPECT_EQ(
 581    "repeated_float: 1.2\n"
 582    "repeated_float: 1.23\n"
 583    "repeated_float: 1.234\n"
 584    "repeated_float: 1.2345\n"
 585    "repeated_float: 1.23456\n"
 586    "repeated_float: 1.2e+10\n"
 587    "repeated_float: 1.23e+10\n"
 588    "repeated_float: 1.234e+10\n"
 589    "repeated_float: 1.2345e+10\n"
 590    "repeated_float: 1.23456e+10\n"
 591    "repeated_double: 1.2\n"
 592    "repeated_double: 1.23\n"
 593    "repeated_double: 1.234\n"
 594    "repeated_double: 1.2345\n"
 595    "repeated_double: 1.23456\n"
 596    "repeated_double: 1.234567\n"
 597    "repeated_double: 1.2345678\n"
 598    "repeated_double: 1.23456789\n"
 599    "repeated_double: 1.234567898\n"
 600    "repeated_double: 1.2345678987\n"
 601    "repeated_double: 1.23456789876\n"
 602    "repeated_double: 1.234567898765\n"
 603    "repeated_double: 1.2345678987654\n"
 604    "repeated_double: 1.23456789876543\n"
 605    "repeated_double: 1.2e+100\n"
 606    "repeated_double: 1.23e+100\n"
 607    "repeated_double: 1.234e+100\n"
 608    "repeated_double: 1.2345e+100\n"
 609    "repeated_double: 1.23456e+100\n"
 610    "repeated_double: 1.234567e+100\n"
 611    "repeated_double: 1.2345678e+100\n"
 612    "repeated_double: 1.23456789e+100\n"
 613    "repeated_double: 1.234567898e+100\n"
 614    "repeated_double: 1.2345678987e+100\n"
 615    "repeated_double: 1.23456789876e+100\n"
 616    "repeated_double: 1.234567898765e+100\n"
 617    "repeated_double: 1.2345678987654e+100\n"
 618    "repeated_double: 1.23456789876543e+100\n",
 619    RemoveRedundantZeros(message.DebugString()));
 620}
 621
 622
 623TEST_F(TextFormatTest, AllowPartial) {
 624  unittest::TestRequired message;
 625  TextFormat::Parser parser;
 626  parser.AllowPartialMessage(true);
 627  EXPECT_TRUE(parser.ParseFromString("a: 1", &message));
 628  EXPECT_EQ(1, message.a());
 629  EXPECT_FALSE(message.has_b());
 630  EXPECT_FALSE(message.has_c());
 631}
 632
 633TEST_F(TextFormatTest, ParseExotic) {
 634  unittest::TestAllTypes message;
 635  ASSERT_TRUE(TextFormat::ParseFromString(
 636    "repeated_int32: -1\n"
 637    "repeated_int32: -2147483648\n"
 638    "repeated_int64: -1\n"
 639    "repeated_int64: -9223372036854775808\n"
 640    "repeated_uint32: 4294967295\n"
 641    "repeated_uint32: 2147483648\n"
 642    "repeated_uint64: 18446744073709551615\n"
 643    "repeated_uint64: 9223372036854775808\n"
 644    "repeated_double: 123.0\n"
 645    "repeated_double: 123.5\n"
 646    "repeated_double: 0.125\n"
 647    "repeated_double: 1.23E17\n"
 648    "repeated_double: 1.235E+22\n"
 649    "repeated_double: 1.235e-18\n"
 650    "repeated_double: 123.456789\n"
 651    "repeated_double: inf\n"
 652    "repeated_double: Infinity\n"
 653    "repeated_double: -inf\n"
 654    "repeated_double: -Infinity\n"
 655    "repeated_double: nan\n"
 656    "repeated_double: NaN\n"
 657    "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n",
 658    &message));
 659
 660  ASSERT_EQ(2, message.repeated_int32_size());
 661  EXPECT_EQ(-1, message.repeated_int32(0));
 662  // Note:  In C, a negative integer literal is actually the unary negation
 663  //   operator being applied to a positive integer literal, and 2147483648 is
 664  //   outside the range of int32.  However, it is not outside the range of
 665  //   uint32.  Confusingly, this means that everything works if we make the
 666  //   literal unsigned, even though we are negating it.
 667  EXPECT_EQ(-2147483648u, message.repeated_int32(1));
 668
 669  ASSERT_EQ(2, message.repeated_int64_size());
 670  EXPECT_EQ(-1, message.repeated_int64(0));
 671  // Note:  In C, a negative integer literal is actually the unary negation
 672  //   operator being applied to a positive integer literal, and
 673  //   9223372036854775808 is outside the range of int64.  However, it is not
 674  //   outside the range of uint64.  Confusingly, this means that everything
 675  //   works if we make the literal unsigned, even though we are negating it.
 676  EXPECT_EQ(-GOOGLE_ULONGLONG(9223372036854775808), message.repeated_int64(1));
 677
 678  ASSERT_EQ(2, message.repeated_uint32_size());
 679  EXPECT_EQ(4294967295u, message.repeated_uint32(0));
 680  EXPECT_EQ(2147483648u, message.repeated_uint32(1));
 681
 682  ASSERT_EQ(2, message.repeated_uint64_size());
 683  EXPECT_EQ(GOOGLE_ULONGLONG(18446744073709551615), message.repeated_uint64(0));
 684  EXPECT_EQ(GOOGLE_ULONGLONG(9223372036854775808), message.repeated_uint64(1));
 685
 686  ASSERT_EQ(13, message.repeated_double_size());
 687  EXPECT_EQ(123.0     , message.repeated_double(0));
 688  EXPECT_EQ(123.5     , message.repeated_double(1));
 689  EXPECT_EQ(0.125     , message.repeated_double(2));
 690  EXPECT_EQ(1.23E17   , message.repeated_double(3));
 691  EXPECT_EQ(1.235E22  , message.repeated_double(4));
 692  EXPECT_EQ(1.235E-18 , message.repeated_double(5));
 693  EXPECT_EQ(123.456789, message.repeated_double(6));
 694  EXPECT_EQ(message.repeated_double(7), numeric_limits<double>::infinity());
 695  EXPECT_EQ(message.repeated_double(8), numeric_limits<double>::infinity());
 696  EXPECT_EQ(message.repeated_double(9), -numeric_limits<double>::infinity());
 697  EXPECT_EQ(message.repeated_double(10), -numeric_limits<double>::infinity());
 698  EXPECT_TRUE(IsNaN(message.repeated_double(11)));
 699  EXPECT_TRUE(IsNaN(message.repeated_double(12)));
 700
 701  // Note:  Since these string literals have \0's in them, we must explicitly
 702  //   pass their sizes to string's constructor.
 703  ASSERT_EQ(1, message.repeated_string_size());
 704  EXPECT_EQ(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12),
 705            message.repeated_string(0));
 706}
 707
 708class TextFormatParserTest : public testing::Test {
 709 protected:
 710  void ExpectFailure(const string& input, const string& message, int line,
 711                     int col) {
 712    scoped_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes);
 713    ExpectFailure(input, message, line, col, proto.get());
 714  }
 715
 716  void ExpectFailure(const string& input, const string& message, int line,
 717                     int col, Message* proto) {
 718    ExpectMessage(input, message, line, col, proto, false);
 719  }
 720
 721  void ExpectMessage(const string& input, const string& message, int line,
 722                     int col, Message* proto, bool expected_result) {
 723    TextFormat::Parser parser;
 724    MockErrorCollector error_collector;
 725    parser.RecordErrorsTo(&error_collector);
 726    EXPECT_EQ(parser.ParseFromString(input, proto), expected_result);
 727    EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) + ": " + message + "\n",
 728              error_collector.text_);
 729  }
 730
 731  // An error collector which simply concatenates all its errors into a big
 732  // block of text which can be checked.
 733  class MockErrorCollector : public io::ErrorCollector {
 734   public:
 735    MockErrorCollector() {}
 736    ~MockErrorCollector() {}
 737
 738    string text_;
 739
 740    // implements ErrorCollector -------------------------------------
 741    void AddError(int line, int column, const string& message) {
 742      strings::SubstituteAndAppend(&text_, "$0:$1: $2\n",
 743                                   line + 1, column + 1, message);
 744    }
 745
 746    void AddWarning(int line, int column, const string& message) {
 747      AddError(line, column, "WARNING:" + message);
 748    }
 749  };
 750};
 751
 752TEST_F(TextFormatParserTest, ParseFieldValueFromString) {
 753  scoped_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
 754  const Descriptor* d = message->GetDescriptor();
 755
 756#define EXPECT_FIELD(name, value, valuestring) \
 757  EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
 758    valuestring, d->FindFieldByName("optional_" #name), message.get())); \
 759  EXPECT_EQ(value, message->optional_##name()); \
 760  EXPECT_TRUE(message->has_optional_##name());
 761
 762#define EXPECT_FLOAT_FIELD(name, value, valuestring) \
 763  EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
 764    valuestring, d->FindFieldByName("optional_" #name), message.get())); \
 765  EXPECT_FLOAT_EQ(value, message->optional_##name()); \
 766  EXPECT_TRUE(message->has_optional_##name());
 767
 768#define EXPECT_DOUBLE_FIELD(name, value, valuestring) \
 769  EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
 770    valuestring, d->FindFieldByName("optional_" #name), message.get())); \
 771  EXPECT_DOUBLE_EQ(value, message->optional_##name()); \
 772  EXPECT_TRUE(message->has_optional_##name());
 773
 774#define EXPECT_INVALID(name, valuestring) \
 775  EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \
 776    valuestring, d->FindFieldByName("optional_" #name), message.get()));
 777
 778  // int32
 779  EXPECT_FIELD(int32, 1, "1");
 780  EXPECT_FIELD(int32, -1, "-1");
 781  EXPECT_FIELD(int32, 0x1234, "0x1234");
 782  EXPECT_INVALID(int32, "a");
 783  EXPECT_INVALID(int32, "999999999999999999999999999999999999");
 784  EXPECT_INVALID(int32, "1,2");
 785
 786  // int64
 787  EXPECT_FIELD(int64, 1, "1");
 788  EXPECT_FIELD(int64, -1, "-1");
 789  EXPECT_FIELD(int64, 0x1234567812345678LL, "0x1234567812345678");
 790  EXPECT_INVALID(int64, "a");
 791  EXPECT_INVALID(int64, "999999999999999999999999999999999999");
 792  EXPECT_INVALID(int64, "1,2");
 793
 794  // uint64
 795  EXPECT_FIELD(uint64, 1, "1");
 796  EXPECT_FIELD(uint64, 0xf234567812345678ULL, "0xf234567812345678");
 797  EXPECT_INVALID(uint64, "-1");
 798  EXPECT_INVALID(uint64, "a");
 799  EXPECT_INVALID(uint64, "999999999999999999999999999999999999");
 800  EXPECT_INVALID(uint64, "1,2");
 801
 802  // fixed32
 803  EXPECT_FIELD(fixed32, 1, "1");
 804  EXPECT_FIELD(fixed32, 0x12345678, "0x12345678");
 805  EXPECT_INVALID(fixed32, "-1");
 806  EXPECT_INVALID(fixed32, "a");
 807  EXPECT_INVALID(fixed32, "999999999999999999999999999999999999");
 808  EXPECT_INVALID(fixed32, "1,2");
 809
 810  // fixed64
 811  EXPECT_FIELD(fixed64, 1, "1");
 812  EXPECT_FIELD(fixed64, 0x1234567812345678ULL, "0x1234567812345678");
 813  EXPECT_INVALID(fixed64, "-1");
 814  EXPECT_INVALID(fixed64, "a");
 815  EXPECT_INVALID(fixed64, "999999999999999999999999999999999999");
 816  EXPECT_INVALID(fixed64, "1,2");
 817
 818  // bool
 819  EXPECT_FIELD(bool, true, "true");
 820  EXPECT_FIELD(bool, false, "false");
 821  EXPECT_FIELD(bool, true, "1");
 822  EXPECT_FIELD(bool, true, "t");
 823  EXPECT_FIELD(bool, false, "0");
 824  EXPECT_FIELD(bool, false, "f");
 825  EXPECT_INVALID(bool, "2");
 826  EXPECT_INVALID(bool, "-0");
 827  EXPECT_INVALID(bool, "on");
 828  EXPECT_INVALID(bool, "a");
 829  EXPECT_INVALID(bool, "True");
 830
 831  // float
 832  EXPECT_FIELD(float, 1, "1");
 833  EXPECT_FLOAT_FIELD(float, 1.5, "1.5");
 834  EXPECT_FLOAT_FIELD(float, 1.5e3, "1.5e3");
 835  EXPECT_FLOAT_FIELD(float, -4.55, "-4.55");
 836  EXPECT_INVALID(float, "a");
 837  EXPECT_INVALID(float, "1,2");
 838
 839  // double
 840  EXPECT_FIELD(double, 1, "1");
 841  EXPECT_FIELD(double, -1, "-1");
 842  EXPECT_DOUBLE_FIELD(double, 2.3, "2.3");
 843  EXPECT_DOUBLE_FIELD(double, 3e5, "3e5");
 844  EXPECT_INVALID(double, "a");
 845  EXPECT_INVALID(double, "1,2");
 846
 847  // string
 848  EXPECT_FIELD(string, "hello", "\"hello\"");
 849  EXPECT_FIELD(string, "-1.87", "'-1.87'");
 850  EXPECT_INVALID(string, "hello");  // without quote for value
 851
 852  // enum
 853  EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR");
 854  EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ,
 855               SimpleItoa(unittest::TestAllTypes::BAZ));
 856  EXPECT_INVALID(nested_enum, "FOOBAR");
 857
 858  // message
 859  EXPECT_TRUE(TextFormat::ParseFieldValueFromString(
 860    "<bb:12>", d->FindFieldByName("optional_nested_message"), message.get()));
 861  EXPECT_EQ(12, message->optional_nested_message().bb()); \
 862  EXPECT_TRUE(message->has_optional_nested_message());
 863  EXPECT_INVALID(nested_message, "any");
 864
 865#undef EXPECT_FIELD
 866#undef EXPECT_FLOAT_FIELD
 867#undef EXPECT_DOUBLE_FIELD
 868#undef EXPECT_INVALID
 869}
 870
 871
 872TEST_F(TextFormatParserTest, InvalidToken) {
 873  ExpectFailure("optional_bool: true\n-5\n", "Expected identifier.",
 874                2, 1);
 875
 876  ExpectFailure("optional_bool: true!\n", "Expected identifier.", 1, 20);
 877  ExpectFailure("\"some string\"", "Expected identifier.", 1, 1);
 878}
 879
 880TEST_F(TextFormatParserTest, InvalidFieldName) {
 881  ExpectFailure(
 882      "invalid_field: somevalue\n",
 883      "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
 884      "\"invalid_field\".",
 885      1, 14);
 886}
 887
 888TEST_F(TextFormatParserTest, InvalidCapitalization) {
 889  // We require that group names be exactly as they appear in the .proto.
 890  ExpectFailure(
 891      "optionalgroup {\na: 15\n}\n",
 892      "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
 893      "\"optionalgroup\".",
 894      1, 15);
 895  ExpectFailure(
 896      "OPTIONALgroup {\na: 15\n}\n",
 897      "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
 898      "\"OPTIONALgroup\".",
 899      1, 15);
 900  ExpectFailure(
 901      "Optional_Double: 10.0\n",
 902      "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
 903      "\"Optional_Double\".",
 904      1, 16);
 905}
 906
 907TEST_F(TextFormatParserTest, InvalidFieldValues) {
 908  // Invalid values for a double/float field.
 909  ExpectFailure("optional_double: \"hello\"\n", "Expected double.", 1, 18);
 910  ExpectFailure("optional_double: true\n", "Expected double.", 1, 18);
 911  ExpectFailure("optional_double: !\n", "Expected double.", 1, 18);
 912  ExpectFailure("optional_double {\n  \n}\n", "Expected \":\", found \"{\".",
 913                1, 17);
 914
 915  // Invalid values for a signed integer field.
 916  ExpectFailure("optional_int32: \"hello\"\n", "Expected integer.", 1, 17);
 917  ExpectFailure("optional_int32: true\n", "Expected integer.", 1, 17);
 918  ExpectFailure("optional_int32: 4.5\n", "Expected integer.", 1, 17);
 919  ExpectFailure("optional_int32: !\n", "Expected integer.", 1, 17);
 920  ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".",
 921                1, 16);
 922  ExpectFailure("optional_int32: 0x80000000\n",
 923                "Integer out of range.", 1, 17);
 924  ExpectFailure("optional_int32: -0x80000001\n",
 925                "Integer out of range.", 1, 18);
 926  ExpectFailure("optional_int64: 0x8000000000000000\n",
 927                "Integer out of range.", 1, 17);
 928  ExpectFailure("optional_int64: -0x8000000000000001\n",
 929                "Integer out of range.", 1, 18);
 930
 931  // Invalid values for an unsigned integer field.
 932  ExpectFailure("optional_uint64: \"hello\"\n", "Expected integer.", 1, 18);
 933  ExpectFailure("optional_uint64: true\n", "Expected integer.", 1, 18);
 934  ExpectFailure("optional_uint64: 4.5\n", "Expected integer.", 1, 18);
 935  ExpectFailure("optional_uint64: -5\n", "Expected integer.", 1, 18);
 936  ExpectFailure("optional_uint64: !\n", "Expected integer.", 1, 18);
 937  ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".",
 938                1, 17);
 939  ExpectFailure("optional_uint32: 0x100000000\n",
 940                "Integer out of range.", 1, 18);
 941  ExpectFailure("optional_uint64: 0x10000000000000000\n",
 942                "Integer out of range.", 1, 18);
 943
 944  // Invalid values for a boolean field.
 945  ExpectFailure("optional_bool: \"hello\"\n", "Expected identifier.", 1, 16);
 946  ExpectFailure("optional_bool: 5\n", "Integer out of range.", 1, 16);
 947  ExpectFailure("optional_bool: -7.5\n", "Expected identifier.", 1, 16);
 948  ExpectFailure("optional_bool: !\n", "Expected identifier.", 1, 16);
 949
 950  ExpectFailure(
 951      "optional_bool: meh\n",
 952      "Invalid value for boolean field \"optional_bool\". Value: \"meh\".",
 953      2, 1);
 954
 955  ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".",
 956                1, 15);
 957
 958  // Invalid values for a string field.
 959  ExpectFailure("optional_string: true\n", "Expected string.", 1, 18);
 960  ExpectFailure("optional_string: 5\n", "Expected string.", 1, 18);
 961  ExpectFailure("optional_string: -7.5\n", "Expected string.", 1, 18);
 962  ExpectFailure("optional_string: !\n", "Expected string.", 1, 18);
 963  ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".",
 964                1, 17);
 965
 966  // Invalid values for an enumeration field.
 967  ExpectFailure("optional_nested_enum: \"hello\"\n",
 968                "Expected integer or identifier.", 1, 23);
 969
 970  // Valid token, but enum value is not defined.
 971  ExpectFailure("optional_nested_enum: 5\n",
 972                "Unknown enumeration value of \"5\" for field "
 973                "\"optional_nested_enum\".", 2, 1);
 974  // We consume the negative sign, so the error position starts one character
 975  // later.
 976  ExpectFailure("optional_nested_enum: -7.5\n", "Expected integer.", 1, 24);
 977  ExpectFailure("optional_nested_enum: !\n",
 978                "Expected integer or identifier.", 1, 23);
 979
 980  ExpectFailure(
 981      "optional_nested_enum: grah\n",
 982      "Unknown enumeration value of \"grah\" for field "
 983      "\"optional_nested_enum\".", 2, 1);
 984
 985  ExpectFailure(
 986      "optional_nested_enum {\n \n}\n",
 987      "Expected \":\", found \"{\".", 1, 22);
 988}
 989
 990TEST_F(TextFormatParserTest, MessageDelimeters) {
 991  // Non-matching delimeters.
 992  ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".",
 993                3, 1);
 994
 995  // Invalid delimeters.
 996  ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".",
 997                1, 15);
 998
 999  // Unending message.
1000  ExpectFailure("optional_nested_message {\n \nbb: 118\n",
1001                "Expected identifier.",
1002                4, 1);
1003}
1004
1005TEST_F(TextFormatParserTest, UnknownExtension) {
1006  // Non-matching delimeters.
1007  ExpectFailure("[blahblah]: 123",
1008                "Extension \"blahblah\" is not defined or is not an "
1009                "extension of \"protobuf_unittest.TestAllTypes\".",
1010                1, 11);
1011}
1012
1013TEST_F(TextFormatParserTest, MissingRequired) {
1014  unittest::TestRequired message;
1015  ExpectFailure("a: 1",
1016                "Message missing required fields: b, c",
1017                0, 1, &message);
1018}
1019
1020TEST_F(TextFormatParserTest, ParseDuplicateRequired) {
1021  unittest::TestRequired message;
1022  ExpectFailure("a: 1 b: 2 c: 3 a: 1",
1023                "Non-repeated field \"a\" is specified multiple times.",
1024                1, 17, &message);
1025}
1026
1027TEST_F(TextFormatParserTest, ParseDuplicateOptional) {
1028  unittest::ForeignMessage message;
1029  ExpectFailure("c: 1 c: 2",
1030                "Non-repeated field \"c\" is specified multiple times.",
1031                1, 7, &message);
1032}
1033
1034TEST_F(TextFormatParserTest, MergeDuplicateRequired) {
1035  unittest::TestRequired message;
1036  TextFormat::Parser parser;
1037  EXPECT_TRUE(parser.MergeFromString("a: 1 b: 2 c: 3 a: 4", &message));
1038  EXPECT_EQ(4, message.a());
1039}
1040
1041TEST_F(TextFormatParserTest, MergeDuplicateOptional) {
1042  unittest::ForeignMessage message;
1043  TextFormat::Parser parser;
1044  EXPECT_TRUE(parser.MergeFromString("c: 1 c: 2", &message));
1045  EXPECT_EQ(2, message.c());
1046}
1047
1048TEST_F(TextFormatParserTest, ExplicitDelimiters) {
1049  unittest::TestRequired message;
1050  EXPECT_TRUE(TextFormat::ParseFromString("a:1,b:2;c:3", &message));
1051  EXPECT_EQ(1, message.a());
1052  EXPECT_EQ(2, message.b());
1053  EXPECT_EQ(3, message.c());
1054}
1055
1056TEST_F(TextFormatParserTest, PrintErrorsToStderr) {
1057  vector<string> errors;
1058
1059  {
1060    ScopedMemoryLog log;
1061    unittest::TestAllTypes proto;
1062    EXPECT_FALSE(TextFormat::ParseFromString("no_such_field: 1", &proto));
1063    errors = log.GetMessages(ERROR);
1064  }
1065
1066  ASSERT_EQ(1, errors.size());
1067  EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: "
1068            "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field "
1069            "named \"no_such_field\".",
1070            errors[0]);
1071}
1072
1073TEST_F(TextFormatParserTest, FailsOnTokenizationError) {
1074  vector<string> errors;
1075
1076  {
1077    ScopedMemoryLog log;
1078    unittest::TestAllTypes proto;
1079    EXPECT_FALSE(TextFormat::ParseFromString("\020", &proto));
1080    errors = log.GetMessages(ERROR);
1081  }
1082
1083  ASSERT_EQ(1, errors.size());
1084  EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: "
1085            "1:1: Invalid control characters encountered in text.",
1086            errors[0]);
1087}
1088
1089TEST_F(TextFormatParserTest, ParseDeprecatedField) {
1090  unittest::TestDeprecatedFields message;
1091  ExpectMessage("deprecated_int32: 42",
1092                "WARNING:text format contains deprecated field "
1093                "\"deprecated_int32\"", 1, 21, &message, true);
1094}
1095
1096class TextFormatMessageSetTest : public testing::Test {
1097 protected:
1098  static const char proto_debug_string_[];
1099};
1100const char TextFormatMessageSetTest::proto_debug_string_[] =
1101"message_set {\n"
1102"  [protobuf_unittest.TestMessageSetExtension1] {\n"
1103"    i: 23\n"
1104"  }\n"
1105"  [protobuf_unittest.TestMessageSetExtension2] {\n"
1106"    str: \"foo\"\n"
1107"  }\n"
1108"}\n";
1109
1110
1111TEST_F(TextFormatMessageSetTest, Serialize) {
1112  protobuf_unittest::TestMessageSetContainer proto;
1113  protobuf_unittest::TestMessageSetExtension1* item_a =
1114    proto.mutable_message_set()->MutableExtension(
1115      protobuf_unittest::TestMessageSetExtension1::message_set_extension);
1116  item_a->set_i(23);
1117  protobuf_unittest::TestMessageSetExtension2* item_b =
1118    proto.mutable_message_set()->MutableExtension(
1119      protobuf_unittest::TestMessageSetExtension2::message_set_extension);
1120  item_b->set_str("foo");
1121  EXPECT_EQ(proto_debug_string_, proto.DebugString());
1122}
1123
1124TEST_F(TextFormatMessageSetTest, Deserialize) {
1125  protobuf_unittest::TestMessageSetContainer proto;
1126  ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto));
1127  EXPECT_EQ(23, proto.message_set().GetExtension(
1128    protobuf_unittest::TestMessageSetExtension1::message_set_extension).i());
1129  EXPECT_EQ("foo", proto.message_set().GetExtension(
1130    protobuf_unittest::TestMessageSetExtension2::message_set_extension).str());
1131
1132  // Ensure that these are the only entries present.
1133  vector<const FieldDescriptor*> descriptors;
1134  proto.message_set().GetReflection()->ListFields(
1135    proto.message_set(), &descriptors);
1136  EXPECT_EQ(2, descriptors.size());
1137}
1138
1139}  // namespace text_format_unittest
1140}  // namespace protobuf
1141}  // namespace google