带有CRLF的godoc示例输出
我编写了以下方法:带有CRLF的godoc示例输出,go,automated-tests,documentation-generation,godoc,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.Enc
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
命令,因为注释中的换行符是换行符(我在Linux上),而c.Encode
生成的换行符必须是\r\n(CRLF)换行符(由某些规范定义)
如何让示例在保持简单的同时不失败go test
?是否有办法提示对换行符进行测试/godoc,或者让他们更加宽容
我可能可以手动编辑这两行上的换行符,也可能编辑整个代码库,但这将非常脆弱,我希望避免使用此解决方案。将
编码io.Writer
重定向到缓冲区。在缓冲区中,将示例输出的CRLF(\r\n
)替换为LF(\n
)。比如说,
示例_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
不要在示例中包含输出(或至少省略输出:
)标题。改为在测试中验证正确性。