Spring REST Docs

时间:2017-04-28 12:35:51

标签: spring spring-restdocs

我有一个REST端点,可以生成随机图像。我使用的是Spring REST Docs,但是响应在http-response.adoc文件中都是乱码。有没有一种简单的方法让Mock MVC和REST Docs将文件存储在某处,以便我的.adoc文件可以引用它?

3 个答案:

答案 0 :(得分:1)

不是完美但有效的解决方案:

class ImageSnippet implements Snippet {

    private final String filePath;

    public ImageSnippet(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public void document(Operation operation) throws IOException {
        byte[] picture = operation.getResponse().getContent();

        Path path = Paths.get(filePath);
        Files.deleteIfExists(path);
        Files.createDirectories(path.getParent());
        Files.createFile(path);

        try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
            fos.write(picture);
        }
    }
}

在MockMvc测试中使用(图像文件夹路径很重要):

    mockMvc.perform(get("/my-profile/barcode")
                      .accept(MediaType.IMAGE_PNG))
            .andExpect(status().isOk())
            .andDo(document("my-profile/barcode",
                      new ImageSnippet("build/asciidoc/html5/images/barcode.png")));

.adoc模板中:

 image::barcode.png[]

这是我的build.gradle Asciidoctor配置(imagesdir很重要):

asciidoctor {
    dependsOn test
    backends = ['html5']
    options doctype: 'book'

    attributes = [
            'source-highlighter': 'highlightjs',
            'imagesdir'         : './images',
            'toc'               : 'left',
            'toclevels'         : 3,
            'numbered'          : '',
            'icons'             : 'font',
            'setanchors'        : '',
            'idprefix'          : '',
            'idseparator'       : '-',
            'docinfo1'          : '',
            'safe-mode-unsafe'  : '',
            'allow-uri-read'    : '',
            'snippets'          : snippetsDir,
            linkattrs           : true,
            encoding            : 'utf-8'
    ]

    inputs.dir snippetsDir
    outputDir 'build/asciidoc'
    sourceDir 'src/docs/asciidoc'
    sources {
        include 'index.adoc'
    }
}

答案 1 :(得分:1)

您可以做的是实现一个自定义代码段,以保存生成的响应。您可以使用收到的操作的RestDocumentationContext属性获取输出目录。

    mockMvc.perform(get("/example"))
            .andDo(document("some-example", operation -> {
                var context = (RestDocumentationContext) operation.getAttributes().get(RestDocumentationContext.class.getName());
                var path = Paths.get(context.getOutputDirectory().getAbsolutePath(), operation.getName(), "response-file.png");
                Files.createDirectories(path.getParent());
                Files.write(path, operation.getResponse().getContent());
            }));

但是,这将在输出目录中创建一个.png文件,如果您在需要嵌入该文件的源目录中包含Asciidoc,则通常没有用。因此,您可以做的是创建一个Asciidoc文件,其中包含图像标签的自定义HTML,其源是响应的base64表示形式。

    mockMvc.perform(get("/example"))
            .andDo(document("some-example", operation -> {
                var context = (RestDocumentationContext) operation.getAttributes().get(RestDocumentationContext.class.getName());
                var path = Paths.get(context.getOutputDirectory().getAbsolutePath(), operation.getName(), "response-file.adoc");
                var outputStream = new ByteArrayOutputStream();
                outputStream.write("++++\n".getBytes());
                outputStream.write("<img src=\"data:image/png;base64,".getBytes());
                outputStream.write(Base64.getEncoder().encode(operation.getResponse().getContent()));
                outputStream.write("\"/>\n".getBytes());
                outputStream.write("++++\n".getBytes());
                Files.createDirectories(path.getParent());
                Files.write(path, outputStream.toByteArray());
            }));

尽管在空间方面会增加一些开销,但如果使用它,则无需弄乱从源中引用构建文件。

答案 2 :(得分:0)

如果您不需要/不想在文档中显示图像的另一种方法:使用ContentModifyingOperationPreprocessor用一些字符串替换字节,这使文档的读者可以清楚地看到响应中有一些图像字节。

例如:

        mockMvc.perform(get("/api/users/{id}/avatar", user.getId().asString())
                                .with(createCustomerAuth()))
               .andExpect(status().isOk())
               .andDo(document("get-user-avatar-example",
                               null,
                               Preprocessors.preprocessResponse(new ContentModifyingOperationPreprocessor(new ContentModifier() {
                                   @Override
                                   public byte[] modifyContent(byte[] originalContent, MediaType contentType) {
                                       return "<< IMAGE BODY HERE >>".getBytes(StandardCharsets.UTF_8);
                                   }
                               }))));

这将生成一个adoc文件,如下所示:

[source,http,options="nowrap"]
----
HTTP/1.1 200 OK
Content-Type: image/png
Content-Length: 15
Cache-Control: max-age=3600

<< IMAGE BODY HERE >>
----