Started working on unit tests

Fixed some bugs in the CSVColumn processor
This commit is contained in:
Leon Mika 2023-04-24 04:08:46 +00:00
parent 1c08248c69
commit 8c7e9453ee
3 changed files with 70 additions and 5 deletions

3
csv.go
View file

@ -9,6 +9,7 @@ import (
func CSVColumn(name string) func(r io.Reader, w io.Writer) error { func CSVColumn(name string) func(r io.Reader, w io.Writer) error {
return func(r io.Reader, w io.Writer) error { return func(r io.Reader, w io.Writer) error {
cr := csv.NewReader(r) cr := csv.NewReader(r)
cr.FieldsPerRecord = -1
header, err := cr.Read() header, err := cr.Read()
if err != nil { if err != nil {
@ -34,7 +35,7 @@ func CSVColumn(name string) func(r io.Reader, w io.Writer) error {
return err return err
} }
} }
if len(rec) < colIdx { if len(rec) <= colIdx {
continue continue
} }

31
csv_test.go Normal file
View file

@ -0,0 +1,31 @@
package scriptx_test
import (
"testing"
"github.com/bitfield/script"
"github.com/lmika/scriptx"
)
func TestCSVColumn(t *testing.T) {
t.Run("should return named column of CSV input", func(t *testing.T) {
verifyPipeLines(t, func(p *script.Pipe) *script.Pipe {
return p.Filter(scriptx.CSVColumn("state"))
}, []string{
"city,state,country",
"Melbourne,Vic,AU",
"Sydney,NSW,AU",
"Canberra,\"Territory, Australian Capital\",AU",
"New York,NY,US,Extra,Comments,Allowed",
"Missing state is ignored",
"# Comment is ignored",
"Seattle,WA",
}, []string{
"Vic",
"NSW",
"Territory, Australian Capital",
"NY",
"WA",
})
})
}

View file

@ -1,7 +1,40 @@
package scriptx_test package scriptx_test
import "testing" import (
"testing"
"github.com/bitfield/script"
"github.com/lmika/scriptx"
"github.com/stretchr/testify/assert"
)
func TestPrintf(t *testing.T) { func TestPrintf(t *testing.T) {
t.Log("Hello") t.Run("should format each line according to the pattern", func(t *testing.T) {
verifyPipeLines(t, func(p *script.Pipe) *script.Pipe {
return p.Filter(scriptx.Printf("Line: [%v]"))
}, []string{
"Line 1",
"Line 2",
"Line 3",
}, []string{
"Line: [Line 1]",
"Line: [Line 2]",
"Line: [Line 3]",
})
})
}
func verifyPipeLines(t *testing.T, fn func(p *script.Pipe) *script.Pipe, inLines []string, expOut []string) {
pipe := script.Slice(inLines)
outLines, err := fn(pipe).Slice()
assert.NoError(t, err)
assert.Equal(t, expOut, outLines)
}
func verifyPipeErr(t *testing.T, fn func(p *script.Pipe) *script.Pipe, inLines []string) {
pipe := script.Slice(inLines)
_, err := fn(pipe).Slice()
assert.Error(t, err)
} }