go-by-test/dictionary/dictionary_test.go

109 lines
2.2 KiB
Go
Raw Normal View History

2024-09-11 11:48:59 +00:00
package dictionary
2024-09-17 08:10:07 +00:00
import (
"testing"
)
2024-09-11 11:48:59 +00:00
2024-09-17 07:58:41 +00:00
func assertStrings(t testing.TB, got, want, given string) {
2024-09-17 07:55:36 +00:00
t.Helper()
2024-09-11 12:07:00 +00:00
if got != want {
2024-09-17 07:58:41 +00:00
t.Errorf("got %q want %q given %q", got, want, given)
}
}
func assertError(t testing.TB, got, want error) {
t.Helper()
if got != want {
t.Errorf("got %q want %q", got, want)
2024-09-11 12:07:00 +00:00
}
}
2024-09-11 11:48:59 +00:00
func TestSearch(t *testing.T) {
2024-09-11 13:22:42 +00:00
dictionary := Dictionary{"test": "this is just a test"}
2024-09-11 11:48:59 +00:00
2024-09-17 07:55:36 +00:00
t.Run("known word", func(t *testing.T) {
got, _ := dictionary.Search("test")
want := "this is just a test"
2024-09-11 11:48:59 +00:00
2024-09-17 07:58:41 +00:00
assertStrings(t, got, want, "test")
2024-09-17 07:55:36 +00:00
})
t.Run("unknown word", func(t *testing.T) {
_, err := dictionary.Search("undefined")
if err == nil {
t.Fatal("expected to get an error")
}
2024-09-17 07:58:41 +00:00
assertError(t, err, ErrNotFound)
2024-09-17 07:55:36 +00:00
})
2024-09-11 11:48:59 +00:00
}
2024-09-17 08:10:07 +00:00
func assertDefinition(t testing.TB, dict Dictionary, word, def string) {
t.Helper()
got, err := dict.Search(word)
if err != nil {
t.Fatal("Should find added word:", err)
}
assertStrings(t, got, def, word)
}
func TestAdd(t *testing.T) {
2024-09-17 08:19:25 +00:00
t.Run("new word", func(t *testing.T) {
dict := Dictionary{}
2024-09-17 08:10:07 +00:00
2024-09-17 08:19:25 +00:00
word := "test"
def := "this is just a test"
2024-09-17 08:10:07 +00:00
2024-09-17 08:19:25 +00:00
dict.Add(word, def)
assertDefinition(t, dict, word, def)
})
t.Run("existing word", func(t *testing.T) {
word := "test"
def := "this is just a test"
dict := Dictionary{word: def}
err := dict.Add(word, def)
assertError(t, err, ErrWordExists)
assertDefinition(t, dict, word, def)
})
2024-09-17 08:10:07 +00:00
}
2024-09-17 09:31:00 +00:00
func TestUpdate(t *testing.T) {
t.Run("update an existing word", func(t *testing.T) {
word := "test"
def := "this is just a test"
updated := "updated definition"
dict := Dictionary{word: def}
dict.Update(word, updated)
assertDefinition(t, dict, word, updated)
})
t.Run("update an non-existing word", func(t *testing.T) {
word := "test"
updated := "updated definition"
dict := Dictionary{}
err := dict.Update(word, updated)
assertError(t, err, ErrWordDoesNotExist)
})
}
2024-09-17 09:35:22 +00:00
func TestDelete(t *testing.T) {
t.Run("delete a word", func(t *testing.T) {
word := "test"
def := "this is just a test"
dict := Dictionary{word: def}
dict.Delete(word)
_, err := dict.Search(word)
if err == nil {
t.Fatal("expected to get an error")
}
assertError(t, err, ErrNotFound)
})
}