github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/src/pkg/encoding/csv/writer_test.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package csv
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"testing"
    11  )
    12  
    13  var writeTests = []struct {
    14  	Input   [][]string
    15  	Output  string
    16  	UseCRLF bool
    17  }{
    18  	{Input: [][]string{{"abc"}}, Output: "abc\n"},
    19  	{Input: [][]string{{"abc"}}, Output: "abc\r\n", UseCRLF: true},
    20  	{Input: [][]string{{`"abc"`}}, Output: `"""abc"""` + "\n"},
    21  	{Input: [][]string{{`a"b`}}, Output: `"a""b"` + "\n"},
    22  	{Input: [][]string{{`"a"b"`}}, Output: `"""a""b"""` + "\n"},
    23  	{Input: [][]string{{" abc"}}, Output: `" abc"` + "\n"},
    24  	{Input: [][]string{{"abc,def"}}, Output: `"abc,def"` + "\n"},
    25  	{Input: [][]string{{"abc", "def"}}, Output: "abc,def\n"},
    26  	{Input: [][]string{{"abc"}, {"def"}}, Output: "abc\ndef\n"},
    27  	{Input: [][]string{{"abc\ndef"}}, Output: "\"abc\ndef\"\n"},
    28  	{Input: [][]string{{"abc\ndef"}}, Output: "\"abc\r\ndef\"\r\n", UseCRLF: true},
    29  }
    30  
    31  func TestWrite(t *testing.T) {
    32  	for n, tt := range writeTests {
    33  		b := &bytes.Buffer{}
    34  		f := NewWriter(b)
    35  		f.UseCRLF = tt.UseCRLF
    36  		err := f.WriteAll(tt.Input)
    37  		if err != nil {
    38  			t.Errorf("Unexpected error: %s\n", err)
    39  		}
    40  		out := b.String()
    41  		if out != tt.Output {
    42  			t.Errorf("#%d: out=%q want %q", n, out, tt.Output)
    43  		}
    44  	}
    45  }
    46  
    47  type errorWriter struct{}
    48  
    49  func (e errorWriter) Write(b []byte) (int, error) {
    50  	return 0, errors.New("Test")
    51  }
    52  
    53  func TestError(t *testing.T) {
    54  	b := &bytes.Buffer{}
    55  	f := NewWriter(b)
    56  	f.Write([]string{"abc"})
    57  	f.Flush()
    58  	err := f.Error()
    59  
    60  	if err != nil {
    61  		t.Errorf("Unexpected error: %s\n", err)
    62  	}
    63  
    64  	f = NewWriter(errorWriter{})
    65  	f.Write([]string{"abc"})
    66  	f.Flush()
    67  	err = f.Error()
    68  
    69  	if err == nil {
    70  		t.Error("Error should not be nil")
    71  	}
    72  }