diff options
Diffstat (limited to 'src/pkg/encoding/csv')
-rw-r--r-- | src/pkg/encoding/csv/writer.go | 14 | ||||
-rw-r--r-- | src/pkg/encoding/csv/writer_test.go | 28 |
2 files changed, 38 insertions, 4 deletions
diff --git a/src/pkg/encoding/csv/writer.go b/src/pkg/encoding/csv/writer.go index c4dcba566..1faecb664 100644 --- a/src/pkg/encoding/csv/writer.go +++ b/src/pkg/encoding/csv/writer.go @@ -22,7 +22,7 @@ import ( // // If UseCRLF is true, the Writer ends each record with \r\n instead of \n. type Writer struct { - Comma rune // Field delimiter (set to to ',' by NewWriter) + Comma rune // Field delimiter (set to ',' by NewWriter) UseCRLF bool // True to use \r\n as the line terminator w *bufio.Writer } @@ -92,20 +92,26 @@ func (w *Writer) Write(record []string) (err error) { } // Flush writes any buffered data to the underlying io.Writer. +// To check if an error occurred during the Flush, call Error. func (w *Writer) Flush() { w.w.Flush() } +// Error reports any error that has occurred during a previous Write or Flush. +func (w *Writer) Error() error { + _, err := w.w.Write(nil) + return err +} + // WriteAll writes multiple CSV records to w using Write and then calls Flush. func (w *Writer) WriteAll(records [][]string) (err error) { for _, record := range records { err = w.Write(record) if err != nil { - break + return err } } - w.Flush() - return nil + return w.w.Flush() } // fieldNeedsQuotes returns true if our field must be enclosed in quotes. diff --git a/src/pkg/encoding/csv/writer_test.go b/src/pkg/encoding/csv/writer_test.go index 578959007..03ca6b093 100644 --- a/src/pkg/encoding/csv/writer_test.go +++ b/src/pkg/encoding/csv/writer_test.go @@ -6,6 +6,7 @@ package csv import ( "bytes" + "errors" "testing" ) @@ -42,3 +43,30 @@ func TestWrite(t *testing.T) { } } } + +type errorWriter struct{} + +func (e errorWriter) Write(b []byte) (int, error) { + return 0, errors.New("Test") +} + +func TestError(t *testing.T) { + b := &bytes.Buffer{} + f := NewWriter(b) + f.Write([]string{"abc"}) + f.Flush() + err := f.Error() + + if err != nil { + t.Errorf("Unexpected error: %s\n", err) + } + + f = NewWriter(errorWriter{}) + f.Write([]string{"abc"}) + f.Flush() + err = f.Error() + + if err == nil { + t.Error("Error should not be nil") + } +} |