From c292a2f4b4fe8563883871456e19028ff9df0f26 Mon Sep 17 00:00:00 2001 From: Masashi SHIBATA Date: Tue, 10 Oct 2017 23:58:16 +0900 Subject: [PATCH] Fix history and add tests --- history.go | 5 +++- history_test.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 history_test.go diff --git a/history.go b/history.go index d183713..9b861be 100644 --- a/history.go +++ b/history.go @@ -14,7 +14,10 @@ func (h *History) Add(input string) { } func (h *History) Clear() { - copy(h.tmp, h.histories) + h.tmp = make([]string, len(h.histories)) + for i := range h.histories { + h.tmp[i] = h.histories[i] + } h.tmp = append(h.tmp, "") h.selected = len(h.tmp) - 1 } diff --git a/history_test.go b/history_test.go new file mode 100644 index 0000000..9201a13 --- /dev/null +++ b/history_test.go @@ -0,0 +1,62 @@ +package prompt + +import ( + "reflect" + "testing" +) + +func TestClear(t *testing.T) { + h := NewHistory() + h.Add("foo") + h.Clear() + expected := &History{ + histories: []string{"foo"}, + tmp: []string{"foo", ""}, + selected: 1, + } + if !reflect.DeepEqual(expected, h) { + t.Errorf("Should be %#v, but got %#v", expected, h) + } +} + +func TestAdd(t *testing.T) { + h := NewHistory() + h.Add("echo 1") + expected := &History{ + histories: []string{"echo 1"}, + tmp: []string{"echo 1", ""}, + selected: 1, + } + if !reflect.DeepEqual(h, expected) { + t.Errorf("Should be %v, but got %v", expected, h) + } +} + +func TestOlder(t *testing.T) { + h := NewHistory() + h.Add("echo 1") + + // Prepare buffer + buf := NewBuffer() + buf.InsertText("echo 2", false, true) + + // [1 time] Call Older function + buf1, changed := h.Older(buf) + if !changed { + t.Error("Should be changed history but not changed.") + } + if buf1.Text() != "echo 1" { + t.Errorf("Should be %#v, but got %#v", "echo 1", buf1.Text()) + } + + // [2 times] Call Older function + buf = NewBuffer() + buf.InsertText("echo 1", false, true) + buf2, changed := h.Older(buf) + if changed { + t.Error("Should be not changed history but changed.") + } + if !reflect.DeepEqual("echo 1", buf2.Text()) { + t.Errorf("Should be %#v, but got %#v", "echo 1", buf2.Text()) + } +}