2023-04-09 17:44:27 +03:00
|
|
|
package csv
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/csv"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/require"
|
2023-11-20 04:06:36 +03:00
|
|
|
|
2024-01-15 04:45:34 +03:00
|
|
|
"github.com/neilotoole/sq/testh/tu"
|
2023-04-09 17:44:27 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func Test_detectHeaderRow(t *testing.T) {
|
|
|
|
testCases := []struct {
|
|
|
|
fp string
|
|
|
|
comma rune // zero value uses comma
|
|
|
|
want bool
|
|
|
|
}{
|
|
|
|
{fp: "testdata/sakila-csv/actor.csv", want: true},
|
|
|
|
{fp: "testdata/sakila-csv-noheader/actor.csv", want: false},
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, tc := range testCases {
|
|
|
|
tc := tc
|
|
|
|
|
2024-01-15 04:45:34 +03:00
|
|
|
t.Run(tu.Name(i, tc.fp), func(t *testing.T) {
|
2023-04-09 17:44:27 +03:00
|
|
|
recs := readAllRecs(t, tc.comma, tc.fp)
|
|
|
|
|
|
|
|
gotHasHeader, err := detectHeaderRow(recs)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Equal(t, tc.want, gotHasHeader)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func readAllRecs(t *testing.T, comma rune, fp string) [][]string {
|
2024-01-27 16:43:17 +03:00
|
|
|
t.Helper()
|
2023-04-09 17:44:27 +03:00
|
|
|
b, err := os.ReadFile(fp)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
cr := csv.NewReader(&crFilterReader{r: bytes.NewReader(b)})
|
|
|
|
if comma != rune(0) {
|
|
|
|
cr.Comma = comma
|
|
|
|
}
|
|
|
|
|
|
|
|
recs, err := cr.ReadAll()
|
|
|
|
require.NoError(t, err)
|
|
|
|
return recs
|
|
|
|
}
|