github.com/grailbio/base@v0.0.11/tsv/row_writer_test.go (about)

     1  // Copyright 2019 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package tsv_test
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"testing"
    11  
    12  	"github.com/grailbio/base/tsv"
    13  )
    14  
    15  func TestRowWriter(t *testing.T) {
    16  	var buf bytes.Buffer
    17  	rw := tsv.NewRowWriter(&buf)
    18  	type embedded struct {
    19  		EmbeddedString string  `tsv:"estring"`
    20  		EmbeddedFloat  float64 `tsv:"efloat,fmt=0.3f"`
    21  	}
    22  	var row struct {
    23  		Bool    bool   `tsv:"true_or_false"`
    24  		String  string `tsv:"name"`
    25  		Int8    int8
    26  		Int16   int16
    27  		Int32   int32
    28  		Int64   int64
    29  		Int     int
    30  		Uint8   uint8
    31  		Uint16  uint16
    32  		Uint32  uint32
    33  		Uint64  uint64
    34  		Uint    uint
    35  		Float32 float32
    36  		Float64 float64
    37  		embedded
    38  		skippedString string
    39  		skippedFunc   func()
    40  	}
    41  	row.String = "abc"
    42  	row.Float32 = -3
    43  	row.Float64 = 1e300
    44  	if err := rw.Write(&row); err != nil {
    45  		t.Error(err)
    46  	}
    47  	row.String = "def"
    48  	row.Int = 2
    49  	row.Float32 = 0
    50  	row.EmbeddedString = "estring"
    51  	row.EmbeddedFloat = 0.123456
    52  	if err := rw.Write(&row); err != nil {
    53  		t.Error(err)
    54  	}
    55  	if err := rw.Flush(); err != nil {
    56  		t.Error(err)
    57  	}
    58  	got := buf.String()
    59  	want := `true_or_false	name	Int8	Int16	Int32	Int64	Int	Uint8	Uint16	Uint32	Uint64	Uint	Float32	Float64	estring	efloat
    60  false	abc	0	0	0	0	0	0	0	0	0	0	-3	1e+300		0.000
    61  false	def	0	0	0	0	2	0	0	0	0	0	0	1e+300	estring	0.123
    62  `
    63  	if got != want {
    64  		t.Errorf("got: %q, want %q", got, want)
    65  	}
    66  }
    67  
    68  func ExampleRowWriter() {
    69  	type rowTyp struct {
    70  		Foo float64 `tsv:"foo,fmt=.2f"`
    71  		Bar float64 `tsv:"bar,fmt=.3f"`
    72  		Baz float64
    73  	}
    74  	rows := []rowTyp{
    75  		{Foo: 0.1234, Bar: 0.4567, Baz: 0.9876},
    76  		{Foo: 1.1234, Bar: 1.4567, Baz: 1.9876},
    77  	}
    78  	var buf bytes.Buffer
    79  	w := tsv.NewRowWriter(&buf)
    80  	for i := range rows {
    81  		if err := w.Write(&rows[i]); err != nil {
    82  			panic(err)
    83  		}
    84  	}
    85  	if err := w.Flush(); err != nil {
    86  		panic(err)
    87  	}
    88  	fmt.Print(string(buf.Bytes()))
    89  
    90  	// Output:
    91  	// foo	bar	Baz
    92  	// 0.12	0.457	0.9876
    93  	// 1.12	1.457	1.9876
    94  }