3

我写了以下方法:

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 或让它们更宽松?

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

4

1 回答 1

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
于 2018-06-23T17:39:40.110 回答