Make Java TextFormat.printToUnicodeString() escape newlines.

Fix issue #77
pull/109/head
Feng Xiao 10 years ago
parent 209840eca7
commit 90f2f50233
  1. 3
      java/src/main/java/com/google/protobuf/TextFormat.java
  2. 18
      java/src/test/java/com/google/protobuf/TextFormatTest.java

@ -411,7 +411,8 @@ public final class TextFormat {
generator.print("\"");
generator.print(escapeNonAscii ?
escapeText((String) value) :
escapeDoubleQuotesAndBackslashes((String) value));
escapeDoubleQuotesAndBackslashes((String) value)
.replace("\n", "\\n"));
generator.print("\"");
break;

@ -864,15 +864,15 @@ public class TextFormatTest extends TestCase {
assertEquals(message.getOptionalString(), builder.getOptionalString());
}
public void testPrintToUnicodeStringWithNewlines() {
public void testPrintToUnicodeStringWithNewlines() throws Exception {
// No newlines at start and end
assertEquals("optional_string: \"test newlines\n\nin\nstring\"\n",
assertEquals("optional_string: \"test newlines\\n\\nin\\nstring\"\n",
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("test newlines\n\nin\nstring")
.build()));
// Newlines at start and end
assertEquals("optional_string: \"\ntest\nnewlines\n\nin\nstring\n\"\n",
assertEquals("optional_string: \"\\ntest\\nnewlines\\n\\nin\\nstring\\n\"\n",
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
.build()));
@ -882,14 +882,22 @@ public class TextFormatTest extends TestCase {
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("")
.build()));
assertEquals("optional_string: \"\n\"\n",
assertEquals("optional_string: \"\\n\"\n",
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("\n")
.build()));
assertEquals("optional_string: \"\n\n\"\n",
assertEquals("optional_string: \"\\n\\n\"\n",
TextFormat.printToUnicodeString(TestAllTypes.newBuilder()
.setOptionalString("\n\n")
.build()));
// Test escaping roundtrip
TestAllTypes message = TestAllTypes.newBuilder()
.setOptionalString("\ntest\nnewlines\n\nin\nstring\n")
.build();
TestAllTypes.Builder builder = TestAllTypes.newBuilder();
TextFormat.merge(TextFormat.printToUnicodeString(message), builder);
assertEquals(message.getOptionalString(), builder.getOptionalString());
}
public void testPrintToUnicodeString_unknown() {

Loading…
Cancel
Save