Skip to content

Commit

Permalink
add parse package to parse csv files
Browse files Browse the repository at this point in the history
  • Loading branch information
danielkvist committed Jul 22, 2019
1 parent 96d8cb5 commit 3f601c3
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 0 deletions.
42 changes: 42 additions & 0 deletions parser/parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package parser

import (
"bufio"
"encoding/csv"
"io"
"os"
)

type Site struct {
Name string
URL string
}

func Parse(file string) ([]*Site, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}

r := csv.NewReader(bufio.NewReader(f))
return parse(r)
}

func parse(r *csv.Reader) ([]*Site, error) {
var sites []*Site

for {
line, err := r.Read()
if err == io.EOF {
break
}

if err != nil {
return nil, err
}

sites = append(sites, &Site{Name: line[0], URL: line[1]})
}

return sites, nil
}
73 changes: 73 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package parser

import (
"encoding/csv"
"strings"
"testing"
)

func TestParse(t *testing.T) {
tt := []struct {
name string
input string
expectedResult []*Site
}{
{
name: "one line",
input: "500px,https://500px.com/",
expectedResult: []*Site{
{
Name: "500px",
URL: "https://500px.com/",
},
},
},
{
name: "multiple lines",
input: "500px,https://500px.com/\nGoogle,https://google.com\nGitHub,https://github.com",
expectedResult: []*Site{
{
Name: "500px",
URL: "https://500px.com/",
},
{
Name: "Google",
URL: "https://google.com",
},
{
Name: "GitHub",
URL: "https://github.com",
},
},
},
{
name: "empty",
input: "",
expectedResult: []*Site{},
},
}

for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
r := csv.NewReader(strings.NewReader(tc.input))
sites, err := parse(r)
if err != nil {
t.Fatalf("while parsing csv input: %v", err)
}

if len(sites) != len(tc.expectedResult) {
t.Fatalf("expected len of parsed sites to be %v. got=%v", len(tc.expectedResult), len(sites))
}

for i, es := range tc.expectedResult {
if sites[i].Name != es.Name {
t.Fatalf("expected a parsed site called %q. got a site called %q", es.Name, sites[i].Name)
}

if sites[i].URL != es.URL {
t.Fatalf("expected a parsed site with URL %q. got a site with URL %q", es.URL, sites[i].URL)
}
}
})
}
}

0 comments on commit 3f601c3

Please sign in to comment.