master
  1package main
  2
  3import (
  4	"testing"
  5)
  6
  7// https://github.com/quii/learn-go-with-tests/blob/master/maps.md
  8func TestSearch(t *testing.T) {
  9	dictionary := Dictionary{"test": "this is just a test"}
 10
 11	t.Run("known word", func(t *testing.T) {
 12		got, _ := dictionary.Search("test")
 13		want := "this is just a test"
 14
 15		assertStrings(t, got, want)
 16	})
 17
 18	t.Run("unknown word", func(t *testing.T) {
 19		_, got := dictionary.Search("unknown")
 20
 21		assertError(t, got, ErrorNotFound)
 22	})
 23}
 24
 25func TestAdd(t *testing.T) {
 26	t.Run("new word", func(t *testing.T) {
 27		dictionary := Dictionary{}
 28		key := "test"
 29		value := "this is just a test"
 30		err := dictionary.Add(key, value)
 31
 32		assertNil(t, err)
 33		assertDefinition(t, dictionary, key, value)
 34	})
 35
 36	t.Run("existing word", func(t *testing.T) {
 37		key := "test"
 38		value := "this is just a test"
 39		dictionary := Dictionary{key: value}
 40		err := dictionary.Add(key, "new test")
 41
 42		assertError(t, err, ErrorWordExists)
 43		assertDefinition(t, dictionary, key, value)
 44	})
 45}
 46
 47func TestUpdate(t *testing.T) {
 48	t.Run("existing word", func(t *testing.T) {
 49		word := "test"
 50		definition := "this is just a test"
 51
 52		dictionary := Dictionary{word: definition}
 53		newDefinition := "new definition"
 54		err := dictionary.Update(word, newDefinition)
 55
 56		assertNil(t, err)
 57		assertDefinition(t, dictionary, word, newDefinition)
 58	})
 59
 60	t.Run("new word", func(t *testing.T) {
 61		word := "test"
 62		definition := "this is just a test"
 63
 64		dictionary := Dictionary{}
 65		err := dictionary.Update(word, definition)
 66
 67		assertError(t, err, ErrorWordDoesNotExist)
 68	})
 69}
 70
 71func TestDelete(t *testing.T) {
 72	word := "test"
 73	dictionary := Dictionary{word: "test definition"}
 74	dictionary.Delete(word)
 75
 76	_, err := dictionary.Search(word)
 77
 78	if err != ErrorNotFound {
 79		t.Errorf("Expected %q to be deleted", word)
 80	}
 81}
 82
 83func assertStrings(t *testing.T, got, want string) {
 84	t.Helper()
 85
 86	if got != want {
 87		t.Errorf("got %q want %q", got, want)
 88	}
 89}
 90
 91func assertDefinition(t *testing.T, dictionary Dictionary, key, expected string) {
 92	t.Helper()
 93
 94	actual, err := dictionary.Search("test")
 95	if err != nil {
 96		t.Fatal("should find added key:", err)
 97	}
 98
 99	if expected != actual {
100		t.Errorf("actual %q want %q", actual, expected)
101	}
102}
103
104func assertNil(t *testing.T, actual error) {
105	if actual != nil {
106		t.Errorf("expected nil got %q", actual)
107	}
108}