Reputation: 49
I have written the following method:
func (c *Component) Encode(w io.Writer){
//encodes c and writes the bytes into w, containing a few CRLF linebreaks
}
I also wrote the function demonstrating the encoder:
func ExampleComponent_Encode() {
c := &Component{
Name: "DESCRIPTION",
}
c.Encode(os.Stdout)
//Output:
//BEGIN:DESCRIPTION
//END:DESCRIPTION
}
The Problem is now that this example fails the go test
command because the linebreaks in the comments are \n linebreaks (I'm on Linux) while the linebreaks generated by c.Encode
have to be \r\n(CRLF) linebreaks (as defined by some spec).
How can i get the example to not fail go test
while also keeping it straightforward? Is there perhaps a way to hint go test/godoc on the linebreaks or get them to be more lenient?
I propably can hand-edit the linebreaks on these two lines or possibly the whole codebase but that will be pretty fragile and I want to avoid this solution.
Upvotes: 3
Views: 626
Reputation: 166704
Redirect the Encode
io.Writer
to a buffer. In the buffer, replace CRLF (\r\n
) with LF (\n
) for the example output. For example,
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
}
Output:
$ go test -v example_test.go
=== RUN ExampleComponent_Encode
--- PASS: ExampleComponent_Encode (0.00s)
PASS
Upvotes: 1