我写了以下方法:
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失败?有没有办法在换行符上提示go test/godoc,或者让它们变得更宽松一些?
我可以手动编辑这两行的换行符,也可以编辑整个代码库,但这将是非常脆弱的,我希望避免这种解决方案。
发布于 2018-06-24 01:39:40
将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)
PASShttps://stackoverflow.com/questions/50996081
复制相似问题