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/testing/file.h>
46 #include <google/protobuf/testing/file.h>
47 #include <google/protobuf/map_unittest.pb.h>
48 #include <google/protobuf/test_util.h>
49 #include <google/protobuf/test_util2.h>
50 #include <google/protobuf/unittest.pb.h>
51 #include <google/protobuf/unittest_mset.pb.h>
52 #include <google/protobuf/unittest_mset_wire_format.pb.h>
53 #include <google/protobuf/unittest_proto3.pb.h>
54 #include <google/protobuf/io/tokenizer.h>
55 #include <google/protobuf/io/zero_copy_stream_impl.h>
56 #include <google/protobuf/stubs/strutil.h>
57 #include <gmock/gmock.h>
58 #include <google/protobuf/testing/googletest.h>
59 #include <gtest/gtest.h>
60 #include <google/protobuf/stubs/logging.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 indentation. 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(StrCat(line, ":", col, ": ", message, "\n"),
1413 error_collector.text_);
1414 parser_.RecordErrorsTo(nullptr);
1415 }
1416
ExpectSuccessAndTree(const std::string & input,Message * proto,TextFormat::ParseInfoTree * info_tree)1417 void ExpectSuccessAndTree(const std::string& input, Message* proto,
1418 TextFormat::ParseInfoTree* info_tree) {
1419 MockErrorCollector error_collector;
1420 parser_.RecordErrorsTo(&error_collector);
1421 parser_.WriteLocationsTo(info_tree);
1422 EXPECT_TRUE(parser_.ParseFromString(input, proto));
1423 parser_.WriteLocationsTo(nullptr);
1424 parser_.RecordErrorsTo(nullptr);
1425 }
1426
ExpectLocation(TextFormat::ParseInfoTree * tree,const Descriptor * d,const std::string & field_name,int index,int line,int column)1427 void ExpectLocation(TextFormat::ParseInfoTree* tree, const Descriptor* d,
1428 const std::string& field_name, int index, int line,
1429 int column) {
1430 TextFormat::ParseLocation location =
1431 tree->GetLocation(d->FindFieldByName(field_name), index);
1432 EXPECT_EQ(line, location.line);
1433 EXPECT_EQ(column, location.column);
1434 }
1435
1436 // An error collector which simply concatenates all its errors into a big
1437 // block of text which can be checked.
1438 class MockErrorCollector : public io::ErrorCollector {
1439 public:
MockErrorCollector()1440 MockErrorCollector() {}
~MockErrorCollector()1441 ~MockErrorCollector() {}
1442
1443 std::string text_;
1444
1445 // implements ErrorCollector -------------------------------------
AddError(int line,int column,const std::string & message)1446 void AddError(int line, int column, const std::string& message) {
1447 strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", line + 1, column + 1,
1448 message);
1449 }
1450
AddWarning(int line,int column,const std::string & message)1451 void AddWarning(int line, int column, const std::string& message) {
1452 AddError(line, column, "WARNING:" + message);
1453 }
1454 };
1455
1456 TextFormat::Parser parser_;
1457 };
1458
TEST_F(TextFormatParserTest,ParseInfoTreeBuilding)1459 TEST_F(TextFormatParserTest, ParseInfoTreeBuilding) {
1460 std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
1461 const Descriptor* d = message->GetDescriptor();
1462
1463 std::string stringData =
1464 "optional_int32: 1\n"
1465 "optional_int64: 2\n"
1466 " optional_double: 2.4\n"
1467 "repeated_int32: 5\n"
1468 "repeated_int32: 10\n"
1469 "optional_nested_message <\n"
1470 " bb: 78\n"
1471 ">\n"
1472 "repeated_nested_message <\n"
1473 " bb: 79\n"
1474 ">\n"
1475 "repeated_nested_message <\n"
1476 " bb: 80\n"
1477 ">";
1478
1479 TextFormat::ParseInfoTree tree;
1480 ExpectSuccessAndTree(stringData, message.get(), &tree);
1481
1482 // Verify that the tree has the correct positions.
1483 ExpectLocation(&tree, d, "optional_int32", -1, 0, 0);
1484 ExpectLocation(&tree, d, "optional_int64", -1, 1, 0);
1485 ExpectLocation(&tree, d, "optional_double", -1, 2, 2);
1486
1487 ExpectLocation(&tree, d, "repeated_int32", 0, 3, 0);
1488 ExpectLocation(&tree, d, "repeated_int32", 1, 4, 0);
1489
1490 ExpectLocation(&tree, d, "optional_nested_message", -1, 5, 0);
1491 ExpectLocation(&tree, d, "repeated_nested_message", 0, 8, 0);
1492 ExpectLocation(&tree, d, "repeated_nested_message", 1, 11, 0);
1493
1494 // Check for fields not set. For an invalid field, the location returned
1495 // should be -1, -1.
1496 ExpectLocation(&tree, d, "repeated_int64", 0, -1, -1);
1497 ExpectLocation(&tree, d, "repeated_int32", 6, -1, -1);
1498 ExpectLocation(&tree, d, "some_unknown_field", -1, -1, -1);
1499
1500 // Verify inside the nested message.
1501 const FieldDescriptor* nested_field =
1502 d->FindFieldByName("optional_nested_message");
1503
1504 TextFormat::ParseInfoTree* nested_tree =
1505 tree.GetTreeForNested(nested_field, -1);
1506 ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 6, 2);
1507
1508 // Verify inside another nested message.
1509 nested_field = d->FindFieldByName("repeated_nested_message");
1510 nested_tree = tree.GetTreeForNested(nested_field, 0);
1511 ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 9, 2);
1512
1513 nested_tree = tree.GetTreeForNested(nested_field, 1);
1514 ExpectLocation(nested_tree, nested_field->message_type(), "bb", -1, 12, 2);
1515
1516 // Verify a NULL tree for an unknown nested field.
1517 TextFormat::ParseInfoTree* unknown_nested_tree =
1518 tree.GetTreeForNested(nested_field, 2);
1519
1520 EXPECT_EQ(NULL, unknown_nested_tree);
1521 }
1522
TEST_F(TextFormatParserTest,ParseFieldValueFromString)1523 TEST_F(TextFormatParserTest, ParseFieldValueFromString) {
1524 std::unique_ptr<unittest::TestAllTypes> message(new unittest::TestAllTypes);
1525 const Descriptor* d = message->GetDescriptor();
1526
1527 #define EXPECT_FIELD(name, value, valuestring) \
1528 EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
1529 valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1530 EXPECT_EQ(value, message->optional_##name()); \
1531 EXPECT_TRUE(message->has_optional_##name());
1532
1533 #define EXPECT_BOOL_FIELD(name, value, valuestring) \
1534 EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
1535 valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1536 EXPECT_TRUE(message->optional_##name() == value); \
1537 EXPECT_TRUE(message->has_optional_##name());
1538
1539 #define EXPECT_FLOAT_FIELD(name, value, valuestring) \
1540 EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
1541 valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1542 EXPECT_FLOAT_EQ(value, message->optional_##name()); \
1543 EXPECT_TRUE(message->has_optional_##name());
1544
1545 #define EXPECT_DOUBLE_FIELD(name, value, valuestring) \
1546 EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \
1547 valuestring, d->FindFieldByName("optional_" #name), message.get())); \
1548 EXPECT_DOUBLE_EQ(value, message->optional_##name()); \
1549 EXPECT_TRUE(message->has_optional_##name());
1550
1551 #define EXPECT_INVALID(name, valuestring) \
1552 EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \
1553 valuestring, d->FindFieldByName("optional_" #name), message.get()));
1554
1555 // int32
1556 EXPECT_FIELD(int32, 1, "1");
1557 EXPECT_FIELD(int32, -1, "-1");
1558 EXPECT_FIELD(int32, 0x1234, "0x1234");
1559 EXPECT_INVALID(int32, "a");
1560 EXPECT_INVALID(int32, "999999999999999999999999999999999999");
1561 EXPECT_INVALID(int32, "1,2");
1562
1563 // int64
1564 EXPECT_FIELD(int64, 1, "1");
1565 EXPECT_FIELD(int64, -1, "-1");
1566 EXPECT_FIELD(int64, 0x1234567812345678LL, "0x1234567812345678");
1567 EXPECT_INVALID(int64, "a");
1568 EXPECT_INVALID(int64, "999999999999999999999999999999999999");
1569 EXPECT_INVALID(int64, "1,2");
1570
1571 // uint64
1572 EXPECT_FIELD(uint64, 1, "1");
1573 EXPECT_FIELD(uint64, 0xf234567812345678ULL, "0xf234567812345678");
1574 EXPECT_INVALID(uint64, "-1");
1575 EXPECT_INVALID(uint64, "a");
1576 EXPECT_INVALID(uint64, "999999999999999999999999999999999999");
1577 EXPECT_INVALID(uint64, "1,2");
1578
1579 // fixed32
1580 EXPECT_FIELD(fixed32, 1, "1");
1581 EXPECT_FIELD(fixed32, 0x12345678, "0x12345678");
1582 EXPECT_INVALID(fixed32, "-1");
1583 EXPECT_INVALID(fixed32, "a");
1584 EXPECT_INVALID(fixed32, "999999999999999999999999999999999999");
1585 EXPECT_INVALID(fixed32, "1,2");
1586
1587 // fixed64
1588 EXPECT_FIELD(fixed64, 1, "1");
1589 EXPECT_FIELD(fixed64, 0x1234567812345678ULL, "0x1234567812345678");
1590 EXPECT_INVALID(fixed64, "-1");
1591 EXPECT_INVALID(fixed64, "a");
1592 EXPECT_INVALID(fixed64, "999999999999999999999999999999999999");
1593 EXPECT_INVALID(fixed64, "1,2");
1594
1595 // bool
1596 EXPECT_BOOL_FIELD(bool, true, "true");
1597 EXPECT_BOOL_FIELD(bool, false, "false");
1598 EXPECT_BOOL_FIELD(bool, true, "1");
1599 EXPECT_BOOL_FIELD(bool, true, "t");
1600 EXPECT_BOOL_FIELD(bool, false, "0");
1601 EXPECT_BOOL_FIELD(bool, false, "f");
1602 EXPECT_FIELD(bool, true, "True");
1603 EXPECT_FIELD(bool, false, "False");
1604 EXPECT_INVALID(bool, "tRue");
1605 EXPECT_INVALID(bool, "faLse");
1606 EXPECT_INVALID(bool, "2");
1607 EXPECT_INVALID(bool, "-0");
1608 EXPECT_INVALID(bool, "on");
1609 EXPECT_INVALID(bool, "a");
1610
1611 // float
1612 EXPECT_FIELD(float, 1, "1");
1613 EXPECT_FLOAT_FIELD(float, 1.5, "1.5");
1614 EXPECT_FLOAT_FIELD(float, 1.5e3, "1.5e3");
1615 EXPECT_FLOAT_FIELD(float, -4.55, "-4.55");
1616 EXPECT_INVALID(float, "a");
1617 EXPECT_INVALID(float, "1,2");
1618
1619 // double
1620 EXPECT_FIELD(double, 1, "1");
1621 EXPECT_FIELD(double, -1, "-1");
1622 EXPECT_DOUBLE_FIELD(double, 2.3, "2.3");
1623 EXPECT_DOUBLE_FIELD(double, 3e5, "3e5");
1624 EXPECT_INVALID(double, "a");
1625 EXPECT_INVALID(double, "1,2");
1626 // Rejects hex and oct numbers for a double field.
1627 EXPECT_INVALID(double, "0xf");
1628 EXPECT_INVALID(double, "012");
1629
1630 // string
1631 EXPECT_FIELD(string, "hello", "\"hello\"");
1632 EXPECT_FIELD(string, "-1.87", "'-1.87'");
1633 EXPECT_INVALID(string, "hello"); // without quote for value
1634
1635 // enum
1636 EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR");
1637 EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAZ,
1638 StrCat(unittest::TestAllTypes::BAZ));
1639 EXPECT_INVALID(nested_enum, "FOOBAR");
1640
1641 // message
1642 EXPECT_TRUE(TextFormat::ParseFieldValueFromString(
1643 "<bb:12>", d->FindFieldByName("optional_nested_message"), message.get()));
1644 EXPECT_EQ(12, message->optional_nested_message().bb());
1645 EXPECT_TRUE(message->has_optional_nested_message());
1646 EXPECT_INVALID(nested_message, "any");
1647
1648 #undef EXPECT_FIELD
1649 #undef EXPECT_BOOL_FIELD
1650 #undef EXPECT_FLOAT_FIELD
1651 #undef EXPECT_DOUBLE_FIELD
1652 #undef EXPECT_INVALID
1653 }
1654
TEST_F(TextFormatParserTest,InvalidToken)1655 TEST_F(TextFormatParserTest, InvalidToken) {
1656 ExpectFailure("optional_bool: true\n-5\n", "Expected identifier, got: -", 2,
1657 1);
1658
1659 ExpectFailure("optional_bool: true!\n", "Expected identifier, got: !", 1, 20);
1660 ExpectFailure("\"some string\"", "Expected identifier, got: \"some string\"",
1661 1, 1);
1662 }
1663
TEST_F(TextFormatParserTest,InvalidFieldName)1664 TEST_F(TextFormatParserTest, InvalidFieldName) {
1665 ExpectFailure(
1666 "invalid_field: somevalue\n",
1667 "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1668 "\"invalid_field\".",
1669 1, 14);
1670 }
1671
TEST_F(TextFormatParserTest,InvalidCapitalization)1672 TEST_F(TextFormatParserTest, InvalidCapitalization) {
1673 // We require that group names be exactly as they appear in the .proto.
1674 ExpectFailure(
1675 "optionalgroup {\na: 15\n}\n",
1676 "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1677 "\"optionalgroup\".",
1678 1, 15);
1679 ExpectFailure(
1680 "OPTIONALgroup {\na: 15\n}\n",
1681 "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1682 "\"OPTIONALgroup\".",
1683 1, 15);
1684 ExpectFailure(
1685 "Optional_Double: 10.0\n",
1686 "Message type \"protobuf_unittest.TestAllTypes\" has no field named "
1687 "\"Optional_Double\".",
1688 1, 16);
1689 }
1690
TEST_F(TextFormatParserTest,AllowIgnoreCapitalizationError)1691 TEST_F(TextFormatParserTest, AllowIgnoreCapitalizationError) {
1692 TextFormat::Parser parser;
1693 protobuf_unittest::TestAllTypes proto;
1694
1695 // These fields have a mismatching case.
1696 EXPECT_FALSE(parser.ParseFromString("Optional_Double: 10.0", &proto));
1697 EXPECT_FALSE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto));
1698
1699 // ... but are parsed correctly if we match case insensitive.
1700 parser.AllowCaseInsensitiveField(true);
1701 EXPECT_TRUE(parser.ParseFromString("Optional_Double: 10.0", &proto));
1702 EXPECT_EQ(10.0, proto.optional_double());
1703 EXPECT_TRUE(parser.ParseFromString("oPtIoNaLgRoUp { a: 15 }", &proto));
1704 EXPECT_EQ(15, proto.optionalgroup().a());
1705 }
1706
TEST_F(TextFormatParserTest,InvalidFieldValues)1707 TEST_F(TextFormatParserTest, InvalidFieldValues) {
1708 // Invalid values for a double/float field.
1709 ExpectFailure("optional_double: \"hello\"\n",
1710 "Expected double, got: \"hello\"", 1, 18);
1711 ExpectFailure("optional_double: true\n", "Expected double, got: true", 1, 18);
1712 ExpectFailure("optional_double: !\n", "Expected double, got: !", 1, 18);
1713 ExpectFailure("optional_double {\n \n}\n", "Expected \":\", found \"{\".", 1,
1714 17);
1715
1716 // Invalid values for a signed integer field.
1717 ExpectFailure("optional_int32: \"hello\"\n",
1718 "Expected integer, got: \"hello\"", 1, 17);
1719 ExpectFailure("optional_int32: true\n", "Expected integer, got: true", 1, 17);
1720 ExpectFailure("optional_int32: 4.5\n", "Expected integer, got: 4.5", 1, 17);
1721 ExpectFailure("optional_int32: !\n", "Expected integer, got: !", 1, 17);
1722 ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", 1,
1723 16);
1724 ExpectFailure("optional_int32: 0x80000000\n",
1725 "Integer out of range (0x80000000)", 1, 17);
1726 ExpectFailure("optional_int64: 0x8000000000000000\n",
1727 "Integer out of range (0x8000000000000000)", 1, 17);
1728 ExpectFailure("optional_int32: -0x80000001\n",
1729 "Integer out of range (0x80000001)", 1, 18);
1730 ExpectFailure("optional_int64: -0x8000000000000001\n",
1731 "Integer out of range (0x8000000000000001)", 1, 18);
1732
1733 // Invalid values for an unsigned integer field.
1734 ExpectFailure("optional_uint64: \"hello\"\n",
1735 "Expected integer, got: \"hello\"", 1, 18);
1736 ExpectFailure("optional_uint64: true\n", "Expected integer, got: true", 1,
1737 18);
1738 ExpectFailure("optional_uint64: 4.5\n", "Expected integer, got: 4.5", 1, 18);
1739 ExpectFailure("optional_uint64: -5\n", "Expected integer, got: -", 1, 18);
1740 ExpectFailure("optional_uint64: !\n", "Expected integer, got: !", 1, 18);
1741 ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", 1,
1742 17);
1743 ExpectFailure("optional_uint32: 0x100000000\n",
1744 "Integer out of range (0x100000000)", 1, 18);
1745 ExpectFailure("optional_uint64: 0x10000000000000000\n",
1746 "Integer out of range (0x10000000000000000)", 1, 18);
1747
1748 // Invalid values for a boolean field.
1749 ExpectFailure("optional_bool: \"hello\"\n",
1750 "Expected identifier, got: \"hello\"", 1, 16);
1751 ExpectFailure("optional_bool: 5\n", "Integer out of range (5)", 1, 16);
1752 ExpectFailure("optional_bool: -7.5\n", "Expected identifier, got: -", 1, 16);
1753 ExpectFailure("optional_bool: !\n", "Expected identifier, got: !", 1, 16);
1754
1755 ExpectFailure(
1756 "optional_bool: meh\n",
1757 "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", 2,
1758 1);
1759
1760 ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", 1,
1761 15);
1762
1763 // Invalid values for a string field.
1764 ExpectFailure("optional_string: true\n", "Expected string, got: true", 1, 18);
1765 ExpectFailure("optional_string: 5\n", "Expected string, got: 5", 1, 18);
1766 ExpectFailure("optional_string: -7.5\n", "Expected string, got: -", 1, 18);
1767 ExpectFailure("optional_string: !\n", "Expected string, got: !", 1, 18);
1768 ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", 1,
1769 17);
1770
1771 // Invalid values for an enumeration field.
1772 ExpectFailure("optional_nested_enum: \"hello\"\n",
1773 "Expected integer or identifier, got: \"hello\"", 1, 23);
1774
1775 // Valid token, but enum value is not defined.
1776 ExpectFailure("optional_nested_enum: 5\n",
1777 "Unknown enumeration value of \"5\" for field "
1778 "\"optional_nested_enum\".",
1779 2, 1);
1780 // We consume the negative sign, so the error position starts one character
1781 // later.
1782 ExpectFailure("optional_nested_enum: -7.5\n", "Expected integer, got: 7.5", 1,
1783 24);
1784 ExpectFailure("optional_nested_enum: !\n",
1785 "Expected integer or identifier, got: !", 1, 23);
1786
1787 ExpectFailure("optional_nested_enum: grah\n",
1788 "Unknown enumeration value of \"grah\" for field "
1789 "\"optional_nested_enum\".",
1790 2, 1);
1791
1792 ExpectFailure("optional_nested_enum {\n \n}\n",
1793 "Expected \":\", found \"{\".", 1, 22);
1794 }
1795
TEST_F(TextFormatParserTest,MessageDelimiters)1796 TEST_F(TextFormatParserTest, MessageDelimiters) {
1797 // Non-matching delimiters.
1798 ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", 3,
1799 1);
1800
1801 // Invalid delimiters.
1802 ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", 1,
1803 15);
1804
1805 // Unending message.
1806 ExpectFailure("optional_nested_message {\n \nbb: 118\n",
1807 "Expected identifier, got: ", 4, 1);
1808 }
1809
TEST_F(TextFormatParserTest,UnknownExtension)1810 TEST_F(TextFormatParserTest, UnknownExtension) {
1811 // Non-matching delimiters.
1812 ExpectFailure("[blahblah]: 123",
1813 "Extension \"blahblah\" is not defined or is not an "
1814 "extension of \"protobuf_unittest.TestAllTypes\".",
1815 1, 11);
1816 }
1817
TEST_F(TextFormatParserTest,MissingRequired)1818 TEST_F(TextFormatParserTest, MissingRequired) {
1819 unittest::TestRequired message;
1820 ExpectFailure("a: 1", "Message missing required fields: b, c", 0, 1,
1821 &message);
1822 }
1823
TEST_F(TextFormatParserTest,ParseDuplicateRequired)1824 TEST_F(TextFormatParserTest, ParseDuplicateRequired) {
1825 unittest::TestRequired message;
1826 ExpectFailure("a: 1 b: 2 c: 3 a: 1",
1827 "Non-repeated field \"a\" is specified multiple times.", 1, 17,
1828 &message);
1829 }
1830
TEST_F(TextFormatParserTest,ParseDuplicateOptional)1831 TEST_F(TextFormatParserTest, ParseDuplicateOptional) {
1832 unittest::ForeignMessage message;
1833 ExpectFailure("c: 1 c: 2",
1834 "Non-repeated field \"c\" is specified multiple times.", 1, 7,
1835 &message);
1836 }
1837
TEST_F(TextFormatParserTest,MergeDuplicateRequired)1838 TEST_F(TextFormatParserTest, MergeDuplicateRequired) {
1839 unittest::TestRequired message;
1840 TextFormat::Parser parser;
1841 EXPECT_TRUE(parser.MergeFromString("a: 1 b: 2 c: 3 a: 4", &message));
1842 EXPECT_EQ(4, message.a());
1843 }
1844
TEST_F(TextFormatParserTest,MergeDuplicateOptional)1845 TEST_F(TextFormatParserTest, MergeDuplicateOptional) {
1846 unittest::ForeignMessage message;
1847 TextFormat::Parser parser;
1848 EXPECT_TRUE(parser.MergeFromString("c: 1 c: 2", &message));
1849 EXPECT_EQ(2, message.c());
1850 }
1851
TEST_F(TextFormatParserTest,ExplicitDelimiters)1852 TEST_F(TextFormatParserTest, ExplicitDelimiters) {
1853 unittest::TestRequired message;
1854 EXPECT_TRUE(TextFormat::ParseFromString("a:1,b:2;c:3", &message));
1855 EXPECT_EQ(1, message.a());
1856 EXPECT_EQ(2, message.b());
1857 EXPECT_EQ(3, message.c());
1858 }
1859
TEST_F(TextFormatParserTest,PrintErrorsToStderr)1860 TEST_F(TextFormatParserTest, PrintErrorsToStderr) {
1861 std::vector<std::string> errors;
1862
1863 {
1864 ScopedMemoryLog log;
1865 unittest::TestAllTypes proto;
1866 EXPECT_FALSE(TextFormat::ParseFromString("no_such_field: 1", &proto));
1867 errors = log.GetMessages(ERROR);
1868 }
1869
1870 ASSERT_EQ(1, errors.size());
1871 EXPECT_EQ(
1872 "Error parsing text-format protobuf_unittest.TestAllTypes: "
1873 "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field "
1874 "named \"no_such_field\".",
1875 errors[0]);
1876 }
1877
TEST_F(TextFormatParserTest,FailsOnTokenizationError)1878 TEST_F(TextFormatParserTest, FailsOnTokenizationError) {
1879 std::vector<std::string> errors;
1880
1881 {
1882 ScopedMemoryLog log;
1883 unittest::TestAllTypes proto;
1884 EXPECT_FALSE(TextFormat::ParseFromString("\020", &proto));
1885 errors = log.GetMessages(ERROR);
1886 }
1887
1888 ASSERT_EQ(1, errors.size());
1889 EXPECT_EQ(
1890 "Error parsing text-format protobuf_unittest.TestAllTypes: "
1891 "1:1: Invalid control characters encountered in text.",
1892 errors[0]);
1893 }
1894
TEST_F(TextFormatParserTest,ParseDeprecatedField)1895 TEST_F(TextFormatParserTest, ParseDeprecatedField) {
1896 unittest::TestDeprecatedFields message;
1897 ExpectMessage("deprecated_int32: 42",
1898 "WARNING:text format contains deprecated field "
1899 "\"deprecated_int32\"",
1900 1, 21, &message, true);
1901 }
1902
TEST_F(TextFormatParserTest,SetRecursionLimit)1903 TEST_F(TextFormatParserTest, SetRecursionLimit) {
1904 const char* format = "child: { $0 }";
1905 std::string input;
1906 for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input);
1907
1908 unittest::NestedTestAllTypes message;
1909 ExpectSuccessAndTree(input, &message, nullptr);
1910
1911 input = strings::Substitute(format, input);
1912 parser_.SetRecursionLimit(100);
1913 ExpectMessage(input,
1914 "Message is too deep, the parser exceeded the configured "
1915 "recursion limit of 100.",
1916 1, 908, &message, false);
1917
1918 parser_.SetRecursionLimit(101);
1919 ExpectSuccessAndTree(input, &message, nullptr);
1920 }
1921
TEST_F(TextFormatParserTest,SetRecursionLimitUnknownFieldValue)1922 TEST_F(TextFormatParserTest, SetRecursionLimitUnknownFieldValue) {
1923 const char* format = "[$0]";
1924 std::string input = "\"test_value\"";
1925 for (int i = 0; i < 99; ++i) input = strings::Substitute(format, input);
1926 std::string not_deep_input = StrCat("unknown_nested_array: ", input);
1927
1928 parser_.AllowUnknownField(true);
1929 parser_.SetRecursionLimit(100);
1930
1931 unittest::NestedTestAllTypes message;
1932 ExpectSuccessAndTree(not_deep_input, &message, nullptr);
1933
1934 input = strings::Substitute(format, input);
1935 std::string deep_input = StrCat("unknown_nested_array: ", input);
1936 ExpectMessage(
1937 deep_input,
1938 "WARNING:Message type \"protobuf_unittest.NestedTestAllTypes\" has no "
1939 "field named \"unknown_nested_array\".\n1:123: Message is too deep, the "
1940 "parser exceeded the configured recursion limit of 100.",
1941 1, 21, &message, false);
1942
1943 parser_.SetRecursionLimit(101);
1944 ExpectSuccessAndTree(deep_input, &message, nullptr);
1945 }
1946
TEST_F(TextFormatParserTest,SetRecursionLimitUnknownFieldMessage)1947 TEST_F(TextFormatParserTest, SetRecursionLimitUnknownFieldMessage) {
1948 const char* format = "unknown_child: { $0 }";
1949 std::string input;
1950 for (int i = 0; i < 100; ++i) input = strings::Substitute(format, input);
1951
1952 parser_.AllowUnknownField(true);
1953 parser_.SetRecursionLimit(100);
1954
1955 unittest::NestedTestAllTypes message;
1956 ExpectSuccessAndTree(input, &message, nullptr);
1957
1958 input = strings::Substitute(format, input);
1959 ExpectMessage(
1960 input,
1961 "WARNING:Message type \"protobuf_unittest.NestedTestAllTypes\" has no "
1962 "field named \"unknown_child\".\n1:1716: Message is too deep, the parser "
1963 "exceeded the configured recursion limit of 100.",
1964 1, 14, &message, false);
1965
1966 parser_.SetRecursionLimit(101);
1967 ExpectSuccessAndTree(input, &message, nullptr);
1968 }
1969
1970 class TextFormatMessageSetTest : public testing::Test {
1971 protected:
1972 static const char proto_debug_string_[];
1973 };
1974 const char TextFormatMessageSetTest::proto_debug_string_[] =
1975 "message_set {\n"
1976 " [protobuf_unittest.TestMessageSetExtension1] {\n"
1977 " i: 23\n"
1978 " }\n"
1979 " [protobuf_unittest.TestMessageSetExtension2] {\n"
1980 " str: \"foo\"\n"
1981 " }\n"
1982 "}\n";
1983
TEST_F(TextFormatMessageSetTest,Serialize)1984 TEST_F(TextFormatMessageSetTest, Serialize) {
1985 protobuf_unittest::TestMessageSetContainer proto;
1986 protobuf_unittest::TestMessageSetExtension1* item_a =
1987 proto.mutable_message_set()->MutableExtension(
1988 protobuf_unittest::TestMessageSetExtension1::message_set_extension);
1989 item_a->set_i(23);
1990 protobuf_unittest::TestMessageSetExtension2* item_b =
1991 proto.mutable_message_set()->MutableExtension(
1992 protobuf_unittest::TestMessageSetExtension2::message_set_extension);
1993 item_b->set_str("foo");
1994 EXPECT_EQ(proto_debug_string_, proto.DebugString());
1995 }
1996
TEST_F(TextFormatMessageSetTest,Deserialize)1997 TEST_F(TextFormatMessageSetTest, Deserialize) {
1998 protobuf_unittest::TestMessageSetContainer proto;
1999 ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto));
2000 EXPECT_EQ(
2001 23,
2002 proto.message_set()
2003 .GetExtension(
2004 protobuf_unittest::TestMessageSetExtension1::message_set_extension)
2005 .i());
2006 EXPECT_EQ(
2007 "foo",
2008 proto.message_set()
2009 .GetExtension(
2010 protobuf_unittest::TestMessageSetExtension2::message_set_extension)
2011 .str());
2012
2013 // Ensure that these are the only entries present.
2014 std::vector<const FieldDescriptor*> descriptors;
2015 proto.message_set().GetReflection()->ListFields(proto.message_set(),
2016 &descriptors);
2017 EXPECT_EQ(2, descriptors.size());
2018 }
2019
TEST(TextFormatUnknownFieldTest,TestUnknownField)2020 TEST(TextFormatUnknownFieldTest, TestUnknownField) {
2021 protobuf_unittest::TestAllTypes proto;
2022 TextFormat::Parser parser;
2023 // Unknown field is not permitted by default.
2024 EXPECT_FALSE(parser.ParseFromString("unknown_field: 12345", &proto));
2025 EXPECT_FALSE(parser.ParseFromString("12345678: 12345", &proto));
2026
2027 parser.AllowUnknownField(true);
2028 EXPECT_TRUE(parser.ParseFromString("unknown_field: 12345", &proto));
2029 EXPECT_TRUE(parser.ParseFromString("unknown_field: -12345", &proto));
2030 EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345", &proto));
2031 EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345", &proto));
2032 EXPECT_TRUE(parser.ParseFromString("unknown_field: 1.2345f", &proto));
2033 EXPECT_TRUE(parser.ParseFromString("unknown_field: -1.2345f", &proto));
2034 EXPECT_TRUE(parser.ParseFromString("unknown_field: inf", &proto));
2035 EXPECT_TRUE(parser.ParseFromString("unknown_field: -inf", &proto));
2036 EXPECT_TRUE(parser.ParseFromString("unknown_field: TYPE_STRING", &proto));
2037 EXPECT_TRUE(
2038 parser.ParseFromString("unknown_field: \"string value\"", &proto));
2039 // Invalid field value
2040 EXPECT_FALSE(parser.ParseFromString("unknown_field: -TYPE_STRING", &proto));
2041 // Two or more unknown fields
2042 EXPECT_TRUE(
2043 parser.ParseFromString("unknown_field1: TYPE_STRING\n"
2044 "unknown_field2: 12345",
2045 &proto));
2046 // Unknown nested message
2047 EXPECT_TRUE(
2048 parser.ParseFromString("unknown_message1: {}\n"
2049 "unknown_message2 {\n"
2050 " unknown_field: 12345\n"
2051 "}\n"
2052 "unknown_message3 <\n"
2053 " unknown_nested_message {\n"
2054 " unknown_field: 12345\n"
2055 " }\n"
2056 ">",
2057 &proto));
2058 // Unmatched delimiters for message body
2059 EXPECT_FALSE(parser.ParseFromString("unknown_message: {>", &proto));
2060 // Unknown extension
2061 EXPECT_TRUE(
2062 parser.ParseFromString("[somewhere.unknown_extension1]: 12345\n"
2063 "[somewhere.unknown_extension2] {\n"
2064 " unknown_field: 12345\n"
2065 "}",
2066 &proto));
2067 // Unknown fields between known fields
2068 ASSERT_TRUE(
2069 parser.ParseFromString("optional_int32: 1\n"
2070 "unknown_field: 12345\n"
2071 "optional_string: \"string\"\n"
2072 "unknown_message { unknown: 0 }\n"
2073 "optional_nested_message { bb: 2 }",
2074 &proto));
2075 EXPECT_EQ(1, proto.optional_int32());
2076 EXPECT_EQ("string", proto.optional_string());
2077 EXPECT_EQ(2, proto.optional_nested_message().bb());
2078
2079 // Unknown field with numeric tag number instead of identifier.
2080 EXPECT_TRUE(parser.ParseFromString("12345678: 12345", &proto));
2081
2082 // Nested unknown extensions.
2083 EXPECT_TRUE(
2084 parser.ParseFromString("[test.extension1] <\n"
2085 " unknown_nested_message <\n"
2086 " [test.extension2] <\n"
2087 " unknown_field: 12345\n"
2088 " >\n"
2089 " >\n"
2090 ">",
2091 &proto));
2092 EXPECT_TRUE(
2093 parser.ParseFromString("[test.extension1] {\n"
2094 " unknown_nested_message {\n"
2095 " [test.extension2] {\n"
2096 " unknown_field: 12345\n"
2097 " }\n"
2098 " }\n"
2099 "}",
2100 &proto));
2101 EXPECT_TRUE(
2102 parser.ParseFromString("[test.extension1] <\n"
2103 " some_unknown_fields: <\n"
2104 " unknown_field: 12345\n"
2105 " >\n"
2106 ">",
2107 &proto));
2108 EXPECT_TRUE(
2109 parser.ParseFromString("[test.extension1] {\n"
2110 " some_unknown_fields: {\n"
2111 " unknown_field: 12345\n"
2112 " }\n"
2113 "}",
2114 &proto));
2115
2116 // Unknown field with compact repetition.
2117 EXPECT_TRUE(parser.ParseFromString("unknown_field: [1, 2]", &proto));
2118 // Unknown field with compact repetition of some unknown enum.
2119 EXPECT_TRUE(parser.ParseFromString("unknown_field: [VAL1, VAL2]", &proto));
2120 // Unknown field with compact repetition with sub-message.
2121 EXPECT_TRUE(parser.ParseFromString("unknown_field: [{a:1}, <b:2>]", &proto));
2122 }
2123
TEST(TextFormatUnknownFieldTest,TestAnyInUnknownField)2124 TEST(TextFormatUnknownFieldTest, TestAnyInUnknownField) {
2125 protobuf_unittest::TestAllTypes proto;
2126 TextFormat::Parser parser;
2127 parser.AllowUnknownField(true);
2128 EXPECT_TRUE(
2129 parser.ParseFromString("unknown {\n"
2130 " [type.googleapis.com/foo.bar] {\n"
2131 " }\n"
2132 "}",
2133 &proto));
2134 }
2135
TEST(TextFormatUnknownFieldTest,TestUnknownExtension)2136 TEST(TextFormatUnknownFieldTest, TestUnknownExtension) {
2137 protobuf_unittest::TestAllTypes proto;
2138 TextFormat::Parser parser;
2139 std::string message_with_ext =
2140 "[test.extension1] {\n"
2141 " some_unknown_fields: {\n"
2142 " unknown_field: 12345\n"
2143 " }\n"
2144 "}";
2145 // Unknown extensions are not permitted by default.
2146 EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto));
2147 // AllowUnknownField implies AllowUnknownExtension.
2148 parser.AllowUnknownField(true);
2149 EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto));
2150
2151 parser.AllowUnknownField(false);
2152 EXPECT_FALSE(parser.ParseFromString(message_with_ext, &proto));
2153 parser.AllowUnknownExtension(true);
2154 EXPECT_TRUE(parser.ParseFromString(message_with_ext, &proto));
2155 // Unknown fields are still not accepted.
2156 EXPECT_FALSE(parser.ParseFromString("unknown_field: 1", &proto));
2157 }
2158
2159
2160 } // namespace text_format_unittest
2161 } // namespace protobuf
2162 } // namespace google
2163