Files
ultrashorty/internal/csv_test.go
T

103 lines
2.9 KiB
Go
Raw Normal View History

package internal
import (
"os"
"path/filepath"
"testing"
)
func writeCSV(t *testing.T, content string) string {
t.Helper()
p := filepath.Join(t.TempDir(), "redirects.csv")
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return p
}
func TestReadCsvRedirects(t *testing.T) {
t.Run("valid file", func(t *testing.T) {
p := writeCSV(t, "From,To,Status Code\n/a,https://example.com/a,301\n/b,https://example.com/b,302\n")
got, err := ReadCsvRedirects(p)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != 2 {
t.Fatalf("got %d redirects, want 2", len(got))
}
if got[0].From != "/a" || got[0].To != "https://example.com/a" || got[0].StatusCode != 301 {
t.Errorf("row 0 = %+v", got[0])
}
})
t.Run("headings in any order", func(t *testing.T) {
p := writeCSV(t, "Status Code,To,From\n301,https://example.com,/x\n")
got, err := ReadCsvRedirects(p)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got[0].From != "/x" || got[0].To != "https://example.com" || got[0].StatusCode != 301 {
t.Errorf("got %+v", got[0])
}
})
t.Run("header only yields no redirects", func(t *testing.T) {
got, err := ReadCsvRedirects(writeCSV(t, "From,To,Status Code\n"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(got) != 0 {
t.Fatalf("got %d redirects, want 0", len(got))
}
})
t.Run("missing heading is an error", func(t *testing.T) {
if _, err := ReadCsvRedirects(writeCSV(t, "From,To\n/a,https://example.com\n")); err == nil {
t.Fatal("want error for missing Status Code heading")
}
})
t.Run("non-numeric status is an error", func(t *testing.T) {
if _, err := ReadCsvRedirects(writeCSV(t, "From,To,Status Code\n/a,https://example.com,oops\n")); err == nil {
t.Fatal("want error for non-numeric status code")
}
})
t.Run("non-3xx status is an error", func(t *testing.T) {
for _, code := range []string{"0", "-1", "200", "404", "500", "1000"} {
_, err := ReadCsvRedirects(writeCSV(t, "From,To,Status Code\n/a,https://example.com,"+code+"\n"))
if err == nil {
t.Errorf("status %s: want error, got nil", code)
}
}
})
t.Run("ragged row is an error", func(t *testing.T) {
if _, err := ReadCsvRedirects(writeCSV(t, "From,To,Status Code\n/a,https://example.com\n")); err == nil {
t.Fatal("want error for a row with too few fields")
}
})
t.Run("missing file is an error", func(t *testing.T) {
if _, err := ReadCsvRedirects(filepath.Join(t.TempDir(), "nope.csv")); err == nil {
t.Fatal("want error for a file that does not exist")
}
})
}
func TestHeadingsIndexOf(t *testing.T) {
h := Headings{"From", "To", "Status Code"}
if got := h.IndexOf("To"); got != 1 {
t.Errorf("IndexOf(To) = %d, want 1", got)
}
if got := h.IndexOf("Status Code"); got != 2 {
t.Errorf("IndexOf(Status Code) = %d, want 2", got)
}
if got := h.IndexOf("Nope"); got != -1 {
t.Errorf("IndexOf(Nope) = %d, want -1", got)
}
}