From 8c7e9453ee680588a1b374e739323ce331458a1a Mon Sep 17 00:00:00 2001 From: Leon Mika Date: Mon, 24 Apr 2023 04:08:46 +0000 Subject: [PATCH] Started working on unit tests Fixed some bugs in the CSVColumn processor --- csv.go | 5 +++-- csv_test.go | 31 +++++++++++++++++++++++++++++++ fmt_test.go | 39 ++++++++++++++++++++++++++++++++++++--- 3 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 csv_test.go diff --git a/csv.go b/csv.go index 072dcde..7cbaee7 100644 --- a/csv.go +++ b/csv.go @@ -9,6 +9,7 @@ import ( func CSVColumn(name string) func(r io.Reader, w io.Writer) error { return func(r io.Reader, w io.Writer) error { cr := csv.NewReader(r) + cr.FieldsPerRecord = -1 header, err := cr.Read() if err != nil { @@ -34,7 +35,7 @@ func CSVColumn(name string) func(r io.Reader, w io.Writer) error { return err } } - if len(rec) < colIdx { + if len(rec) <= colIdx { continue } @@ -46,4 +47,4 @@ func CSVColumn(name string) func(r io.Reader, w io.Writer) error { } } } -} \ No newline at end of file +} diff --git a/csv_test.go b/csv_test.go new file mode 100644 index 0000000..7bd15f8 --- /dev/null +++ b/csv_test.go @@ -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", + }) + }) +} diff --git a/fmt_test.go b/fmt_test.go index 0791423..9a12a4f 100644 --- a/fmt_test.go +++ b/fmt_test.go @@ -1,7 +1,40 @@ 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) { - t.Log("Hello") -} \ No newline at end of file + 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) +}