Adding CSV parser and tests
This commit is contained in:
parent
db6302fe52
commit
e718dc4062
36
internal/csvparser/parser.go
Normal file
36
internal/csvparser/parser.go
Normal file
|
@ -0,0 +1,36 @@
|
|||
package csvparser
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
// CsvLine holds a single line from the source CSV file
|
||||
type CsvLine struct {
|
||||
Code string
|
||||
Name string
|
||||
}
|
||||
|
||||
// ParseFile parses a given CSV file and returns a slice of CsvLine
|
||||
func ParseFile(file string) ([]CsvLine, error) {
|
||||
csvfile, err := os.Open(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
r := csv.NewReader(csvfile)
|
||||
var lines []CsvLine
|
||||
|
||||
for {
|
||||
record, err := r.Read()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lines = append(lines, CsvLine{Code: record[0], Name: record[1]})
|
||||
}
|
||||
return lines, nil
|
||||
}
|
45
internal/csvparser/parser_test.go
Normal file
45
internal/csvparser/parser_test.go
Normal file
|
@ -0,0 +1,45 @@
|
|||
package csvparser
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestCsvParser tests the correct function of the CSV file parser
|
||||
func TestCsvParser(t *testing.T) {
|
||||
check := []CsvLine{
|
||||
{Code: "Foo", Name: "bar"},
|
||||
{Code: "Bla", Name: "blub"},
|
||||
{Code: "Nom", Name: "LoL"},
|
||||
{Code: "123", Name: "256"},
|
||||
{Code: "Rawr", Name: "Bla"},
|
||||
{Code: "Lorem ipsum", Name: "dolor \"sit amet"},
|
||||
{Code: "Smile", Name: "😇"},
|
||||
{Code: "empty", Name: ""},
|
||||
}
|
||||
parsed, err := ParseFile(filepath.Join("..", "..", "test", "data", "csvparser.csv"))
|
||||
if err != nil {
|
||||
t.Fatalf("Got error: %+v", err)
|
||||
}
|
||||
if len(parsed) != len(check) {
|
||||
t.Fatalf("Slice-length mismatch, got %d, expected %d", len(parsed), len(check))
|
||||
}
|
||||
for i, item := range check {
|
||||
if item != parsed[i] {
|
||||
t.Errorf("Got wrong CSV line, got %s, expected %s", parsed[i], item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCsvParserFileError(t *testing.T) {
|
||||
_, err := ParseFile("nonexisting")
|
||||
if err == nil {
|
||||
t.Fatalf("Got no error")
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("Got error %+v, expected %+v", err, os.ErrNotExist)
|
||||
}
|
||||
|
||||
}
|
11
test/data/csvparser.csv
Normal file
11
test/data/csvparser.csv
Normal file
|
@ -0,0 +1,11 @@
|
|||
Foo,bar
|
||||
Bla,blub
|
||||
|
||||
Nom,LoL
|
||||
123,256
|
||||
"Rawr",Bla
|
||||
"Lorem ipsum","dolor ""sit amet"
|
||||
|
||||
|
||||
Smile,😇
|
||||
empty,
|
|
Loading…
Reference in a new issue