dict: deal with unknown keys
This commit is contained in:
parent
baff9ee722
commit
fc67cf14ff
@ -1,11 +1,15 @@
|
|||||||
package dictionary
|
package dictionary
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
type Dictionary map[string]string
|
type Dictionary map[string]string
|
||||||
|
|
||||||
func (d Dictionary) Search(word string) string {
|
var ErrNotFound = errors.New("could not find the word you were looking for")
|
||||||
|
|
||||||
|
func (d Dictionary) Search(word string) (string, error) {
|
||||||
result, ok := d[word]
|
result, ok := d[word]
|
||||||
if !ok {
|
if !ok {
|
||||||
return ""
|
return "", ErrNotFound
|
||||||
}
|
}
|
||||||
return result
|
return result, nil
|
||||||
}
|
}
|
||||||
|
@ -3,7 +3,7 @@ package dictionary
|
|||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func assertStrings(t testing.TB, got, want string) {
|
func assertStrings(t testing.TB, got, want string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
if got != want {
|
if got != want {
|
||||||
t.Errorf("got %q want %q given %q", got, want, "test")
|
t.Errorf("got %q want %q given %q", got, want, "test")
|
||||||
@ -13,8 +13,20 @@ func assertStrings(t testing.TB, got, want string) {
|
|||||||
func TestSearch(t *testing.T) {
|
func TestSearch(t *testing.T) {
|
||||||
dictionary := Dictionary{"test": "this is just a test"}
|
dictionary := Dictionary{"test": "this is just a test"}
|
||||||
|
|
||||||
got := dictionary.Search("test")
|
t.Run("known word", func(t *testing.T) {
|
||||||
want := "this is just a test"
|
got, _ := dictionary.Search("test")
|
||||||
|
want := "this is just a test"
|
||||||
|
|
||||||
assertStrings(t, got, want)
|
assertStrings(t, got, want)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("unknown word", func(t *testing.T) {
|
||||||
|
_, err := dictionary.Search("undefined")
|
||||||
|
want := "could not find the word you were looking for"
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected to get an error")
|
||||||
|
}
|
||||||
|
|
||||||
|
assertStrings(t, err.Error(), want)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user