Avoid byte[] to String to byte[] conversion when pretty printing

Previously, PrettyPrintingContentModifier would convert the byte[]
content into a String and then back into a byte[]. It did so without
consideration for the content’s character set. As a result, it could
fail to preserve the correct character encoding.

This commit updates PrettyPrintingContentModifier to avoid converting
the content into a String and back into a byte[] and to work entirely
with byte arrays instead. Removing the intermediate String from the
process removes the possibility of the content becoming corrupted.

Closes gh-202
This commit is contained in:
Andy Wilkinson
2016-02-15 11:30:28 +00:00
parent 74f9e272fd
commit cfc413f7ed
2 changed files with 31 additions and 11 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2015 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,12 +16,17 @@
package org.springframework.restdocs.operation.preprocess;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.restdocs.test.OutputCapture;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.junit.Assert.assertThat;
@@ -68,4 +73,16 @@ public class PrettyPrintingContentModifierTests {
null), equalTo(content.getBytes()));
}
@Test
public void encodingIsPreserved() throws Exception {
Map<String, String> input = new HashMap<>();
input.put("japanese", "\u30b3\u30f3\u30c6\u30f3\u30c4");
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, String> output = objectMapper
.readValue(new PrettyPrintingContentModifier().modifyContent(
objectMapper.writeValueAsBytes(input), null), Map.class);
assertThat(output, is(equalTo(input)));
}
}