Skip to content

Commit

Permalink
Use testify
Browse files Browse the repository at this point in the history
  • Loading branch information
suzaku committed Dec 8, 2020
1 parent 42e986d commit fbac31e
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 115 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/suzaku/shonenjump

go 1.12

require github.com/stretchr/testify v1.6.1
12 changes: 12 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
133 changes: 46 additions & 87 deletions jump/entry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package jump
import (
"bufio"
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
)

func TestEntryListSave(t *testing.T) {
Expand All @@ -22,53 +23,42 @@ func TestEntryListSave(t *testing.T) {
{filepath.Join(dir, "c"), 15},
}
for _, e := range rawEntries {
if err := os.MkdirAll(e.val, 0664); err != nil {
t.Fatal(err)
}
err := os.MkdirAll(e.val, 0664)
assert.Nil(t, err)
}
// Append a non-exist dir that should be ignored
rawEntries = append(rawEntries, &entry{val: "non-exist", score: 15})
entries := entryList(rawEntries)

fileName := filepath.Join(dir, "testEntries")

if err := entries.Save(fileName); err != nil {
log.Fatal(err)
}
err = entries.Save(fileName)
assert.Nil(t, err)

entriesFile, err := os.Open(fileName)
if err != nil {
t.Fatal(err)
}
assert.Nil(t, err)

scanner := bufio.NewScanner(entriesFile)
var results []string
for scanner.Scan() {
line := scanner.Text()
results = append(results, line)
}
if len(results) != len(entries)-1 {
t.Errorf("Incorrect number of entries saved: %q", results)
}
assert.Equal(t, len(entries)-1, len(results), "Incorrect number of entries saved")

for i, r := range results {
if r != entries[i].String() {
t.Errorf("Entry %d saved incorrectly: %q", i, results[i])
}
if err := os.Remove(entries[i].val); err != nil {
t.Fatal(err)
}
assert.Equal(t, entries[i].String(), r)
err := os.Remove(entries[i].val)
assert.Nil(t, err)
}

if err := entries.Save(fileName); err != nil {
log.Fatal(err)
}
err = entries.Save(fileName)
assert.Nil(t, err)

content, err := ioutil.ReadFile(fileName)
if err != nil {
t.Fatal(err)
}
if len(content) != 0 {
t.Errorf("Expected empty content, got: %v", string(content))
}
assert.Nil(t, err)

assert.Empty(t, content)
}

func TestEntryListSort(t *testing.T) {
Expand All @@ -81,9 +71,7 @@ func TestEntryListSort(t *testing.T) {
entries.Sort()
expected := []string{"a", "c", "b"}
for i, e := range entries {
if expected[i] != e.val {
t.Errorf("Item %d not in place, expected %s, got %s", i, expected[i], e.val)
}
assert.Equal(t, expected[i], e.val)
}
}

Expand All @@ -93,13 +81,11 @@ func TestEntryListUpdate(t *testing.T) {
&entry{"/path_a", 0},
}
entries = entries.Update("/path_a", 1)
if entries[0].score != 10 || entries[1].score != 1 {
t.Errorf("Invalid update: %v", entries)
}
assert.Equal(t, float64(10), entries[0].score)
assert.Equal(t, float64(1), entries[1].score)

entries = entries.Update("/path_c", 1)
if len(entries) != 3 {
t.Errorf("New entry not created: %d", len(entries))
}
assert.Len(t, entries, 3)
}

