github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/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  	{Input: [][]string{{"abc\rdef"}}, Output: "\"abcdef\"\r\n", UseCRLF: true},
    30  	{Input: [][]string{{"abc\rdef"}}, Output: "\"abc\rdef\"\n", UseCRLF: false},
    31  }
    32  
    33  func TestWrite(t *testing.T) {
    34  	for n, tt := range writeTests {
    35  		b := &bytes.Buffer{}
    36  		f := NewWriter(b)
    37  		f.UseCRLF = tt.UseCRLF
    38  		err := f.WriteAll(tt.Input)
    39  		if err != nil {
    40  			t.Errorf("Unexpected error: %s\n", err)
    41  		}
    42  		out := b.String()
    43  		if out != tt.Output {
    44  			t.Errorf("#%d: out=%q want %q", n, out, tt.Output)
    45  		}
    46  	}
    47  }
    48  
    49  type errorWriter struct{}
    50  
    51  func (e errorWriter) Write(b []byte) (int, error) {
    52  	return 0, errors.New("Test")
    53  }
    54  
    55  func TestError(t *testing.T) {
    56  	b := &bytes.Buffer{}
    57  	f := NewWriter(b)
    58  	f.Write([]string{"abc"})
    59  	f.Flush()
    60  	err := f.Error()
    61  
    62  	if err != nil {
    63  		t.Errorf("Unexpected error: %s\n", err)
    64  	}
    65  
    66  	f = NewWriter(errorWriter{})
    67  	f.Write([]string{"abc"})
    68  	f.Flush()
    69  	err = f.Error()
    70  
    71  	if err == nil {
    72  		t.Error("Error should not be nil")
    73  	}
    74  }