示例#1
0
func TestCSVWriterStruct(t *testing.T) {
	fname := "testdata/out-struct.csv"
	tbl, err := csvutil.Create(fname)
	if err != nil {
		t.Errorf("could not create %s: %v\n", fname, err)
	}
	defer tbl.Close()
	tbl.Writer.Comma = ';'

	// test WriteHeader w/o a trailing newline
	err = tbl.WriteHeader("## a simple set of data: int64;float64;string")
	if err != nil {
		t.Errorf("error writing header: %v\n", err)
	}

	for i := 0; i < 10; i++ {
		data := struct {
			I int
			F float64
			S string
		}{
			I: i,
			F: float64(i),
			S: fmt.Sprintf("str-%d", i),
		}
		err = tbl.WriteRow(data)
		if err != nil {
			t.Errorf("error writing row %d: %v\n", i, err)
			break
		}
	}

	err = tbl.Close()
	if err != nil {
		t.Errorf("error closing table: %v\n", err)
	}

	err = diff("testdata/simple.csv", fname)
	if err != nil {
		t.Errorf("files differ: %v\n", err)
	}
}
示例#2
0
func TestCSVWriterArgs(t *testing.T) {
	fname := "testdata/out-args.csv"
	tbl, err := csvutil.Create(fname)
	if err != nil {
		t.Errorf("could not create %s: %v\n", fname, err)
	}
	defer tbl.Close()
	tbl.Writer.Comma = ';'

	err = tbl.WriteHeader("## a simple set of data: int64;float64;string\n")
	if err != nil {
		t.Errorf("error writing header: %v\n", err)
	}

	for i := 0; i < 10; i++ {
		var (
			f = float64(i)
			s = fmt.Sprintf("str-%d", i)
		)
		err = tbl.WriteRow(i, f, s)
		if err != nil {
			t.Errorf("error writing row %d: %v\n", i, err)
			break
		}
	}

	err = tbl.Close()
	if err != nil {
		t.Errorf("error closing table: %v\n", err)
	}

	err = diff("testdata/simple.csv", fname)
	if err != nil {
		t.Errorf("files differ: %v\n", err)
	}
}
示例#3
0
func TestCSVAppend(t *testing.T) {
	fname := "testdata/append-test.csv"
	tbl, err := csvutil.Create(fname)
	if err != nil {
		t.Fatal(err)
	}
	defer tbl.Close()

	tbl.Writer.Comma = ';'

	// test WriteHeader w/o a trailing newline
	err = tbl.WriteHeader("## a simple set of data: int64;float64;string")
	if err != nil {
		t.Errorf("error writing header: %v\n", err)
	}

	for i := 0; i < 10; i++ {
		data := struct {
			I int
			F float64
			S string
		}{
			I: i,
			F: float64(i),
			S: fmt.Sprintf("str-%d", i),
		}
		err = tbl.WriteRow(data)
		if err != nil {
			t.Errorf("error writing row %d: %v\n", i, err)
			break
		}
	}

	err = tbl.Close()
	if err != nil {
		t.Errorf("error closing table: %v\n", err)
	}

	// re-open to append
	tbl, err = csvutil.Append(fname)
	if err != nil {
		t.Fatal(err)
	}
	defer tbl.Close()

	tbl.Writer.Comma = ';'
	for i := 10; i < 20; i++ {
		data := struct {
			I int
			F float64
			S string
		}{
			I: i,
			F: float64(i),
			S: fmt.Sprintf("str-%d", i),
		}
		err = tbl.WriteRow(data)
		if err != nil {
			t.Errorf("error writing row %d: %v\n", i, err)
			break
		}
	}

	err = tbl.Close()
	if err != nil {
		t.Fatal(err)
	}

	err = diff("testdata/append.csv", fname)
	if err != nil {
		t.Errorf("files differ: %v\n", err)
	}
}