go-by-test/dictionary/dictionary_test.go
2024-09-17 11:35:22 +02:00

109 lines
2.2 KiB
Go

package dictionary
import (
"testing"
)
func assertStrings(t testing.TB, got, want, given string) {
t.Helper()
if got != want {
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)
}
}
func TestSearch(t *testing.T) {
dictionary := Dictionary{"test": "this is just a test"}
t.Run("known word", func(t *testing.T) {
got, _ := dictionary.Search("test")
want := "this is just a test"
assertStrings(t, got, want, "test")
})
t.Run("unknown word", func(t *testing.T) {
_, err := dictionary.Search("undefined")
if err == nil {
t.Fatal("expected to get an error")
}
assertError(t, err, ErrNotFound)
})
}
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) {
t.Run("new word", func(t *testing.T) {
dict := Dictionary{}
word := "test"
def := "this is just a test"
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)
})
}
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)
})
}
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)
})
}