func TestEntryListAge(t *testing.T) {
Expand All @@ -111,84 +97,60 @@ func TestEntryListAge(t *testing.T) {
entries.Age()
expected := []float64{18.0, 9.0, 0}
for i, e := range entries {
if e.score != expected[i] {
t.Errorf("Score not updated correctly, expect %f, get %f", expected[i], e.score)
}
assert.Equal(t, expected[i], e.score)
}
}

func TestString(t *testing.T) {
e := &entry{"/etc/init", 10.1234}
if e.String() != "10.12\t/etc/init" {
t.Errorf("Wrong string representation: %s", e.String())
}
assert.Equal(t, "10.12\t/etc/init", e.String())
}

func TestUpdateEntryScore(t *testing.T) {
e := &entry{"/etc/init", 0}
e.updateScore(10)
if e.score != 10 {
t.Errorf("Entity score is wrong: %f", e.score)
}
assert.Equal(t, float64(10), e.score)

e.updateScore(10)
if e.score-14.14 < 0.001 {
t.Errorf("Entity score is wrong: %f", e.score)
}
assert.InDelta(t, 14.14, e.score, 0.01)
}

func TestLoadEntries(t *testing.T) {
t.Run("Should make sure the entries are sorted by score", func(t *testing.T) {
f, err := ioutil.TempFile("", "entries")
if err != nil {
t.Fatal(err)
}
assert.Nil(t, err)

content := []byte("20\t/a\n22\t/a/b\n12.5\t/c\n")
err = ioutil.WriteFile(f.Name(), content, 0666)
if err != nil {
t.Fatal(err)
}
assert.Nil(t, err)

store := NewStore(f.Name())
entries, err := store.ReadEntries()
if err != nil {
t.Fatal(err)
}
if len(entries) != 3 {
t.Errorf("Expect 3 entries, got: %v ", entries)
}
assert.Nil(t, err)

assert.Len(t, entries, 3)
paths := make([]string, len(entries))
for i, e := range entries {
paths[i] = e.val
}
assertItemsEqual(t, paths, []string{"/a/b", "/a", "/c"})
assert.Equal(t, []string{"/a/b", "/a", "/c"}, paths)
})
}

func TestPreprocessPath(t *testing.T) {
path, err := preprocessPath("/abc/")
if err != nil {
t.Error(err)
}
if path != "/abc" {
t.Errorf("Trailing slash is not removed in path: %s", path)
}
assert.Nil(t, err)
assert.Equal(t, "/abc", path, "Trailing slash is not removed in path")
path, err = preprocessPath("abc")
if err != nil {
t.Error(err)
}
assert.Nil(t, err)
pwd, err := os.Getwd()
if err != nil {
t.Error(err)
}
if path != filepath.Join(pwd, "abc") {
t.Errorf("Relative path not converted to absolute path: %s", path)
}
assert.Nil(t, err)
assert.Equal(t, filepath.Join(pwd, "abc"), path)
}

func TestClearNotExistDirs(t *testing.T) {
dir, err := ioutil.TempDir("", "test")
if err != nil {
t.Fatal(err)
}
assert.Nil(t, err)
cases := []struct {
basename string
create bool
Expand All @@ -204,9 +166,8 @@ func TestClearNotExistDirs(t *testing.T) {
for _, c := range cases {
e := &entry{val: filepath.Join(dir, c.basename)}
if c.create {
if err := os.MkdirAll(e.val, 0644); err != nil {
log.Fatal(err)
}
err := os.MkdirAll(e.val, 0644)
assert.Nil(t, err)
expected = append(expected, e.val)
}
entries = append(entries, e)
Expand All @@ -216,8 +177,6 @@ func TestClearNotExistDirs(t *testing.T) {
for _, r := range result {
output = append(output, r.val)
}
assertItemsEqual(t, output, expected)
if !changed {
t.Error("Empty dirs get deleted, but changed is false.")
}
assert.Equal(t, expected, output)
assert.True(t, changed, "Empty dirs get deleted, but changed is false.")
}
40 changes: 15 additions & 25 deletions jump/match_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package jump

import "testing"
import (
"testing"

"github.com/stretchr/testify/assert"
)

func BenchmarkGetCandidates(b *testing.B) {
orig := isValidPath
Expand All @@ -16,9 +20,7 @@ func BenchmarkGetCandidates(b *testing.B) {
for i := 0; i < b.N; i++ {
candidates = GetCandidates(entries, []string{"foo", "bar"}, MaxCompleteOptions)
}
if len(candidates) == 0 {
b.Fail()
}
assert.Empty(b, candidates)
}

func generateEntries() []*entry {
Expand Down Expand Up @@ -56,7 +58,7 @@ func TestGetCandidatesShouldRemoveDuplication(t *testing.T) {
entries := []*entry{{"path1", 10}}
result := GetCandidates(entries, []string{"foo"}, 4)
expected := []string{"path1", "path2"}
assertItemsEqual(t, result, expected)
assert.Equal(t, expected, result, "Incorrect candidates")
}

func TestGetCandidates(t *testing.T) {
Expand All @@ -82,7 +84,7 @@ func TestGetCandidates(t *testing.T) {
"/foo/bazar",
"/foo/bar/baz",
}
assertItemsEqual(t, result, expected)
assert.Equal(t, expected, result, "Incorrect candidates")
}

func TestAnywhere(t *testing.T) {
Expand All @@ -98,7 +100,7 @@ func TestAnywhere(t *testing.T) {
"/foo/bazar",
"/foo/gxxbazabc",
}
assertItemsEqual(t, result, expected)
assert.Equal(t, expected, result, "Incorrect candidates")
}

func TestExactName(t *testing.T) {
Expand All @@ -111,11 +113,11 @@ func TestExactName(t *testing.T) {
}
t.Run("Should returns empty result if the number of args is not exactly one", func(t *testing.T) {
result := matchExactName(entries, []string{"tidb", "baz"})
assertItemsEqual(t, result, []string{})
assert.Empty(t, result)
})
t.Run("Should only match last part of name", func(t *testing.T) {
result := matchExactName(entries, []string{"tidb"})
assertItemsEqual(t, result, []string{"/app/open/tidb"})
assert.Equal(t, []string{"/app/open/tidb"}, result)
})
}

Expand All @@ -131,7 +133,7 @@ func TestFuzzy(t *testing.T) {
"/foo/bar/baz",
"/foo/bazar",
}
assertItemsEqual(t, result, expected)
assert.Equal(t, expected, result)
}

func TestConsecutive(t *testing.T) {
Expand All @@ -148,18 +150,7 @@ func TestConsecutive(t *testing.T) {
"/foo/bazar",
"/foo/xxbaz",
}
assertItemsEqual(t, result, expected)
}

func assertItemsEqual(t *testing.T, result []string, expected []string) {
if len(result) != len(expected) {
t.Errorf("Expected %v, got %v", expected, result)
}
for i, r := range result {
if expected[i] != r {
t.Errorf("Got unexpected element in index %d: %v", i, r)
}
}
assert.Equal(t, expected, result)
}

func TestCalculateDiff(t *testing.T) {
Expand Down Expand Up @@ -195,9 +186,8 @@ func TestCalculateDiff(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := calculateDiff(tt.args.source, tt.args.target); got != tt.want {
t.Errorf("calculateDiff() = %v, want %v", got, tt.want)
}
got := calculateDiff(tt.args.source, tt.args.target)
assert.Equal(t, tt.want, got)
})
}
}
8 changes: 5 additions & 3 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestParseCompleteOption(t *testing.T) {
Expand All @@ -18,8 +20,8 @@ func TestParseCompleteOption(t *testing.T) {
}
for _, test := range tests {
needle, index, path := parseCompleteOption(test.input)
if !(test.needle == needle && test.index == index && test.path == path) {
t.Errorf("Unexpected parse result for %s: (%s, %d, %s)", test.input, needle, index, path)
}
assert.Equal(t, test.needle, needle)
assert.Equal(t, test.index, index)
assert.Equal(t, test.path, path)
}
}

0 comments on commit fbac31e

Please sign in to comment.