• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
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 <google/protobuf/text_format.h>
36 
37 #include <math.h>
38 #include <stdlib.h>
39 
40 #include <limits>
41 #include <memory>
42 
43 #include <google/protobuf/stubs/logging.h>
44 #include <google/protobuf/stubs/common.h>
45 #include <google/protobuf/stubs/logging.h>
46 #include <google/protobuf/testing/file.h>
47 #include <google/protobuf/testing/file.h>
48 #include <google/protobuf/map_unittest.pb.h>
49 #include <google/protobuf/test_util.h>
50 #include <google/protobuf/test_util2.h>
51 #include <google/protobuf/unittest.pb.h>
52 #include <google/protobuf/unittest_mset.pb.h>
53 #include <google/protobuf/unittest_mset_wire_format.pb.h>
54 #include <google/protobuf/unittest_proto3.pb.h>
55 #include <google/protobuf/io/tokenizer.h>
56 #include <google/protobuf/io/zero_copy_stream_impl.h>
57 #include <google/protobuf/stubs/strutil.h>
58 #include <gmock/gmock.h>
59 #include <google/protobuf/testing/googletest.h>
60 #include <gtest/gtest.h>
61 #include <google/protobuf/stubs/substitute.h>
62 
63 
64 #include <google/protobuf/port_def.inc>
65 
66 namespace google {
67 namespace protobuf {
68 
69 // Can't use an anonymous namespace here due to brokenness of Tru64 compiler.
70 namespace text_format_unittest {
71 
72 // A basic string with different escapable characters for testing.
73 const std::string kEscapeTestString =
74     "\"A string with ' characters \n and \r newlines and \t tabs and \001 "
75     "slashes \\ and  multiple   spaces";
76 
77 // A representation of the above string with all the characters escaped.
78 const std::string kEscapeTestStringEscaped =
79     "\"\\\"A string with \\' characters \\n and \\r newlines "
80     "and \\t tabs and \\001 slashes \\\\ and  multiple   spaces\"";
81 
82 class TextFormatTest : public testing::Test {
83  public:
SetUpTestSuite()84   static void SetUpTestSuite() {
85     GOOGLE_CHECK_OK(File::GetContents(
86         TestUtil::GetTestDataPath(
87             "net/proto2/internal/"
88             "testdata/text_format_unittest_data_oneof_implemented.txt"),
89         &static_proto_debug_string_, true));
90     CleanStringLineEndings(&static_proto_debug_string_, false);
91   }
92 
TextFormatTest()93   TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {}
94 
95  protected:
96   // Debug string read from text_format_unittest_data.txt.
97   const std::string proto_debug_string_;
98   unittest::TestAllTypes proto_;
99 
100  private:
101   static std::string static_proto_debug_string_;
102 };
103 std::string TextFormatTest::static_proto_debug_string_;
104 
105 class TextFormatExtensionsTest : public testing::Test {
106  public:
SetUpTestSuite()107   static void SetUpTestSuite() {
108     GOOGLE_CHECK_OK(File::GetContents(
109         TestUtil::GetTestDataPath("net/proto2/internal/testdata/"
110                                   "text_format_unittest_extensions_data.txt"),
111         &static_proto_debug_string_, true));
112     CleanStringLineEndings(&static_proto_debug_string_, false);
113   }
114 
TextFormatExtensionsTest()115   TextFormatExtensionsTest()
116       : proto_debug_string_(static_proto_debug_string_) {}
117 
118  protected:
119   // Debug string read from text_format_unittest_data.txt.
120   const std::string proto_debug_string_;
121   unittest::TestAllExtensions proto_;
122 
123  private:
124   static std::string static_proto_debug_string_;
125 };
126 std::string TextFormatExtensionsTest::static_proto_debug_string_;
127 
TEST_F(TextFormatTest,Basic)128 TEST_F(TextFormatTest, Basic) {
129   TestUtil::SetAllFields(&proto_);
130   EXPECT_EQ(proto_debug_string_, proto_.DebugString());
131 }
132 
TEST_F(TextFormatExtensionsTest,Extensions)133 TEST_F(TextFormatExtensionsTest, Extensions) {
134   TestUtil::SetAllExtensions(&proto_);
135   EXPECT_EQ(proto_debug_string_, proto_.DebugString());
136 }
137 
TEST_F(TextFormatTest,ShortDebugString)138 TEST_F(TextFormatTest, ShortDebugString) {
139   proto_.set_optional_int32(1);
140   proto_.set_optional_string("hello");
141   proto_.mutable_optional_nested_message()->set_bb(2);
142   proto_.mutable_optional_foreign_message();
143 
144   EXPECT_EQ(
145       "optional_int32: 1 optional_string: \"hello\" "
146       "optional_nested_message { bb: 2 } "
147       "optional_foreign_message { }",
148       proto_.ShortDebugString());
149 }
150 
TEST_F(TextFormatTest,ShortPrimitiveRepeateds)151 TEST_F(TextFormatTest, ShortPrimitiveRepeateds) {
152   proto_.set_optional_int32(123);
153   proto_.add_repeated_int32(456);
154   proto_.add_repeated_int32(789);
155   proto_.add_repeated_string("foo");
156   proto_.add_repeated_string("bar");
157   proto_.add_repeated_nested_message()->set_bb(2);
158   proto_.add_repeated_nested_message()->set_bb(3);
159   proto_.add_repeated_nested_enum(unittest::TestAllTypes::FOO);
160   proto_.add_repeated_nested_enum(unittest::TestAllTypes::BAR);
161 
162   TextFormat::Printer printer;
163   printer.SetUseShortRepeatedPrimitives(true);
164   std::string text;
165   EXPECT_TRUE(printer.PrintToString(proto_, &text));
166 
167   EXPECT_EQ(
168       "optional_int32: 123\n"
169       "repeated_int32: [456, 789]\n"
170       "repeated_string: \"foo\"\n"
171       "repeated_string: \"bar\"\n"
172       "repeated_nested_message {\n  bb: 2\n}\n"
173       "repeated_nested_message {\n  bb: 3\n}\n"
174       "repeated_nested_enum: [FOO, BAR]\n",
175       text);
176 
177   // Verify that any existing data in the string is cleared when PrintToString()
178   // is called.
179   text = "just some data here...\n\nblah blah";
180   EXPECT_TRUE(printer.PrintToString(proto_, &text));
181 
182   EXPECT_EQ(
183       "optional_int32: 123\n"
184       "repeated_int32: [456, 789]\n"
185       "repeated_string: \"foo\"\n"
186       "repeated_string: \"bar\"\n"
187       "repeated_nested_message {\n  bb: 2\n}\n"
188       "repeated_nested_message {\n  bb: 3\n}\n"
189       "repeated_nested_enum: [FOO, BAR]\n",
190       text);
191 
192   // Try in single-line mode.
193   printer.SetSingleLineMode(true);
194   EXPECT_TRUE(printer.PrintToString(proto_, &text));
195 
196   EXPECT_EQ(
197       "optional_int32: 123 "
198       "repeated_int32: [456, 789] "
199       "repeated_string: \"foo\" "
200       "repeated_string: \"bar\" "
201       "repeated_nested_message { bb: 2 } "
202       "repeated_nested_message { bb: 3 } "
203       "repeated_nested_enum: [FOO, BAR] ",
204       text);
205 }
206 
207 
TEST_F(TextFormatTest,StringEscape)208 TEST_F(TextFormatTest, StringEscape) {
209   // Set the string value to test.
210   proto_.set_optional_string(kEscapeTestString);
211 
212   // Get the DebugString from the proto.
213   std::string debug_string = proto_.DebugString();
214   std::string utf8_debug_string = proto_.Utf8DebugString();
215 
216   // Hardcode a correct value to test against.
217   std::string correct_string =
218       "optional_string: " + kEscapeTestStringEscaped + "\n";
219 
220   // Compare.
221   EXPECT_EQ(correct_string, debug_string);
222   // UTF-8 string is the same as non-UTF-8 because
223   // the protocol buffer contains no UTF-8 text.
224   EXPECT_EQ(correct_string, utf8_debug_string);
225 
226   std::string expected_short_debug_string =
227       "optional_string: " + kEscapeTestStringEscaped;
228   EXPECT_EQ(expected_short_debug_string, proto_.ShortDebugString());
229 }
230 
TEST_F(TextFormatTest,Utf8DebugString)231 TEST_F(TextFormatTest, Utf8DebugString) {
232   // Set the string value to test.
233   proto_.set_optional_string("\350\260\267\346\255\214");
234   proto_.set_optional_bytes("\350\260\267\346\255\214");
235 
236   // Get the DebugString from the proto.
237   std::string debug_string = proto_.DebugString();
238   std::string utf8_debug_string = proto_.Utf8DebugString();
239 
240   // Hardcode a correct value to test against.
241   std::string correct_utf8_string =
242       "optional_string: "
243       "\"\350\260\267\346\255\214\""
244       "\n"
245       "optional_bytes: "
246       "\"\\350\\260\\267\\346\\255\\214\""
247       "\n";
248   std::string correct_string =
249       "optional_string: "
250       "\"\\350\\260\\267\\346\\255\\214\""
251       "\n"
252       "optional_bytes: "
253       "\"\\350\\260\\267\\346\\255\\214\""
254       "\n";
255 
256   // Compare.
257   EXPECT_EQ(correct_utf8_string, utf8_debug_string);
258   EXPECT_EQ(correct_string, debug_string);
259 }
260 
TEST_F(TextFormatTest,PrintUnknownFields)261 TEST_F(TextFormatTest, PrintUnknownFields) {
262   // Test printing of unknown fields in a message.
263 
264   unittest::TestEmptyMessage message;
265   UnknownFieldSet* unknown_fields = message.mutable_unknown_fields();
266 
267   unknown_fields->AddVarint(5, 1);
268   unknown_fields->AddFixed32(5, 2);
269   unknown_fields->AddFixed64(5, 3);
270   unknown_fields->AddLengthDelimited(5, "4");
271   unknown_fields->AddGroup(5)->AddVarint(10, 5);
272 
273   unknown_fields->AddVarint(8, 1);
274   unknown_fields->AddVarint(8, 2);
275   unknown_fields->AddVarint(8, 3);
276 
277   EXPECT_EQ(
278       "5: 1\n"
279       "5: 0x00000002\n"
280       "5: 0x0000000000000003\n"
281       "5: \"4\"\n"
282       "5 {\n"
283       "  10: 5\n"
284       "}\n"
285       "8: 1\n"
286       "8: 2\n"
287       "8: 3\n",
288       message.DebugString());
289 }
290 
TEST_F(TextFormatTest,PrintUnknownFieldsHidden)291 TEST_F(TextFormatTest, PrintUnknownFieldsHidden) {
292   // Test printing of unknown fields in a message when suppressed.
293 
294   unittest::OneString message;
295   message.set_data("data");
296   UnknownFieldSet* unknown_fields = message.mutable_unknown_fields();
297 
298   unknown_fields->AddVarint(5, 1);
299   unknown_fields->AddFixed32(5, 2);
300   unknown_fields->AddFixed64(5, 3);
301   unknown_fields->AddLengthDelimited(5, "4");
302   unknown_fields->AddGroup(5)->AddVarint(10, 5);
303 
304   unknown_fields->AddVarint(8, 1);
305   unknown_fields->AddVarint(8, 2);
306   unknown_fields->AddVarint(8, 3);
307 
308   TextFormat::Printer printer;
309   printer.SetHideUnknownFields(true);
310   std::string output;
311   printer.PrintToString(message, &output);
312 
313   EXPECT_EQ("data: \"data\"\n", output);
314 }
315 
TEST_F(TextFormatTest,PrintUnknownMessage)316 TEST_F(TextFormatTest, PrintUnknownMessage) {
317   // Test heuristic printing of messages in an UnknownFieldSet.
318 
319   protobuf_unittest::TestAllTypes message;
320 
321   // Cases which should not be interpreted as sub-messages.
322 
323   // 'a' is a valid FIXED64 tag, so for the string to be parseable as a message
324   // it should be followed by 8 bytes.  Since this string only has two
325   // subsequent bytes, it should be treated as a string.
326   message.add_repeated_string("abc");
327 
328   // 'd' happens to be a valid ENDGROUP tag.  So,
329   // UnknownFieldSet::MergeFromCodedStream() will successfully parse "def", but
330   // the ConsumedEntireMessage() check should fail.
331   message.add_repeated_string("def");
332 
333   // A zero-length string should never be interpreted as a message even though
334   // it is technically valid as one.
335   message.add_repeated_string("");
336 
337   // Case which should be interpreted as a sub-message.
338 
339   // An actual nested message with content should always be interpreted as a
340   // nested message.
341   message.add_repeated_nested_message()->set_bb(123);
342 
343   std::string data;
344   message.SerializeToString(&data);
345 
346   std::string text;
347   UnknownFieldSet unknown_fields;
348   EXPECT_TRUE(unknown_fields.ParseFromString(data));
349   EXPECT_TRUE(TextFormat::PrintUnknownFieldsToString(unknown_fields, &text));
350   // Field 44 and 48 can be printed in any order.
351   EXPECT_THAT(text, testing::HasSubstr("44: \"abc\"\n"
352                                        "44: \"def\"\n"
353                                        "44: \"\"\n"));
354   EXPECT_THAT(text, testing::HasSubstr("48 {\n"
355                                        "  1: 123\n"
356                                        "}\n"));
357 }
358 
TEST_F(TextFormatTest,PrintDeeplyNestedUnknownMessage)359 TEST_F(TextFormatTest, PrintDeeplyNestedUnknownMessage) {
360   // Create a deeply nested message.
361   static constexpr int kNestingDepth = 25000;
362   static constexpr int kUnknownFieldNumber = 1;
363   std::vector<int> lengths;
364   lengths.reserve(kNestingDepth);
365   lengths.push_back(0);
366   for (int i = 0; i < kNestingDepth - 1; ++i) {
367     lengths.push_back(
368         internal::WireFormatLite::TagSize(
369             kUnknownFieldNumber, internal::WireFormatLite::TYPE_BYTES) +
370         internal::WireFormatLite::LengthDelimitedSize(lengths.back()));
371   }
372   std::string serialized;
373   {
374     io::StringOutputStream zero_copy_stream(&serialized);
375     io::CodedOutputStream coded_stream(&zero_copy_stream);
376     for (int i = kNestingDepth - 1; i >= 0; --i) {
377       internal::WireFormatLite::WriteTag(
378           kUnknownFieldNumber,
379           internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, &coded_stream);
380       coded_stream.WriteVarint32(lengths[i]);
381     }
382   }
383 
384   // Parse the data and verify that we can print it without overflowing the
385   // stack.
386   unittest::TestEmptyMessage message;
387   ASSERT_TRUE(message.ParseFromString(serialized));
388   std::string text;
389   EXPECT_TRUE(TextFormat::PrintToString(message, &text));
390 }
391 
TEST_F(TextFormatTest,PrintMessageWithIndent)392 TEST_F(TextFormatTest, PrintMessageWithIndent) {
393   // Test adding an initial indent to printing.
394 
395   protobuf_unittest::TestAllTypes message;
396 
397   message.add_repeated_string("abc");
398   message.add_repeated_string("def");
399   message.add_repeated_nested_message()->set_bb(123);
400 
401   std::string text;
402   TextFormat::Printer printer;
403   printer.SetInitialIndentLevel(1);
404   EXPECT_TRUE(printer.PrintToString(message, &text));
405   EXPECT_EQ(
406       "  repeated_string: \"abc\"\n"
407       "  repeated_string: \"def\"\n"
408       "  repeated_nested_message {\n"
409       "    bb: 123\n"
410       "  }\n",
411       text);
412 }
413 
TEST_F(TextFormatTest,PrintMessageSingleLine)414 TEST_F(TextFormatTest, PrintMessageSingleLine) {
415   // Test printing a message on a single line.
416 
417   protobuf_unittest::TestAllTypes message;
418 
419   message.add_repeated_string("abc");
420   message.add_repeated_string("def");
421   message.add_repeated_nested_message()->set_bb(123);
422 
423   std::string text;
424   TextFormat::Printer printer;
425   printer.SetInitialIndentLevel(1);
426   printer.SetSingleLineMode(true);
427   EXPECT_TRUE(printer.PrintToString(message, &text));
428   EXPECT_EQ(
429       "  repeated_string: \"abc\" repeated_string: \"def\" "
430       "repeated_nested_message { bb: 123 } ",
431       text);
432 }
433 
TEST_F(TextFormatTest,PrintBufferTooSmall)434 TEST_F(TextFormatTest, PrintBufferTooSmall) {
435   // Test printing a message to a buffer that is too small.
436 
437   protobuf_unittest::TestAllTypes message;
438 
439   message.add_repeated_string("abc");
440   message.add_repeated_string("def");
441 
442   char buffer[1] = "";
443   io::ArrayOutputStream output_stream(buffer, 1);
444   EXPECT_FALSE(TextFormat::Print(message, &output_stream));
445   EXPECT_EQ(buffer[0], 'r');
446   EXPECT_EQ(output_stream.ByteCount(), 1);
447 }
448 
449 // A printer that appends 'u' to all unsigned int32.
450 class CustomUInt32FieldValuePrinter : public TextFormat::FieldValuePrinter {
451  public:
PrintUInt32(uint32 val) const452   virtual std::string PrintUInt32(uint32 val) const {
453     return StrCat(FieldValuePrinter::PrintUInt32(val), "u");
454   }
455 };
456 
TEST_F(TextFormatTest,DefaultCustomFieldPrinter)457 TEST_F(TextFormatTest, DefaultCustomFieldPrinter) {
458   protobuf_unittest::TestAllTypes message;
459 
460   message.set_optional_uint32(42);
461   message.add_repeated_uint32(1);
462   message.add_repeated_uint32(2);
463   message.add_repeated_uint32(3);
464 
465   TextFormat::Printer printer;
466   printer.SetDefaultFieldValuePrinter(new CustomUInt32FieldValuePrinter());
467   // Let's see if that works well together with the repeated primitives:
468   printer.SetUseShortRepeatedPrimitives(true);
469   std::string text;
470   printer.PrintToString(message, &text);
471   EXPECT_EQ("optional_uint32: 42u\nrepeated_uint32: [1u, 2u, 3u]\n", text);
472 }
473 
474 class CustomInt32FieldValuePrinter : public TextFormat::FieldValuePrinter {
475  public:
PrintInt32(int32 val) const476   virtual std::string PrintInt32(int32 val) const {
477     return StrCat("value-is(", FieldValuePrinter::PrintInt32(val), ")");
478   }
479 };
480 
TEST_F(TextFormatTest,FieldSpecificCustomPrinter)481 TEST_F(TextFormatTest, FieldSpecificCustomPrinter) {
482   protobuf_unittest::TestAllTypes message;
483 
484   message.set_optional_int32(42);  // This will be handled by our Printer.
485   message.add_repeated_int32(42);  // This will be printed as number.
486 
487   TextFormat::Printer printer;
488   EXPECT_TRUE(printer.RegisterFieldValuePrinter(
489       message.GetDescriptor()->FindFieldByName("optional_int32"),
490       new CustomInt32FieldValuePrinter()));
491   std::string text;
492   printer.PrintToString(message, &text);
493   EXPECT_EQ("optional_int32: value-is(42)\nrepeated_int32: 42\n", text);
494 }
495 
TEST_F(TextFormatTest,FieldSpecificCustomPrinterRegisterSameFieldTwice)496 TEST_F(TextFormatTest, FieldSpecificCustomPrinterRegisterSameFieldTwice) {
497   protobuf_unittest::TestAllTypes message;
498   TextFormat::Printer printer;
499   const FieldDescriptor* const field =
500       message.GetDescriptor()->FindFieldByName("optional_int32");
501   ASSERT_TRUE(printer.RegisterFieldValuePrinter(
502       field, new CustomInt32FieldValuePrinter()));
503   const TextFormat::FieldValuePrinter* const rejected =
504       new CustomInt32FieldValuePrinter();
505   ASSERT_FALSE(printer.RegisterFieldValuePrinter(field, rejected));
506   delete rejected;
507 }
508 
TEST_F(TextFormatTest,ErrorCasesRegisteringFieldValuePrinterShouldFail)509 TEST_F(TextFormatTest, ErrorCasesRegisteringFieldValuePrinterShouldFail) {
510   protobuf_unittest::TestAllTypes message;
511   TextFormat::Printer printer;
512   // NULL printer.
513   EXPECT_FALSE(printer.RegisterFieldValuePrinter(
514       message.GetDescriptor()->FindFieldByName("optional_int32"),
515       static_cast<const TextFormat::FieldValuePrinter*>(nullptr)));
516   EXPECT_FALSE(printer.RegisterFieldValuePrinter(
517       message.GetDescriptor()->FindFieldByName("optional_int32"),
518       static_cast<const TextFormat::FastFieldValuePrinter*>(nullptr)));
519   // Because registration fails, the ownership of this printer is never taken.
520   TextFormat::FieldValuePrinter my_field_printer;
521   // NULL field
522   EXPECT_FALSE(printer.RegisterFieldValuePrinter(nullptr, &my_field_printer));
523 }
524 
525 class CustomMessageFieldValuePrinter : public TextFormat::FieldValuePrinter {
526  public:
PrintInt32(int32 v) const527   virtual std::string PrintInt32(int32 v) const {
528     return StrCat(FieldValuePrinter::PrintInt32(v), "  # x",
529                         strings::Hex(v));
530   }
531 
PrintMessageStart(const Message & message,int field_index,int field_count,bool single_line_mode) const532   virtual std::string PrintMessageStart(const Message& message, int field_index,
533                                         int field_count,
534                                         bool single_line_mode) const {
535     if (single_line_mode) {
536       return " { ";
537     }
538     return StrCat(" {  # ", message.GetDescriptor()->name(), ": ",
539                         field_index, "\n");
540   }
541 };
542 
TEST_F(TextFormatTest,CustomPrinterForComments)543 TEST_F(TextFormatTest, CustomPrinterForComments) {
544   protobuf_unittest::TestAllTypes message;
545   message.mutable_optional_nested_message();
546   message.mutable_optional_import_message()->set_d(42);
547   message.add_repeated_nested_message();
548   message.add_repeated_nested_message();
549   message.add_repeated_import_message()->set_d(43);
550   message.add_repeated_import_message()->set_d(44);
551   TextFormat::Printer printer;
552   CustomMessageFieldValuePrinter my_field_printer;
553   printer.SetDefaultFieldValuePrinter(new CustomMessageFieldValuePrinter());
554   std::string text;
555   printer.PrintToString(message, &text);
556   EXPECT_EQ(
557       "optional_nested_message {  # NestedMessage: -1\n"
558       "}\n"
559       "optional_import_message {  # ImportMessage: -1\n"
560       "  d: 42  # x2a\n"
561       "}\n"
562       "repeated_nested_message {  # NestedMessage: 0\n"
563       "}\n"
564       "repeated_nested_message {  # NestedMessage: 1\n"
565       "}\n"
566       "repeated_import_message {  # ImportMessage: 0\n"
567       "  d: 43  # x2b\n"
568       "}\n"
569       "repeated_import_message {  # ImportMessage: 1\n"
570       "  d: 44  # x2c\n"
571       "}\n",
572       text);
573 }
574 
575 class CustomMessageContentFieldValuePrinter
576     : public TextFormat::FastFieldValuePrinter {
577  public:
PrintMessageContent(const Message & message,int field_index,int field_count,bool single_line_mode,TextFormat::BaseTextGenerator * generator) const578   bool PrintMessageContent(
579       const Message& message, int field_index, int field_count,
580       bool single_line_mode,
581       TextFormat::BaseTextGenerator* generator) const override {
582     if (message.ByteSizeLong() > 0) {
583       generator->PrintString(
584           strings::Substitute("# REDACTED, $0 bytes\n", message.ByteSizeLong()));
585     }
586     return true;
587   }
588 };
589 
TEST_F(TextFormatTest,CustomPrinterForMessageContent)590 TEST_F(TextFormatTest, CustomPrinterForMessageContent) {
591   protobuf_unittest::TestAllTypes message;
592   message.mutable_optional_nested_message();
593   message.mutable_optional_import_message()->set_d(42);
594   message.add_repeated_nested_message();
595   message.add_repeated_nested_message();
596   message.add_repeated_import_message()->set_d(43);
597   message.add_repeated_import_message()->set_d(44);
598   TextFormat::Printer printer;
599   CustomMessageContentFieldValuePrinter my_field_printer;
600   printer.SetDefaultFieldValuePrinter(
601       new CustomMessageContentFieldValuePrinter());
602   std::string text;
603   printer.PrintToString(message, &text);
604   EXPECT_EQ(
605       "optional_nested_message {\n"
606       "}\n"
607       "optional_import_message {\n"
608       "  # REDACTED, 2 bytes\n"
609       "}\n"
610       "repeated_nested_message {\n"
611       "}\n"
612       "repeated_nested_message {\n"
613       "}\n"
614       "repeated_import_message {\n"
615       "  # REDACTED, 2 bytes\n"
616       "}\n"
617       "repeated_import_message {\n"
618       "  # REDACTED, 2 bytes\n"
619       "}\n",
620       text);
621 }
622 
623 class CustomMultilineCommentPrinter : public TextFormat::FieldValuePrinter {
624  public:
PrintMessageStart(const Message & message,int field_index,int field_count,bool single_line_comment) const625   virtual std::string PrintMessageStart(const Message& message, int field_index,
626                                         int field_count,
627                                         bool single_line_comment) const {
628     return StrCat(" {  # 1\n", "  # 2\n");
629   }
630 };
631 
TEST_F(TextFormatTest,CustomPrinterForMultilineComments)632 TEST_F(TextFormatTest, CustomPrinterForMultilineComments) {
633   protobuf_unittest::TestAllTypes message;
634   message.mutable_optional_nested_message();
635   message.mutable_optional_import_message()->set_d(42);
636   TextFormat::Printer printer;
637   CustomMessageFieldValuePrinter my_field_printer;
638   printer.SetDefaultFieldValuePrinter(new CustomMultilineCommentPrinter());
639   std::string text;
640   printer.PrintToString(message, &text);
641   EXPECT_EQ(
642       "optional_nested_message {  # 1\n"
643       "  # 2\n"
644       "}\n"
645       "optional_import_message {  # 1\n"
646       "  # 2\n"
647       "  d: 42\n"
648       "}\n",
649       text);
650 }
651 
652 // Achieve effects similar to SetUseShortRepeatedPrimitives for messages, using
653 // RegisterFieldValuePrinter. Use this to test the version of PrintFieldName
654 // that accepts repeated field index and count.
655 class CompactRepeatedFieldPrinter : public TextFormat::FastFieldValuePrinter {
656  public:
PrintFieldName(const Message & message,int field_index,int field_count,const Reflection * reflection,const FieldDescriptor * field,TextFormat::BaseTextGenerator * generator) const657   void PrintFieldName(const Message& message, int field_index, int field_count,
658                       const Reflection* reflection,
659                       const FieldDescriptor* field,
660                       TextFormat::BaseTextGenerator* generator) const override {
661     if (field_index == 0 || field_index == -1) {
662       generator->PrintString(field->name());
663     }
664   }
665   // To prevent compiler complaining about Woverloaded-virtual
PrintFieldName(const Message & message,const Reflection * reflection,const FieldDescriptor * field,TextFormat::BaseTextGenerator * generator) const666   void PrintFieldName(const Message& message, const Reflection* reflection,
667                       const FieldDescriptor* field,
668                       TextFormat::BaseTextGenerator* generator) const override {
669   }
PrintMessageStart(const Message & message,int field_index,int field_count,bool single_line_mode,TextFormat::BaseTextGenerator * generator) const670   void PrintMessageStart(
671       const Message& message, int field_index, int field_count,
672       bool single_line_mode,
673       TextFormat::BaseTextGenerator* generator) const override {
674     if (field_index == 0 || field_index == -1) {
675       if (single_line_mode) {
676         generator->PrintLiteral(" { ");
677       } else {
678         generator->PrintLiteral(" {\n");
679       }
680     }
681   }
PrintMessageEnd(const Message & message,int field_index,int field_count,bool single_line_mode,TextFormat::BaseTextGenerator * generator) const682   void PrintMessageEnd(
683       const Message& message, int field_index, int field_count,
684       bool single_line_mode,
685       TextFormat::BaseTextGenerator* generator) const override {
686     if (field_index == field_count - 1 || field_index == -1) {
687       if (single_line_mode) {
688         generator->PrintLiteral("} ");
689       } else {
690         generator->PrintLiteral("}\n");
691       }
692     }
693   }
694 };
695 
TEST_F(TextFormatTest,CompactRepeatedFieldPrinter)696 TEST_F(TextFormatTest, CompactRepeatedFieldPrinter) {
697   TextFormat::Printer printer;
698   ASSERT_TRUE(printer.RegisterFieldValuePrinter(
699       unittest::TestAllTypes::default_instance()
700           .descriptor()
701           ->FindFieldByNumber(
702               unittest::TestAllTypes::kRepeatedNestedMessageFieldNumber),
703       new CompactRepeatedFieldPrinter));
704 
705   protobuf_unittest::TestAllTypes message;
706   message.add_repeated_nested_message()->set_bb(1);
707   message.add_repeated_nested_message()->set_bb(2);
708   message.add_repeated_nested_message()->set_bb(3);
709 
710   std::string text;
711   ASSERT_TRUE(printer.PrintToString(message, &text));
712   EXPECT_EQ(
713       "repeated_nested_message {\n"
714       "  bb: 1\n"
715       "  bb: 2\n"
716       "  bb: 3\n"
717       "}\n",
718       text);
719 }
720 
721 // Print strings into multiple line, with indention. Use this to test
722 // BaseTextGenerator::Indent and BaseTextGenerator::Outdent.
723 class MultilineStringPrinter : public TextFormat::FastFieldValuePrinter {
724  public:
PrintString(const std::string & val,TextFormat::BaseTextGenerator * generator) const725   void PrintString(const std::string& val,
726                    TextFormat::BaseTextGenerator* generator) const override {
727     generator->Indent();
728     int last_pos = 0;
729     int newline_pos = val.find('\n');
730     while (newline_pos != std::string::npos) {
731       generator->PrintLiteral("\n");
732       TextFormat::FastFieldValuePrinter::PrintString(
733           val.substr(last_pos, newline_pos + 1 - last_pos), generator);
734       last_pos = newline_pos + 1;
735       newline_pos = val.find('\n', last_pos);
736     }
737     if (last_pos < val.size()) {
738       generator->PrintLiteral("\n");
739       TextFormat::FastFieldValuePrinter::PrintString(val.substr(last_pos),
740                                                      generator);
741     }
742     generator->Outdent();
743   }
744 };
745 
TEST_F(TextFormatTest,MultilineStringPrinter)746 TEST_F(TextFormatTest, MultilineStringPrinter) {
747   TextFormat::Printer printer;
748   ASSERT_TRUE(printer.RegisterFieldValuePrinter(
749       unittest::TestAllTypes::default_instance()
750           .descriptor()
751           ->FindFieldByNumber(
752               unittest::TestAllTypes::kOptionalStringFieldNumber),
753       new MultilineStringPrinter));
754 
755   protobuf_unittest::TestAllTypes message;
756   message.set_optional_string("first line\nsecond line\nthird line");
757 
758   std::string text;
759   ASSERT_TRUE(printer.PrintToString(message, &text));
760   EXPECT_EQ(
761       "optional_string: \n"
762       "  \"first line\\n\"\n"
763       "  \"second line\\n\"\n"
764       "  \"third line\"\n",
765       text);
766 }
767 
768 class CustomNestedMessagePrinter : public TextFormat::MessagePrinter {
769  public:
CustomNestedMessagePrinter()770   CustomNestedMessagePrinter() {}
~CustomNestedMessagePrinter()771   ~CustomNestedMessagePrinter() override {}
Print(const Message & message,bool single_line_mode,TextFormat::BaseTextGenerator * generator) const772   void Print(const Message& message, bool single_line_mode,
773              TextFormat::BaseTextGenerator* generator) const override {
774     generator->PrintLiteral("custom");
775   }
776 };
777 
TEST_F(TextFormatTest,CustomMessagePrinter)778 TEST_F(TextFormatTest, CustomMessagePrinter) {
779   TextFormat::Printer printer;
780   printer.RegisterMessagePrinter(
781       unittest::TestAllTypes::NestedMessage::default_instance().descriptor(),
782       new CustomNestedMessagePrinter);
783 
784   unittest::TestAllTypes message;
785   std::string text;
786   EXPECT_TRUE(printer.PrintToString(message, &text));
787   EXPECT_EQ("", text);
788 
789   message.mutable_optional_nested_message()->set_bb(1);
790   EXPECT_TRUE(printer.PrintToString(message, &text));
791   EXPECT_EQ("optional_nested_message {\n  custom}\n", text);
792 }
793 
TEST_F(TextFormatTest,ParseBasic)794 TEST_F(TextFormatTest, ParseBasic) {
795   io::ArrayInputStream input_stream(proto_debug_string_.data(),
796                                     proto_debug_string_.size());
797   TextFormat::Parse(&input_stream, &proto_);
798   TestUtil::ExpectAllFieldsSet(proto_);
799 }
800 
TEST_F(TextFormatExtensionsTest,ParseExtensions)801 TEST_F(TextFormatExtensionsTest, ParseExtensions) {
802   io::ArrayInputStream input_stream(proto_debug_string_.data(),
803                                     proto_debug_string_.size());
804   TextFormat::Parse(&input_stream, &proto_);
805   TestUtil::ExpectAllExtensionsSet(proto_);
806 }
807 
TEST_F(TextFormatTest,ParseEnumFieldFromNumber)808 TEST_F(TextFormatTest, ParseEnumFieldFromNumber) {
809   // Create a parse string with a numerical value for an enum field.
810   std::string parse_string =
811       strings::Substitute("optional_nested_enum: $0", unittest::TestAllTypes::BAZ);
812   EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
813   EXPECT_TRUE(proto_.has_optional_nested_enum());
814   EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.optional_nested_enum());
815 }
816 
TEST_F(TextFormatTest,ParseEnumFieldFromNegativeNumber)817 TEST_F(TextFormatTest, ParseEnumFieldFromNegativeNumber) {
818   ASSERT_LT(unittest::SPARSE_E, 0);
819   std::string parse_string =
820       strings::Substitute("sparse_enum: $0", unittest::SPARSE_E);
821   unittest::SparseEnumMessage proto;
822   EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto));
823   EXPECT_TRUE(proto.has_sparse_enum());
824   EXPECT_EQ(unittest::SPARSE_E, proto.sparse_enum());
825 }
826 
TEST_F(TextFormatTest,PrintUnknownEnumFieldProto3)827 TEST_F(TextFormatTest, PrintUnknownEnumFieldProto3) {
828   proto3_unittest::TestAllTypes proto;
829 
830   proto.add_repeated_nested_enum(
831       static_cast<proto3_unittest::TestAllTypes::NestedEnum>(10));
832   proto.add_repeated_nested_enum(
833       static_cast<proto3_unittest::TestAllTypes::NestedEnum>(-10));
834   proto.add_repeated_nested_enum(
835       static_cast<proto3_unittest::TestAllTypes::NestedEnum>(2147483647));
836   proto.add_repeated_nested_enum(
837       static_cast<proto3_unittest::TestAllTypes::NestedEnum>(-2147483648));
838 
839   EXPECT_EQ(
840       "repeated_nested_enum: 10\n"
841       "repeated_nested_enum: -10\n"
842       "repeated_nested_enum: 2147483647\n"
843       "repeated_nested_enum: -2147483648\n",
844       proto.DebugString());
845 }
846 
TEST_F(TextFormatTest,ParseUnknownEnumFieldProto3)847 TEST_F(TextFormatTest, ParseUnknownEnumFieldProto3) {
848   proto3_unittest::TestAllTypes proto;
849   std::string parse_string =
850       "repeated_nested_enum: [10, -10, 2147483647, -2147483648]";
851   EXPECT_TRUE(TextFormat::ParseFromString(parse_string, &proto));
852   ASSERT_EQ(4, proto.repeated_nested_enum_size());
853   EXPECT_EQ(10, proto.repeated_nested_enum(0));
854   EXPECT_EQ(-10, proto.repeated_nested_enum(1));
855   EXPECT_EQ(2147483647, proto.repeated_nested_enum(2));
856   EXPECT_EQ(-2147483648, proto.repeated_nested_enum(3));
857 }
858 
TEST_F(TextFormatTest,ParseStringEscape)859 TEST_F(TextFormatTest, ParseStringEscape) {
860   // Create a parse string with escaped characters in it.
861   std::string parse_string =
862       "optional_string: " + kEscapeTestStringEscaped + "\n";
863 
864   io::ArrayInputStream input_stream(parse_string.data(), parse_string.size());
865   TextFormat::Parse(&input_stream, &proto_);
866 
867   // Compare.
868   EXPECT_EQ(kEscapeTestString, proto_.optional_string());
869 }
870 
TEST_F(TextFormatTest,ParseConcatenatedString)871 TEST_F(TextFormatTest, ParseConcatenatedString) {
872   // Create a parse string with multiple parts on one line.
873   std::string parse_string = "optional_string: \"foo\" \"bar\"\n";
874 
875   io::ArrayInputStream input_stream1(parse_string.data(), parse_string.size());
876   TextFormat::Parse(&input_stream1, &proto_);
877 
878   // Compare.
879   EXPECT_EQ("foobar", proto_.optional_string());
880 
881   // Create a parse string with multiple parts on separate lines.
882   parse_string =
883       "optional_string: \"foo\"\n"
884       "\"bar\"\n";
885 
886   io::ArrayInputStream input_stream2(parse_string.data(), parse_string.size());
887   TextFormat::Parse(&input_stream2, &proto_);
888 
889   // Compare.
890   EXPECT_EQ("foobar", proto_.optional_string());
891 }
892 
TEST_F(TextFormatTest,ParseFloatWithSuffix)893 TEST_F(TextFormatTest, ParseFloatWithSuffix) {
894   // Test that we can parse a floating-point value with 'f' appended to the
895   // end.  This is needed for backwards-compatibility with proto1.
896 
897   // Have it parse a float with the 'f' suffix.
898   std::string parse_string = "optional_float: 1.0f\n";
899 
900   io::ArrayInputStream input_stream(parse_string.data(), parse_string.size());
901 
902   TextFormat::Parse(&input_stream, &proto_);
903 
904   // Compare.
905   EXPECT_EQ(1.0, proto_.optional_float());
906 }
907 
TEST_F(TextFormatTest,ParseShortRepeatedForm)908 TEST_F(TextFormatTest, ParseShortRepeatedForm) {
909   std::string parse_string =
910       // Mixed short-form and long-form are simply concatenated.
911       "repeated_int32: 1\n"
912       "repeated_int32: [456, 789]\n"
913       "repeated_nested_enum: [  FOO ,BAR, # comment\n"
914       "                         3]\n"
915       // Note that while the printer won't print repeated strings in short-form,
916       // the parser will accept them.
917       "repeated_string: [ \"foo\", 'bar' ]\n"
918       // Repeated message
919       "repeated_nested_message: [ { bb: 1 }, { bb : 2 }]\n"
920       // Repeated group
921       "RepeatedGroup [{ a: 3 },{ a: 4 }]\n";
922 
923   ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
924 
925   ASSERT_EQ(3, proto_.repeated_int32_size());
926   EXPECT_EQ(1, proto_.repeated_int32(0));
927   EXPECT_EQ(456, proto_.repeated_int32(1));
928   EXPECT_EQ(789, proto_.repeated_int32(2));
929 
930   ASSERT_EQ(3, proto_.repeated_nested_enum_size());
931   EXPECT_EQ(unittest::TestAllTypes::FOO, proto_.repeated_nested_enum(0));
932   EXPECT_EQ(unittest::TestAllTypes::BAR, proto_.repeated_nested_enum(1));
933   EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.repeated_nested_enum(2));
934 
935   ASSERT_EQ(2, proto_.repeated_string_size());
936   EXPECT_EQ("foo", proto_.repeated_string(0));
937   EXPECT_EQ("bar", proto_.repeated_string(1));
938 
939   ASSERT_EQ(2, proto_.repeated_nested_message_size());
940   EXPECT_EQ(1, proto_.repeated_nested_message(0).bb());
941   EXPECT_EQ(2, proto_.repeated_nested_message(1).bb());
942 
943   ASSERT_EQ(2, proto_.repeatedgroup_size());
944   EXPECT_EQ(3, proto_.repeatedgroup(0).a());
945   EXPECT_EQ(4, proto_.repeatedgroup(1).a());
946 }
947 
TEST_F(TextFormatTest,ParseShortRepeatedWithTrailingComma)948 TEST_F(TextFormatTest, ParseShortRepeatedWithTrailingComma) {
949   std::string parse_string = "repeated_int32: [456,]\n";
950   ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
951   parse_string = "repeated_nested_enum: [  FOO , ]";
952   ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
953   parse_string = "repeated_string: [ \"foo\", ]";
954   ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
955   parse_string = "repeated_nested_message: [ { bb: 1 }, ]";
956   ASSERT_FALSE(TextFormat::ParseFromString(parse_string, &proto_));
957   parse_string = "RepeatedGroup [{ a: 3 },]\n";
958 }
959 
TEST_F(TextFormatTest,ParseShortRepeatedEmpty)960 TEST_F(TextFormatTest, ParseShortRepeatedEmpty) {
961   std::string parse_string =
962       "repeated_int32: []\n"
963       "repeated_nested_enum: []\n"
964       "repeated_string: []\n"
965       "repeated_nested_message: []\n"
966       "RepeatedGroup []\n";
967 
968   ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
969 
970   EXPECT_EQ(0, proto_.repeated_int32_size());
971   EXPECT_EQ(0, proto_.repeated_nested_enum_size());
972   EXPECT_EQ(0, proto_.repeated_string_size());
973   EXPECT_EQ(0, proto_.repeated_nested_message_size());
974   EXPECT_EQ(0, proto_.repeatedgroup_size());
975 }
976 
TEST_F(TextFormatTest,ParseShortRepeatedConcatenatedWithEmpty)977 TEST_F(TextFormatTest, ParseShortRepeatedConcatenatedWithEmpty) {
978   std::string parse_string =
979       // Starting with empty [] should have no impact.
980       "repeated_int32: []\n"
981       "repeated_nested_enum: []\n"
982       "repeated_string: []\n"
983       "repeated_nested_message: []\n"
984       "RepeatedGroup []\n"
985       // Mixed short-form and long-form are simply concatenated.
986       "repeated_int32: 1\n"
987       "repeated_int32: [456, 789]\n"
988       "repeated_nested_enum: [  FOO ,BAR, # comment\n"
989       "                         3]\n"
990       // Note that while the printer won't print repeated strings in short-form,
991       // the parser will accept them.
992       "repeated_string: [ \"foo\", 'bar' ]\n"
993       // Repeated message
994       "repeated_nested_message: [ { bb: 1 }, { bb : 2 }]\n"
995       // Repeated group
996       "RepeatedGroup [{ a: 3 },{ a: 4 }]\n"
997       // Adding empty [] should have no impact.
998       "repeated_int32: []\n"
999       "repeated_nested_enum: []\n"
1000       "repeated_string: []\n"
1001       "repeated_nested_message: []\n"
1002       "RepeatedGroup []\n";
1003 
1004   ASSERT_TRUE(TextFormat::ParseFromString(parse_string, &proto_));
1005 
1006   ASSERT_EQ(3, proto_.repeated_int32_size());
1007   EXPECT_EQ(1, proto_.repeated_int32(0));
1008   EXPECT_EQ(456, proto_.repeated_int32(1));
1009   EXPECT_EQ(789, proto_.repeated_int32(2));
1010 
1011   ASSERT_EQ(3, proto_.repeated_nested_enum_size());
1012   EXPECT_EQ(unittest::TestAllTypes::FOO, proto_.repeated_nested_enum(0));
1013   EXPECT_EQ(unittest::TestAllTypes::BAR, proto_.repeated_nested_enum(1));
1014   EXPECT_EQ(unittest::TestAllTypes::BAZ, proto_.repeated_nested_enum(2));
1015 
1016   ASSERT_EQ(2, proto_.repeated_string_size());
1017   EXPECT_EQ("foo", proto_.repeated_string(0));
1018   EXPECT_EQ("bar", proto_.repeated_string(1));
1019 
1020   ASSERT_EQ(2, proto_.repeated_nested_message_size());
1021   EXPECT_EQ(1, proto_.repeated_nested_message(0).bb());
1022   EXPECT_EQ(2, proto_.repeated_nested_message(1).bb());
1023 
1024   ASSERT_EQ(2, proto_.repeatedgroup_size());
1025   EXPECT_EQ(3, proto_.repeatedgroup(0).a());
1026   EXPECT_EQ(4, proto_.repeatedgroup(1).a());
1027 }
1028 
1029 
TEST_F(TextFormatTest,Comments)1030 TEST_F(TextFormatTest, Comments) {
1031   // Test that comments are ignored.
1032 
1033   std::string parse_string =
1034       "optional_int32: 1  # a comment\n"
1035       "optional_int64: 2  # another comment";
1036 
1037   io::ArrayInputStream input_stream(parse_string.data(), parse_string.size());
1038 
1039   TextFormat::Parse(&input_stream, &proto_);
1040 
1041   // Compare.
1042   EXPECT_EQ(1, proto_.optional_int32());
1043   EXPECT_EQ(2, proto_.optional_int64());
1044 }
1045 
TEST_F(TextFormatTest,OptionalColon)1046 TEST_F(TextFormatTest, OptionalColon) {
1047   // Test that we can place a ':' after the field name of a nested message,
1048   // even though we don't have to.
1049 
1050   std::string parse_string = "optional_nested_message: { bb: 1}\n";
1051 
1052   io::ArrayInputStream input_stream(parse_string.data(), parse_string.size());
1053 
1054   TextFormat::Parse(&input_stream, &proto_);
1055 
1056   // Compare.
1057   EXPECT_TRUE(proto_.has_optional_nested_message());
1058   EXPECT_EQ(1, proto_.optional_nested_message().bb());
1059 }
1060 
1061 // Some platforms (e.g. Windows) insist on padding the exponent to three
1062 // digits when one or two would be just fine.
RemoveRedundantZeros(std::string text)1063 static std::string RemoveRedundantZeros(std::string text) {
1064   text = StringReplace(text, "e+0", "e+", true);
1065   text = StringReplace(text, "e-0", "e-", true);
1066   return text;
1067 }
1068 
TEST_F(TextFormatTest,PrintExotic)1069 TEST_F(TextFormatTest, PrintExotic) {
1070   unittest::TestAllTypes message;
1071 
1072   // Note:  In C, a negative integer literal is actually the unary negation
1073   //   operator being applied to a positive integer literal, and
1074   //   9223372036854775808 is outside the range of int64.  However, it is not
1075   //   outside the range of uint64.  Confusingly, this means that everything
1076   //   works if we make the literal unsigned, even though we are negating it.
1077   message.add_repeated_int64(-PROTOBUF_ULONGLONG(9223372036854775808));
1078   message.add_repeated_uint64(PROTOBUF_ULONGLONG(18446744073709551615));
1079   message.add_repeated_double(123.456);
1080   message.add_repeated_double(1.23e21);
1081   message.add_repeated_double(1.23e-18);
1082   message.add_repeated_double(std::numeric_limits<double>::infinity());
1083   message.add_repeated_double(-std::numeric_limits<double>::infinity());
1084   message.add_repeated_double(std::numeric_limits<double>::quiet_NaN());
1085   message.add_repeated_double(-std::numeric_limits<double>::quiet_NaN());
1086   message.add_repeated_double(std::numeric_limits<double>::signaling_NaN());
1087   message.add_repeated_double(-std::numeric_limits<double>::signaling_NaN());
1088   message.add_repeated_string(std::string("\000\001\a\b\f\n\r\t\v\\\'\"", 12));
1089 
1090   // Fun story:  We used to use 1.23e22 instead of 1.23e21 above, but this
1091   //   seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of
1092   //   the value differed from strtod()'s parsing.  That is to say, the
1093   //   following assertion fails on MinGW:
1094   //     assert(1.23e22 == strtod("1.23e22", NULL));
1095   //   As a result, SimpleDtoa() would print the value as
1096   //   "1.2300000000000001e+22" to make sure strtod() produce the exact same
1097   //   result.  Our goal is to test runtime parsing, not compile-time parsing,
1098   //   so this wasn't our problem.  It was found that using 1.23e21 did not
1099   //   have this problem, so we switched to that instead.
1100 
1101   EXPECT_EQ(
1102       "repeated_int64: -9223372036854775808\n"
1103       "repeated_uint64: 18446744073709551615\n"
1104       "repeated_double: 123.456\n"
1105       "repeated_double: 1.23e+21\n"
1106       "repeated_double: 1.23e-18\n"
1107       "repeated_double: inf\n"
1108       "repeated_double: -inf\n"
1109       "repeated_double: nan\n"
1110       "repeated_double: nan\n"
1111       "repeated_double: nan\n"
1112       "repeated_double: nan\n"
1113       "repeated_string: "
1114       "\"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n",
1115       RemoveRedundantZeros(message.DebugString()));
1116 }
1117 
TEST_F(TextFormatTest,PrintFloatPrecision)1118 TEST_F(TextFormatTest, PrintFloatPrecision) {
1119   unittest::TestAllTypes message;
1120 
1121   message.add_repeated_float(1.0);
1122   message.add_repeated_float(1.2);
1123   message.add_repeated_float(1.23);
1124   message.add_repeated_float(1.234);
1125   message.add_repeated_float(1.2345);
1126   message.add_repeated_float(1.23456);
1127   message.add_repeated_float(1.2e10);
1128   message.add_repeated_float(1.23e10);
1129   message.add_repeated_float(1.234e10);
1130   message.add_repeated_float(1.2345e10);
1131   message.add_repeated_float(1.23456e10);
1132   message.add_repeated_double(1.2);
1133   message.add_repeated_double(1.23);
1134   message.add_repeated_double(1.234);
1135   message.add_repeated_double(1.2345);
1136   message.add_repeated_double(1.23456);
1137   message.add_repeated_double(1.234567);
1138   message.add_repeated_double(1.2345678);
1139   message.add_repeated_double(1.23456789);
1140   message.add_repeated_double(1.234567898);
1141   message.add_repeated_double(1.2345678987);
1142   message.add_repeated_double(1.23456789876);
1143   message.add_repeated_double(1.234567898765);
1144   message.add_repeated_double(1.2345678987654);
1145   message.add_repeated_double(1.23456789876543);
1146   message.add_repeated_double(1.2e100);
1147   message.add_repeated_double(1.23e100);
1148   message.add_repeated_double(1.234e100);
1149   message.add_repeated_double(1.2345e100);
1150   message.add_repeated_double(1.23456e100);
1151   message.add_repeated_double(1.234567e100);
1152   message.add_repeated_double(1.2345678e100);
1153   message.add_repeated_double(1.23456789e100);
1154   message.add_repeated_double(1.234567898e100);
1155   message.add_repeated_double(1.2345678987e100);
1156   message.add_repeated_double(1.23456789876e100);
1157   message.add_repeated_double(1.234567898765e100);
1158   message.add_repeated_double(1.2345678987654e100);
1159   message.add_repeated_double(1.23456789876543e100);
1160 
1161   EXPECT_EQ(
1162       "repeated_float: 1\n"
1163       "repeated_float: 1.2\n"
1164       "repeated_float: 1.23\n"
1165       "repeated_float: 1.234\n"
1166       "repeated_float: 1.2345\n"
1167       "repeated_float: 1.23456\n"
1168       "repeated_float: 1.2e+10\n"
1169       "repeated_float: 1.23e+10\n"
1170       "repeated_float: 1.234e+10\n"
1171       "repeated_float: 1.2345e+10\n"
1172       "repeated_float: 1.23456e+10\n"
1173       "repeated_double: 1.2\n"
1174       "repeated_double: 1.23\n"
1175       "repeated_double: 1.234\n"
1176       "repeated_double: 1.2345\n"
1177       "repeated_double: 1.23456\n"
1178       "repeated_double: 1.234567\n"
1179       "repeated_double: 1.2345678\n"
1180       "repeated_double: 1.23456789\n"
1181       "repeated_double: 1.234567898\n"
1182       "repeated_double: 1.2345678987\n"
1183       "repeated_double: 1.23456789876\n"
1184       "repeated_double: 1.234567898765\n"
1185       "repeated_double: 1.2345678987654\n"
1186       "repeated_double: 1.23456789876543\n"
1187       "repeated_double: 1.2e+100\n"
1188       "repeated_double: 1.23e+100\n"
1189       "repeated_double: 1.234e+100\n"
1190       "repeated_double: 1.2345e+100\n"
1191       "repeated_double: 1.23456e+100\n"
1192       "repeated_double: 1.234567e+100\n"
1193       "repeated_double: 1.2345678e+100\n"
1194       "repeated_double: 1.23456789e+100\n"
1195       "repeated_double: 1.234567898e+100\n"
1196       "repeated_double: 1.2345678987e+100\n"
1197       "repeated_double: 1.23456789876e+100\n"
1198       "repeated_double: 1.234567898765e+100\n"
1199       "repeated_double: 1.2345678987654e+100\n"
1200       "repeated_double: 1.23456789876543e+100\n",
1201       RemoveRedundantZeros(message.DebugString()));
1202 }
1203 
TEST_F(TextFormatTest,AllowPartial)1204 TEST_F(TextFormatTest, AllowPartial) {
1205   unittest::TestRequired message;
1206   TextFormat::Parser parser;
1207   parser.AllowPartialMessage(true);
1208   EXPECT_TRUE(parser.ParseFromString("a: 1", &message));
1209   EXPECT_EQ(1, message.a());
1210   EXPECT_FALSE(message.has_b());
1211   EXPECT_FALSE(message.has_c());
1212 }
1213 
TEST_F(TextFormatTest,ParseExotic)1214 TEST_F(TextFormatTest, ParseExotic) {
1215   unittest::TestAllTypes message;
1216   ASSERT_TRUE(TextFormat::ParseFromString(
1217       "repeated_int32: -1\n"
1218       "repeated_int32: -2147483648\n"
1219       "repeated_int64: -1\n"
1220       "repeated_int64: -9223372036854775808\n"
1221       "repeated_uint32: 4294967295\n"
1222       "repeated_uint32: 2147483648\n"
1223       "repeated_uint64: 18446744073709551615\n"
1224       "repeated_uint64: 9223372036854775808\n"
1225       "repeated_double: 123.0\n"
1226       "repeated_double: 123.5\n"
1227       "repeated_double: 0.125\n"
1228       "repeated_double: 1.23E17\n"
1229       "repeated_double: 1.235E+22\n"
1230       "repeated_double: 1.235e-18\n"
1231       "repeated_double: 123.456789\n"
1232       "repeated_double: inf\n"
1233       "repeated_double: Infinity\n"
1234       "repeated_double: -inf\n"
1235       "repeated_double: -Infinity\n"
1236       "repeated_double: nan\n"
1237       "repeated_double: NaN\n"
1238       "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n",
1239       &message));
1240 
1241   ASSERT_EQ(2, message.repeated_int32_size());
1242   EXPECT_EQ(-1, message.repeated_int32(0));
1243   // Note:  In C, a negative integer literal is actually the unary negation
1244   //   operator being applied to a positive integer literal, and 2147483648 is
1245   //   outside the range of int32.  However, it is not outside the range of
1246   //   uint32.  Confusingly, this means that everything works if we make the
1247   //   literal unsigned, even though we are negating it.
1248   EXPECT_EQ(-2147483648u, message.repeated_int32(1));
1249 
1250   ASSERT_EQ(2, message.repeated_int64_size());
1251   EXPECT_EQ(-1, message.repeated_int64(0));
1252   // Note:  In C, a negative integer literal is actually the unary negation
1253   //   operator being applied to a positive integer literal, and
1254   //   9223372036854775808 is outside the range of int64.  However, it is not
1255   //   outside the range of uint64.  Confusingly, this means that everything
1256   //   works if we make the literal unsigned, even though we are negating it.
1257   EXPECT_EQ(-PROTOBUF_ULONGLONG(9223372036854775808),
1258             message.repeated_int64(1));
1259 
1260   ASSERT_EQ(2, message.repeated_uint32_size());
1261   EXPECT_EQ(4294967295u, message.repeated_uint32(0));
1262   EXPECT_EQ(2147483648u, message.repeated_uint32(1));
1263 
1264   ASSERT_EQ(2, message.repeated_uint64_size());
1265   EXPECT_EQ(PROTOBUF_ULONGLONG(18446744073709551615),
1266             message.repeated_uint64(0));
1267   EXPECT_EQ(PROTOBUF_ULONGLONG(9223372036854775808),
1268             message.repeated_uint64(1));
1269 
1270   ASSERT_EQ(13, message.repeated_double_size());
1271   EXPECT_EQ(123.0, message.repeated_double(0));
1272   EXPECT_EQ(123.5, message.repeated_double(1));
1273   EXPECT_EQ(0.125, message.repeated_double(2));
1274   EXPECT_EQ(1.23E17, message.repeated_double(3));
1275   EXPECT_EQ(1.235E22, message.repeated_double(4));
1276   EXPECT_EQ(1.235E-18, message.repeated_double(5));
1277   EXPECT_EQ(123.456789, message.repeated_double(6));
1278   EXPECT_EQ(message.repeated_double(7),
1279             std::numeric_limits<double>::infinity());
1280   EXPECT_EQ(message.repeated_double(8),
1281             std::numeric_limits<double>::infinity());
1282   EXPECT_EQ(message.repeated_double(9),
1283             -std::numeric_limits<double>::infinity());
1284   EXPECT_EQ(message.repeated_double(10),
1285             -std::numeric_limits<double>::infinity());
1286   EXPECT_TRUE(std::isnan(message.repeated_double(11)));
1287   EXPECT_TRUE(std::isnan(message.repeated_double(12)));
1288 
1289   // Note:  Since these string literals have \0's in them, we must explicitly
1290   // pass their sizes to string's constructor.
1291   ASSERT_EQ(1, message.repeated_string_size());
1292   EXPECT_EQ(std::string("\000\001\a\b\f\n\r\t\v\\\'\"", 12),
1293             message.repeated_string(0));
1294 
1295   ASSERT_TRUE(
1296       TextFormat::ParseFromString("repeated_float: 3.4028235e+38\n"
1297                                   "repeated_float: -3.4028235e+38\n"
1298                                   "repeated_float: 3.402823567797337e+38\n"
1299                                   "repeated_float: -3.402823567797337e+38\n",
1300                                   &message));
1301   EXPECT_EQ(message.repeated_float(0), std::numeric_limits<float>::max());
1302   EXPECT_EQ(message.repeated_float(1), -std::numeric_limits<float>::max());
1303   EXPECT_EQ(message.repeated_float(2), std::numeric_limits<float>::infinity());
1304   EXPECT_EQ(message.repeated_float(3), -std::numeric_limits<float>::infinity());
1305 
1306 }
1307 
TEST_F(TextFormatTest,PrintFieldsInIndexOrder)1308 TEST_F(TextFormatTest, PrintFieldsInIndexOrder) {
1309   protobuf_unittest::TestFieldOrderings message;
1310   // Fields are listed in index order instead of field number.
1311   message.set_my_string("str");  // Field number 11
1312   message.set_my_int(12345);     // Field number 1
1313   message.set_my_float(0.999);   // Field number 101
1314   // Extensions are listed based on the order of extension number.
1315   // Extension number 12.
1316   message
1317       .MutableExtension(
1318           protobuf_unittest::TestExtensionOrderings2::test_ext_orderings2)
1319       ->set_my_string("ext_str2");
1320   // Extension number 13.
1321   message
1322       .MutableExtension(
1323           protobuf_unittest::TestExtensionOrderings1::test_ext_orderings1)
1324       ->set_my_string("ext_str1");
1325   // Extension number 14.
1326   message
1327       .MutableExtension(protobuf_unittest::TestExtensionOrderings2::
1328                             TestExtensionOrderings3::test_ext_orderings3)
1329       ->set_my_string("ext_str3");
1330   // Extension number 50.
1331   *message.MutableExtension(protobuf_unittest::my_extension_string) = "ext_str0";
1332 
1333   TextFormat::Printer printer;
1334   std::string text;
1335 
1336   // By default, print in field number order.
1337   // my_int: 12345
1338   // my_string: "str"
1339   // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {
1340   //   my_string: "ext_str2"
1341   // }
1342   // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {
1343   //   my_string: "ext_str1"
1344   // }
1345   // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3]
1346   // {
1347   //   my_string: "ext_str3"
1348   // }
1349   // [protobuf_unittest.my_extension_string]: "ext_str0"
1350   // my_float: 0.999
1351   printer.PrintToString(message, &text);
1352   EXPECT_EQ(
1353       "my_int: 12345\nmy_string: "
1354       "\"str\"\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] "
1355       "{\n  my_string: "
1356       "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_"
1357       "orderings1] {\n  my_string: "
1358       "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2."
1359       "TestExtensionOrderings3.test_ext_orderings3] {\n  my_string: "
1360       "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: "
1361       "\"ext_str0\"\nmy_float: 0.999\n",
1362       text);
1363 
1364   // Print in index order.
1365   // my_string: "str"
1366   // my_int: 12345
1367   // my_float: 0.999
1368   // [protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] {
1369   //   my_string: "ext_str2"
1370   // }
1371   // [protobuf_unittest.TestExtensionOrderings1.test_ext_orderings1] {
1372   //   my_string: "ext_str1"
1373   // }
1374   // [protobuf_unittest.TestExtensionOrderings2.TestExtensionOrderings3.test_ext_orderings3]
1375   // {
1376   //   my_string: "ext_str3"
1377   // }
1378   // [protobuf_unittest.my_extension_string]: "ext_str0"
1379   printer.SetPrintMessageFieldsInIndexOrder(true);
1380   printer.PrintToString(message, &text);
1381   EXPECT_EQ(
1382       "my_string: \"str\"\nmy_int: 12345\nmy_float: "
1383       "0.999\n[protobuf_unittest.TestExtensionOrderings2.test_ext_orderings2] "
1384       "{\n  my_string: "
1385       "\"ext_str2\"\n}\n[protobuf_unittest.TestExtensionOrderings1.test_ext_"
1386       "orderings1] {\n  my_string: "
1387       "\"ext_str1\"\n}\n[protobuf_unittest.TestExtensionOrderings2."
1388       "TestExtensionOrderings3.test_ext_orderings3] {\n  my_string: "
1389       "\"ext_str3\"\n}\n[protobuf_unittest.my_extension_string]: \"ext_str0\"\n",
1390       text);
1391 }
1392 
1393 class TextFormatParserTest : public testing::Test {
1394  protected:
ExpectFailure(const std::string & input,const std::string & message,int line,int col)1395   void ExpectFailure(const std::string& input, const std::string& message,
1396                      int line, int col) {
1397     std::unique_ptr<unittest::TestAllTypes> proto(new unittest::TestAllTypes);
1398     ExpectFailure(input, message, line, col, proto.get());
1399   }
1400 
ExpectFailure(const std::string & input,const std::string & message,int line,int col,Message * proto)1401   void ExpectFailure(const std::string& input, const std::string& message,
1402                      int line, int col, Message* proto) {
1403     ExpectMessage(input, message, line, col, proto, false);
1404   }
1405 
ExpectMessage(const std::string & input,const std::string & message,int line,int col,Message * proto,bool expected_result)1406   void ExpectMessage(const std::string& input, const std::string& message,
1407                      int line, int col, Message* proto, bool expected_result) {
1408     MockErrorCollector error_collector;
1409     parser_.RecordErrorsTo(&error_collector);
1410     EXPECT_EQ(expected_result, parser_.ParseFromString(input, proto))
1411         << input << " -> " << proto->DebugString();
1412     EXPECT_EQ(
1413         StrCat(line) + ":" + StrCat(col) + ": " + message + "\n",
1414         error_collector.text_);
1415     parser_.RecordErrorsTo(nullptr);
1416   }
1417 
ExpectSuccessAndTree(const std::string & input,Message * proto,TextFormat::ParseInfoTree * info_tree)1418   void ExpectSuccessAndTree(const std::string& input, Message* proto,
1419                             TextFormat::ParseInfoTree* info_tree) {
1420     MockErrorCollector error_collector;
1421     parser_.RecordErrorsTo(&error_collector);
1422     parser_.WriteLocationsTo(info_tree);
1423     EXPECT_TRUE(parser_.ParseFromString(input, proto));
1424     parser_.WriteLocationsTo(nullptr);
1425     parser_.RecordErrorsTo(nullptr);
1426   }
1427 
ExpectLocation(TextFormat::ParseInfoTree * tree,const Descriptor * d,const std::string & field_name,int index,int line,int column)1428   void ExpectLocation(TextFormat::ParseInfoTree* tree, const Descriptor* d,
1429                       const std::string& field_name, int index, int line,
1430                       int column) {
1431     TextFormat::ParseLocation location =
1432         tree->GetLocation(d->FindFieldByName(field_name), index);
1433     EXPECT_EQ(line, location.line);
1434     EXPECT_EQ(column, location.column);
1435   }
1436 
1437   // An error collector which simply concatenates all its errors into a big
1438   // block of text which can be checked.
1439   class MockErrorCollector : public io::ErrorCollector {
1440    public:
MockErrorCollector()1441     MockErrorCollector() {}
~MockErrorCollector()1442     ~MockErrorCollector() {}
1443 
1444     std::string text_;
1445 
1446     // implements ErrorCollector -------------------------------------
AddError(int line,int column,const std::string & message)1447     void AddError(int line, int column, const std::string& message) {
1448       strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line + 1, column + 1,
1449                                 message);
1450     }
1451 
AddWarning(int line,int column,const std::string & message)1452     void AddWarning(int line, int column, const std::string& message) {
1453       AddError(line, column, "WARNING:" + message);
1454     }
1455   };
1456 
1457   TextFormat::Parser parser_;
1458 };
1459 
TEST_F(TextFormatParserTest,ParseInfoTreeBuilding)1460 TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) {
1461   std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
1462   const Descriptor* d = message->GetDescriptor();
1463 
1464   std::string stringData =
1465       "optional_int32: 1\n"
1466       "optional_int64: 2\n"
1467       "  optional_double: 2.4\n"
1468       "repeated_int32: 5\n"
1469       "repeated_int32: 10\n"
1470       "optional_nested_message <\n"
1471       "  bb: 78\n"
1472       ">\n"
1473       "repeated_nested_message <\n"
1474       "  bb: 79\n"
1475       ">\n"
1476       "repeated_nested_message <\n"
1477       "  bb: 80\n"
1478       ">";
1479 
1480   TextFormat::ParseInfoTree tree;
1481   ExpectSuccessAndTree(stringData, message.get(), &tree);
1482 
1483   // Verify that the tree has the correct positions.
1484   ExpectLocation(&tree, d, "optional_int32", -1, 0, 0);
1485   ExpectLocation(&tree, d, "optional_int64", -1, 1, 0);
1486   ExpectLocation(&tree, d, "optional_double", -1, 2, 2);
1487 
1488   ExpectLocation(&tree, d, "repeated_int32", 0, 3, 0);
1489   ExpectLocation(&tree, d, "repeated_int32", 1, 4, 0);
1490 
1491   ExpectLocation(&tree, d, "optional_nested_message", -1, 5, 0);
1492   ExpectLocation(&tree, d, "repeated_nested_message", 0, 8, 0);
1493   ExpectLocation(&tree, d, "repeated_nested_message", 1, 11, 0);
1494 
1495   // Check for fields not set. For an invalid field, the location returned
1496   // should be -1, -1.
1497   ExpectLocation(&tree, d, "repeated_int64", 0, -1, -1);
1498   ExpectLocation(&tree, d, "repeated_int32", 6, -1, -1);
1499   ExpectLocation(&tree, d, "some_unknown_field", -1, -1, -1);
1500 
1501   // Verify inside the nested message.
1502   const FieldDescriptor* nested_field =
1503       d->FindFieldByName("optional_nested_message");
1504 
1505   TextFormat::ParseInfoTree* nested_tree =
1506       tree.GetTreeForNested(nested_field, -1);
1507   ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 6, 2);
1508 
1509   // Verify inside another nested message.
1510   nested_field = d->FindFieldByName("repeated_nested_message");
1511   nested_tree = tree.GetTreeForNested(nested_field, 0);
1512   ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 9, 2);
1513 
1514   nested_tree = tree.GetTreeForNested(nested_field, 1);
1515   ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 12, 2);
1516 
1517   // Verify a NULL tree for an unknown nested field.
1518   TextFormat::ParseInfoTree* unknown_nested_tree =
1519       tree.GetTreeForNested(nested_field, 2);
1520 
1521   EXPECT_EQ(NULL, unknown_nested_tree);
1522 }
1523 
TEST_F(TextFormatParserTest,ParseFieldValueFromString)1524 TEST_F(TextFormatParserTest, ParseFieldValueFromString) {
1525   std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
1526   const Descriptor* d = message->GetDescriptor();
1527 
1528 #define EXPECT_FIELD(name, value, valuestring)                             \
1529   EXPECT_TRUE(TextFormat::ParseFieldValueFromString(                       \
1530       valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1531   EXPECT_EQ(value, message->optional_##name());                            \
1532   EXPECT_TRUE(message->has_optional_##name());
1533 
1534 #define EXPECT_BOOL_FIELD(name, value, valuestring)                        \
1535   EXPECT_TRUE(TextFormat::ParseFieldValueFromString(                       \
1536       valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1537   EXPECT_TRUE(message->optional_##name() == value);                        \
1538   EXPECT_TRUE(message->has_optional_##name());
1539 
1540 #define EXPECT_FLOAT_FIELD(name, value, valuestring)                       \
1541   EXPECT_TRUE(TextFormat::ParseFieldValueFromString(                       \
1542       valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1543   EXPECT_FLOAT_EQ(value, message->optional_##name());                      \
1544   EXPECT_TRUE(message->has_optional_##name());
1545 
1546 #define EXPECT_DOUBLE_FIELD(name, value, valuestring)                      \
1547   EXPECT_TRUE(TextFormat::ParseFieldValueFromString(                       \
1548       valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1549   EXPECT_DOUBLE_EQ(value, message->optional_##name());                     \
1550   EXPECT_TRUE(message->has_optional_##name());
1551 
1552 #define EXPECT_INVALID(name, valuestring)             \
1553   EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \
1554       valuestring, d->FindFieldByName("optional_" #name), message.get()));
1555 
1556   // int32
1557   EXPECT_FIELD(int32, 1, "1");
1558   EXPECT_FIELD(int32, -1, "-1");
1559   EXPECT_FIELD(int32, 0x1234, "0x1234");
1560   EXPECT_INVALID(int32, "a");
1561   EXPECT_INVALID(int32, "999999999999999999999999999999999999");
1562   EXPECT_INVALID(int32, "1,2");
1563 
1564   // int64
1565   EXPECT_FIELD(int64, 1, "1");
1566   EXPECT_FIELD(int64, -1, "-1");
1567   EXPECT_FIELD(int64, 0x1234567812345678LL, "0x1234567812345678");
1568   EXPECT_INVALID(int64, "a");
1569   EXPECT_INVALID(int64, "999999999999999999999999999999999999");
1570   EXPECT_INVALID(int64, "1,2");
1571 
1572   // uint64
1573   EXPECT_FIELD(uint64, 1, "1");
1574   EXPECT_FIELD(uint64, 0xf234567812345678ULL, "0xf234567812345678");
1575   EXPECT_INVALID(uint64, "-1");
1576   EXPECT_INVALID(uint64, "a");
1577   EXPECT_INVALID(uint64, "999999999999999999999999999999999999");
1578   EXPECT_INVALID(uint64, "1,2");
1579 
1580   // fixed32
1581   EXPECT_FIELD(fixed32, 1, "1");
1582   EXPECT_FIELD(fixed32, 0x12345678, "0x12345678");
1583   EXPECT_INVALID(fixed32, "-1");
1584   EXPECT_INVALID(fixed32, "a");
1585   EXPECT_INVALID(fixed32, "999999999999999999999999999999999999");
1586   EXPECT_INVALID(fixed32, "1,2");
1587 
1588   // fixed64
1589   EXPECT_FIELD(fixed64, 1, "1");
1590   EXPECT_FIELD(fixed64, 0x1234567812345678ULL, "0x1234567812345678");
1591   EXPECT_INVALID(fixed64, "-1");
1592   EXPECT_INVALID(fixed64, "a");
1593   EXPECT_INVALID(fixed64, "999999999999999999999999999999999999");
1594   EXPECT_INVALID(fixed64, "1,2");
1595 
1596   // bool
1597   EXPECT_BOOL_FIELD(bool, true, "true");
1598   EXPECT_BOOL_FIELD(bool, false, "false");
1599   EXPECT_BOOL_FIELD(bool, true, "1");
1600   EXPECT_BOOL_FIELD(bool, true, "t");
1601   EXPECT_BOOL_FIELD(bool, false, "0");
1602   EXPECT_BOOL_FIELD(bool, false, "f");
1603   EXPECT_FIELD(bool, true, "True");
1604   EXPECT_FIELD(bool, false, "False");
1605   EXPECT_INVALID(bool, "tRue");
1606   EXPECT_INVALID(bool, "faLse");
1607   EXPECT_INVALID(bool, "2");
1608   EXPECT_INVALID(bool, "-0");
1609   EXPECT_INVALID(bool, "on");
1610   EXPECT_INVALID(bool, "a");
1611 
1612   // float
1613   EXPECT_FIELD(float, 1, "1");
1614   EXPECT_FLOAT_FIELD(float, 1.5, "1.5");
1615   EXPECT_FLOAT_FIELD(float, 1.5e3, "1.5e3");
1616   EXPECT_FLOAT_FIELD(float, -4.55, "-4.55");
1617   EXPECT_INVALID(float, "a");
1618   EXPECT_INVALID(float, "1,2");
1619 
1620   // double
1621   EXPECT_FIELD(double, 1, "1");
1622   EXPECT_FIELD(double, -1, "-1");
1623   EXPECT_DOUBLE_FIELD(double, 2.3, "2.3");
1624   EXPECT_DOUBLE_FIELD(double, 3e5, "3e5");
1625   EXPECT_INVALID(double, "a");
1626   EXPECT_INVALID(double, "1,2");
1627   // Rejects hex and oct numbers for a double field.
1628   EXPECT_INVALID(double, "0xf");
1629   EXPECT_INVALID(double, "012");
1630 
1631   // string
1632   EXPECT_FIELD(string, "hello", "\"hello\"");
1633   EXPECT_FIELD(string, "-1.87", "'-1.87'");
1634   EXPECT_INVALID(string, "hello");  // without quote for value
1635 
1636   // enum
1637   EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR");
1638   EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ,
1639                StrCat(unittest::TestAllTypes::BAZ));
1640   EXPECT_INVALID(nested_enum, "FOOBAR");
1641 
1642   // message
1643   EXPECT_TRUE(TextFormat::ParseFieldValueFromString(
1644       "<bb:12>", d->FindFieldByName("optional_nested_message"), message.get()));
1645   EXPECT_EQ(12, message->optional_nested_message().bb());
1646   EXPECT_TRUE(message->has_optional_nested_message());
1647   EXPECT_INVALID(nested_message, "any");
1648 
1649 #undef EXPECT_FIELD
1650 #undef EXPECT_BOOL_FIELD
1651 #undef EXPECT_FLOAT_FIELD
1652 #undef EXPECT_DOUBLE_FIELD
1653 #undef EXPECT_INVALID
1654 }
1655 
TEST_F(TextFormatParserTest,InvalidToken)1656 TEST_F(TextFormatParserTest, InvalidToken) {
1657   ExpectFailure("optional_bool: true\n-5\n", "Expected identifier, got: -", 2,
1658                 1);
1659 
1660   ExpectFailure("optional_bool: true!\n", "Expected identifier, got: !", 1, 20);
1661   ExpectFailure("\"some string\"", "Expected identifier, got: \"some string\"",
1662                 1, 1);
1663 }
1664 
TEST_F(TextFormatParserTest,InvalidFieldName)1665 TEST_F(TextFormatParserTest, InvalidFieldName) {
1666   ExpectFailure(
1667       "invalid_field: somevalue\n",
1668       "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1669       "\"invalid_field\".",
1670       1, 14);
1671 }
1672 
TEST_F(TextFormatParserTest,InvalidCapitalization)1673 TEST_F(TextFormatParserTest, InvalidCapitalization) {
1674   // We require that group names be exactly as they appear in the .proto.
1675   ExpectFailure(
1676       "optionalgroup {\na: 15\n}\n",
1677       "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1678       "\"optionalgroup\".",
1679       1, 15);
1680   ExpectFailure(
1681       "OPTIONALgroup {\na: 15\n}\n",
1682       "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1683       "\"OPTIONALgroup\".",
1684       1, 15);
1685   ExpectFailure(
1686       "Optional_Double: 10.0\n",
1687       "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1688       "\"Optional_Double\".",
1689       1, 16);
1690 }
1691 
TEST_F(TextFormatParserTest,AllowIgnoreCapitalizationError)1692 TEST_F(TextFormatParserTest, AllowIgnoreCapitalizationError) {
1693   TextFormat::Parser parser;
1694   protobuf_unittest::TestAllTypes proto;
1695 
1696   // These fields have a mismatching case.
1697   EXPECT_FALSE(parser.ParseFromString("Optional_Double: 10.0", &proto));
1698   EXPECT_FALSE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto));
1699 
1700   // ... but are parsed correctly if we match case insensitive.
1701   parser.AllowCaseInsensitiveField(true);
1702   EXPECT_TRUE(parser.ParseFromString("Optional_Double: 10.0", &proto));
1703   EXPECT_EQ(10.0, proto.optional_double());
1704   EXPECT_TRUE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto));
1705   EXPECT_EQ(15, proto.optionalgroup().a());
1706 }
1707 
TEST_F(TextFormatParserTest,InvalidFieldValues)1708 TEST_F(TextFormatParserTest, InvalidFieldValues) {
1709   // Invalid values for a double/float field.
1710   ExpectFailure("optional_double: \"hello\"\n",
1711                 "Expected double, got: \"hello\"", 1, 18);
1712   ExpectFailure("optional_double: true\n", "Expected double, got: true", 1, 18);
1713   ExpectFailure("optional_double: !\n", "Expected double, got: !", 1, 18);
1714   ExpectFailure("optional_double {\n  \n}\n", "Expected \":\", found \"{\".", 1,
1715                 17);
1716 
1717   // Invalid values for a signed integer field.
1718   ExpectFailure("optional_int32: \"hello\"\n",
1719                 "Expected integer, got: \"hello\"", 1, 17);
1720   ExpectFailure("optional_int32: true\n", "Expected integer, got: true", 1, 17);
1721   ExpectFailure("optional_int32: 4.5\n", "Expected integer, got: 4.5", 1, 17);
1722   ExpectFailure("optional_int32: !\n", "Expected integer, got: !", 1, 17);
1723   ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", 1,
1724                 16);
1725   ExpectFailure("optional_int32: 0x80000000\n",
1726                 "Integer out of range (0x80000000)", 1, 17);
1727   ExpectFailure("optional_int64: 0x8000000000000000\n",
1728                 "Integer out of range (0x8000000000000000)", 1, 17);
1729   ExpectFailure("optional_int32: -0x80000001\n",
1730                 "Integer out of range (0x80000001)", 1, 18);
1731   ExpectFailure("optional_int64: -0x8000000000000001\n",
1732                 "Integer out of range (0x8000000000000001)", 1, 18);
1733 
1734   // Invalid values for an unsigned integer field.
1735   ExpectFailure("optional_uint64: \"hello\"\n",
1736                 "Expected integer, got: \"hello\"", 1, 18);
1737   ExpectFailure("optional_uint64: true\n", "Expected integer, got: true", 1,
1738                 18);
1739   ExpectFailure("optional_uint64: 4.5\n", "Expected integer, got: 4.5", 1, 18);
1740   ExpectFailure("optional_uint64: -5\n", "Expected integer, got: -", 1, 18);
1741   ExpectFailure("optional_uint64: !\n", "Expected integer, got: !", 1, 18);
1742   ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", 1,
1743                 17);
1744   ExpectFailure("optional_uint32: 0x100000000\n",
1745                 "Integer out of range (0x100000000)", 1, 18);
1746   ExpectFailure("optional_uint64: 0x10000000000000000\n",
1747                 "Integer out of range (0x10000000000000000)", 1, 18);
1748 
1749   // Invalid values for a boolean field.
1750   ExpectFailure("optional_bool: \"hello\"\n",
1751                 "Expected identifier, got: \"hello\"", 1, 16);
1752   ExpectFailure("optional_bool: 5\n", "Integer out of range (5)", 1, 16);
1753   ExpectFailure("optional_bool: -7.5\n", "Expected identifier, got: -", 1, 16);
1754   ExpectFailure("optional_bool: !\n", "Expected identifier, got: !", 1, 16);
1755 
1756   ExpectFailure(
1757       "optional_bool: meh\n",
1758       "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", 2,
1759       1);
1760 
1761   ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", 1,
1762                 15);
1763 
1764   // Invalid values for a string field.
1765   ExpectFailure("optional_string: true\n", "Expected string, got: true", 1, 18);
1766   ExpectFailure("optional_string: 5\n", "Expected string, got: 5", 1, 18);
1767   ExpectFailure("optional_string: -7.5\n", "Expected string, got: -", 1, 18);
1768   ExpectFailure("optional_string: !\n", "Expected string, got: !", 1, 18);
1769   ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", 1,
1770                 17);
1771 
1772   // Invalid values for an enumeration field.
1773   ExpectFailure("optional_nested_enum: \"hello\"\n",
1774                 "Expected integer or identifier, got: \"hello\"", 1, 23);
1775 
1776   // Valid token, but enum value is not defined.
1777   ExpectFailure("optional_nested_enum: 5\n",
1778                 "Unknown enumeration value of \"5\" for field "
1779                 "\"optional_nested_enum\".",
1780                 2, 1);
1781   // We consume the negative sign, so the error position starts one character
1782   // later.
1783   ExpectFailure("optional_nested_enum: -7.5\n", "Expected integer, got: 7.5", 1,
1784                 24);
1785   ExpectFailure("optional_nested_enum: !\n",
1786                 "Expected integer or identifier, got: !", 1, 23);
1787 
1788   ExpectFailure("optional_nested_enum: grah\n",
1789                 "Unknown enumeration value of \"grah\" for field "
1790                 "\"optional_nested_enum\".",
1791                 2, 1);
1792 
1793   ExpectFailure("optional_nested_enum {\n \n}\n",
1794                 "Expected \":\", found \"{\".", 1, 22);
1795 }
1796 
TEST_F(TextFormatParserTest,MessageDelimiters)1797 TEST_F(TextFormatParserTest, MessageDelimiters) {
1798   // Non-matching delimiters.
1799   ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", 3,
1800                 1);
1801 
1802   // Invalid delimiters.
1803   ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", 1,
1804                 15);
1805 
1806   // Unending message.
1807   ExpectFailure("optional_nested_message {\n \nbb: 118\n",
1808                 "Expected identifier, got: ", 4, 1);
1809 }
1810 
TEST_F(TextFormatParserTest,UnknownExtension)1811 TEST_F(TextFormatParserTest, UnknownExtension) {
1812   // Non-matching delimiters.
1813   ExpectFailure("[blahblah]: 123",
1814                 "Extension \"blahblah\" is not defined or is not an "
1815                 "extension of \"protobuf_unittest.TestAllTypes\".",
1816                 1, 11);
1817 }
1818 
TEST_F(TextFormatParserTest,MissingRequired)1819 TEST_F(TextFormatParserTest, MissingRequired) {
1820   unittest::TestRequired message;
1821   ExpectFailure("a: 1", "Message missing required fields: b, c", 0, 1,
1822                 &message);
1823 }
1824 
TEST_F(TextFormatParserTest,ParseDuplicateRequired)1825 TEST_F(TextFormatParserTest, ParseDuplicateRequired) {
1826   unittest::TestRequired message;
1827   ExpectFailure("a: 1 b: 2 c: 3 a: 1",
1828                 "Non-repeated field \"a\" is specified multiple times.", 1, 17,
1829                 &message);
1830 }
1831 
TEST_F(TextFormatParserTest,ParseDuplicateOptional)1832 TEST_F(TextFormatParserTest, ParseDuplicateOptional) {
1833   unittest::ForeignMessage message;
1834   ExpectFailure("c: 1 c: 2",
1835                 "Non-repeated field \"c\" is specified multiple times.", 1, 7,
1836                 &message);
1837 }
1838 
TEST_F(TextFormatParserTest,MergeDuplicateRequired)1839 TEST_F(TextFormatParserTest, MergeDuplicateRequired) {
1840   unittest::TestRequired message;
1841   TextFormat::Parser parser;
1842   EXPECT_TRUE(parser.MergeFromString("a: 1 b: 2 c: 3 a: 4", &message));
1843   EXPECT_EQ(4, message.a());
1844 }
1845 
TEST_F(TextFormatParserTest,MergeDuplicateOptional)1846 TEST_F(TextFormatParserTest, MergeDuplicateOptional) {
1847   unittest::ForeignMessage message;
1848   TextFormat::Parser parser;
1849   EXPECT_TRUE(parser.MergeFromString("c: 1 c: 2", &message));
1850   EXPECT_EQ(2, message.c());
1851 }
1852 
TEST_F(TextFormatParserTest,ExplicitDelimiters)1853 TEST_F(TextFormatParserTest, ExplicitDelimiters) {
1854   unittest::TestRequired message;
1855   EXPECT_TRUE(TextFormat::ParseFromString("a:1,b:2;c:3", &message));
1856   EXPECT_EQ(1, message.a());
1857   EXPECT_EQ(2, message.b());
1858   EXPECT_EQ(3, message.c());
1859 }
1860 
TEST_F(TextFormatParserTest,PrintErrorsToStderr)1861 TEST_F(TextFormatParserTest, PrintErrorsToStderr) {
1862   std::vector<std::string> errors;
1863 
1864   {
1865     ScopedMemoryLog log;
1866     unittest::TestAllTypes proto;
1867     EXPECT_FALSE(TextFormat::ParseFromString("no_such_field: 1", &proto));
1868     errors = log.GetMessages(ERROR);
1869   }
1870 
1871   ASSERT_EQ(1, errors.size());
1872   EXPECT_EQ(
1873       "Error parsing text-format protobuf_unittest.TestAllTypes: "
1874       "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field "
1875       "named \"no_such_field\".",
1876       errors[0]);
1877 }
1878 
TEST_F(TextFormatParserTest,FailsOnTokenizationError)1879 TEST_F(TextFormatParserTest, FailsOnTokenizationError) {
1880   std::vector<std::string> errors;
1881 
1882   {
1883     ScopedMemoryLog log;
1884     unittest::TestAllTypes proto;
1885     EXPECT_FALSE(TextFormat::ParseFromString("\020", &proto));
1886     errors = log.GetMessages(ERROR);
1887   }
1888 
1889   ASSERT_EQ(1, errors.size());
1890   EXPECT_EQ(
1891       "Error parsing text-format protobuf_unittest.TestAllTypes: "
1892       "1:1: Invalid control characters encountered in text.",
1893       errors[0]);
1894 }
1895 
TEST_F(TextFormatParserTest,ParseDeprecatedField)1896 TEST_F(TextFormatParserTest, ParseDeprecatedField) {
1897   unittest::TestDeprecatedFields message;
1898   ExpectMessage("deprecated_int32: 42",
1899                 "WARNING:text format contains deprecated field "
1900                 "\"deprecated_int32\"",
1901                 1, 21, &message, true);
1902 }
1903 
TEST_F(TextFormatParserTest,SetRecursionLimit)1904 TEST_F(TextFormatParserTest, SetRecursionLimit) {
1905   const char* format = "child: { $0 }";
1906   std::string input;
1907   for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input);
1908 
1909   unittest::NestedTestAllTypes message;
1910   ExpectSuccessAndTree(input, &message, nullptr);
1911 
1912   input = strings::Substitute(format, input);
1913   parser_.SetRecursionLimit(100);
1914   ExpectMessage(input,
1915                 "Message is too deep, the parser exceeded the configured "
1916                 "recursion limit of 100.",
1917                 1, 908, &message, false);
1918 
1919   parser_.SetRecursionLimit(101);
1920   ExpectSuccessAndTree(input, &message, nullptr);
1921 }
1922 
TEST_F(TextFormatParserTest,SetRecursionLimitUnknownField)1923 TEST_F(TextFormatParserTest, SetRecursionLimitUnknownField) {
1924   const char* format = "unknown_child: { $0 }";
1925   std::string input;
1926   for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input);
1927 
1928   parser_.AllowUnknownField(true);
1929 
1930   unittest::NestedTestAllTypes message;
1931   ExpectSuccessAndTree(input, &message, nullptr);
1932 
1933   input = strings::Substitute(format, input);
1934   parser_.SetRecursionLimit(100);
1935   ExpectMessage(
1936       input,
1937       "WARNING:Message type \"protobuf_unittest.NestedTestAllTypes\" has no "
1938       "field named \"unknown_child\".\n1:1716: Message is too deep, the parser "
1939       "exceeded the configured recursion limit of 100.",
1940       1, 14, &message, false);
1941 
1942   parser_.SetRecursionLimit(101);
1943   ExpectSuccessAndTree(input, &message, nullptr);
1944 }
1945 
1946 class TextFormatMessageSetTest : public testing::Test {
1947  protected:
1948   static const char proto_debug_string_[];
1949 };
1950 const char TextFormatMessageSetTest::proto_debug_string_[] =
1951     "message_set {\n"
1952     "  [protobuf_unittest.TestMessageSetExtension1] {\n"
1953     "    i: 23\n"
1954     "  }\n"
1955     "  [protobuf_unittest.TestMessageSetExtension2] {\n"
1956     "    str: \"foo\"\n"
1957     "  }\n"
1958     "}\n";
1959 
TEST_F(TextFormatMessageSetTest,Serialize)1960 TEST_F(TextFormatMessageSetTest, Serialize) {
1961   protobuf_unittest::TestMessageSetContainer proto;
1962   protobuf_unittest::TestMessageSetExtension1* item_a =
1963       proto.mutable_message_set()->MutableExtension(
1964           protobuf_unittest::TestMessageSetExtension1::message_set_extension);
1965   item_a->set_i(23);
1966   protobuf_unittest::TestMessageSetExtension2* item_b =
1967       proto.mutable_message_set()->MutableExtension(
1968           protobuf_unittest::TestMessageSetExtension2::message_set_extension);
1969   item_b->set_str("foo");
1970   EXPECT_EQ(proto_debug_string_, proto.DebugString());
1971 }
1972 
TEST_F(TextFormatMessageSetTest,Deserialize)1973 TEST_F(TextFormatMessageSetTest, Deserialize) {
1974   protobuf_unittest::TestMessageSetContainer proto;
1975   ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto));
1976   EXPECT_EQ(
1977       23,
1978       proto.message_set()
1979           .GetExtension(
1980               protobuf_unittest::TestMessageSetExtension1::message_set_extension)
1981           .i());
1982   EXPECT_EQ(
1983       "foo",
1984       proto.message_set()
1985           .GetExtension(
1986               protobuf_unittest::TestMessageSetExtension2::message_set_extension)
1987           .str());
1988 
1989   // Ensure that these are the only entries present.
1990   std::vector<const FieldDescriptor*> descriptors;
1991   proto.message_set().GetReflection()->ListFields(proto.message_set(),
1992                                                   &descriptors);
1993   EXPECT_EQ(2, descriptors.size());
1994 }
1995 
TEST(TextFormatUnknownFieldTest,TestUnknownField)1996 TEST(TextFormatUnknownFieldTest, TestUnknownField) {
1997   protobuf_unittest::TestAllTypes proto;
1998   TextFormat::Parser parser;
1999   // Unknown field is not permitted by default.
2000   EXPECT_FALSE(parser.ParseFromString("unknown_field: 12345", &proto));
2001   EXPECT_FALSE(parser.ParseFromString("12345678: 12345", &proto));
2002 
2003   parser.AllowUnknownField(true);
2004   EXPECT_TRUE(parser.ParseFromString("unknown_field: 12345", &proto));
2005   EXPECT_TRUE(parser.ParseFromString("unknown_field: -12345", &proto));
2006   EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345", &proto));
2007   EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345", &proto));
2008   EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345f", &proto));
2009   EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345f", &proto));
2010   EXPECT_TRUE(parser.ParseFromString("unknown_field: inf", &proto));
2011   EXPECT_TRUE(parser.ParseFromString("unknown_field: -inf", &proto));
2012   EXPECT_TRUE(parser.ParseFromString("unknown_field: TYPE_STRING", &proto));
2013   EXPECT_TRUE(
2014       parser.ParseFromString("unknown_field: \"string value\"", &proto));
2015   // Invalid field value
2016   EXPECT_FALSE(parser.ParseFromString("unknown_field: -TYPE_STRING", &proto));
2017   // Two or more unknown fields
2018   EXPECT_TRUE(
2019       parser.ParseFromString("unknown_field1: TYPE_STRING\n"
2020                              "unknown_field2: 12345",
2021                              &proto));
2022   // Unknown nested message
2023   EXPECT_TRUE(
2024       parser.ParseFromString("unknown_message1: {}\n"
2025                              "unknown_message2 {\n"
2026                              "  unknown_field: 12345\n"
2027                              "}\n"
2028                              "unknown_message3 <\n"
2029                              "  unknown_nested_message {\n"
2030                              "    unknown_field: 12345\n"
2031                              "  }\n"
2032                              ">",
2033                              &proto));
2034   // Unmatched delimeters for message body
2035   EXPECT_FALSE(parser.ParseFromString("unknown_message: {>", &proto));
2036   // Unknown extension
2037   EXPECT_TRUE(
2038       parser.ParseFromString("[somewhere.unknown_extension1]: 12345\n"
2039                              "[somewhere.unknown_extension2] {\n"
2040                              "  unknown_field: 12345\n"
2041                              "}",
2042                              &proto));
2043   // Unknown fields between known fields
2044   ASSERT_TRUE(
2045       parser.ParseFromString("optional_int32: 1\n"
2046                              "unknown_field: 12345\n"
2047                              "optional_string: \"string\"\n"
2048                              "unknown_message { unknown: 0 }\n"
2049                              "optional_nested_message { bb: 2 }",
2050                              &proto));
2051   EXPECT_EQ(1, proto.optional_int32());
2052   EXPECT_EQ("string", proto.optional_string());
2053   EXPECT_EQ(2, proto.optional_nested_message().bb());
2054 
2055   // Unknown field with numeric tag number instead of identifier.
2056   EXPECT_TRUE(parser.ParseFromString("12345678: 12345", &proto));
2057 
2058   // Nested unknown extensions.
2059   EXPECT_TRUE(
2060       parser.ParseFromString("[test.extension1] <\n"
2061                              "  unknown_nested_message <\n"
2062                              "    [test.extension2] <\n"
2063                              "      unknown_field: 12345\n"
2064                              "    >\n"
2065                              "  >\n"
2066                              ">",
2067                              &proto));
2068   EXPECT_TRUE(
2069       parser.ParseFromString("[test.extension1] {\n"
2070                              "  unknown_nested_message {\n"
2071                              "    [test.extension2] {\n"
2072                              "      unknown_field: 12345\n"
2073                              "    }\n"
2074                              "  }\n"
2075                              "}",
2076                              &proto));
2077   EXPECT_TRUE(
2078       parser.ParseFromString("[test.extension1] <\n"
2079                              "  some_unknown_fields: <\n"
2080                              "    unknown_field: 12345\n"
2081                              "  >\n"
2082                              ">",
2083                              &proto));
2084   EXPECT_TRUE(
2085       parser.ParseFromString("[test.extension1] {\n"
2086                              "  some_unknown_fields: {\n"
2087                              "    unknown_field: 12345\n"
2088                              "  }\n"
2089                              "}",
2090                              &proto));
2091 
2092   // Unknown field with compact repetition.
2093   EXPECT_TRUE(parser.ParseFromString("unknown_field: [1, 2]", &proto));
2094   // Unknown field with compact repetition of some unknown enum.
2095   EXPECT_TRUE(parser.ParseFromString("unknown_field: [VAL1, VAL2]", &proto));
2096   // Unknown field with compact repetition with sub-message.
2097   EXPECT_TRUE(parser.ParseFromString("unknown_field: [{a:1}, <b:2>]", &proto));
2098 }
2099 
TEST(TextFormatUnknownFieldTest,TestAnyInUnknownField)2100 TEST(TextFormatUnknownFieldTest, TestAnyInUnknownField) {
2101   protobuf_unittest::TestAllTypes proto;
2102   TextFormat::Parser parser;
2103   parser.AllowUnknownField(true);
2104   EXPECT_TRUE(
2105       parser.ParseFromString("unknown {\n"
2106                              "  [type.googleapis.com/foo.bar] {\n"
2107                              "  }\n"
2108                              "}",
2109                              &proto));
2110 }
2111 
TEST(TextFormatUnknownFieldTest,TestUnknownExtension)2112 TEST(TextFormatUnknownFieldTest, TestUnknownExtension) {
2113   protobuf_unittest::TestAllTypes proto;
2114   TextFormat::Parser parser;
2115   std::string message_with_ext =
2116       "[test.extension1] {\n"
2117       "  some_unknown_fields: {\n"
2118       "    unknown_field: 12345\n"
2119       "  }\n"
2120       "}";
2121   // Unknown extensions are not permitted by default.
2122   EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto));
2123   // AllowUnknownField implies AllowUnknownExtension.
2124   parser.AllowUnknownField(true);
2125   EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto));
2126 
2127   parser.AllowUnknownField(false);
2128   EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto));
2129   parser.AllowUnknownExtension(true);
2130   EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto));
2131   // Unknown fields are still not accepted.
2132   EXPECT_FALSE(parser.ParseFromString("unknown_field: 1", &proto));
2133 }
2134 
2135 
2136 }  // namespace text_format_unittest
2137 }  // namespace protobuf
2138 }  // namespace google
2139