godoc带CRLF的示例输出

时间:2018-06-22 21:59:43

标签: go automated-tests documentation-generation godoc

我写了以下方法:

func (c *Component) Encode(w io.Writer){
    //encodes c and writes the bytes into w, containing a few CRLF linebreaks
}

我还编写了演示编码器的函数:

func ExampleComponent_Encode() {

    c := &Component{
        Name: "DESCRIPTION",
    }
    c.Encode(os.Stdout)
    //Output:
    //BEGIN:DESCRIPTION
    //END:DESCRIPTION
}

现在的问题是,此示例使go test命令失败,因为注释中的换行符为\ n换行符(我在Linux上),而c.Encode生成的换行符必须为\ r \ n(CRLF)换行符(某些规范定义)。

如何使示例不失败go test,同时又保持简单?也许有什么方法可以提示您对换行进行测试/ godoc或使其更加宽容?

我可以手动编辑这两行或整个代码库上的换行符,但这将非常脆弱,我想避免这种解决方案。

1 个答案:

答案 0 :(得分:1)

Encode io.Writer重定向到缓冲区。在缓冲区中,将示例输出的CRLF(\r\n)替换为LF(\n)。例如,

example_test.go

package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "strings"
)

type Component struct{ Name string }

func (c *Component) Encode(w io.Writer) {
    //encodes c and writes the bytes into w, containing a few CRLF linebreaks
    w.Write([]byte("BEGIN:" + c.Name + "\r\n"))
    w.Write([]byte("END:" + c.Name + "\r\n"))
}

func ExampleComponent_Encode() {
    var buf bytes.Buffer
    c := &Component{
        Name: "DESCRIPTION",
    }
    c.Encode(&buf)

    output := strings.Replace(buf.String(), "\r\n", "\n", -1)
    fmt.Fprintf(os.Stdout, "%s", output)
    //Output:
    //BEGIN:DESCRIPTION
    //END:DESCRIPTION
}

输出:

$ go test -v example_test.go
=== RUN   ExampleComponent_Encode
--- PASS: ExampleComponent_Encode (0.00s)
PASS