-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_test.go
109 lines (95 loc) · 2.14 KB
/
stack_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package gods
import "testing"
func checkStack[T comparable](st *Stack[T], ch []T) bool {
if len(*st) != len(ch) {
return false
}
for i := range *st {
if (*st)[i] != ch[i] {
return false
}
}
return true
}
func TestStack(t *testing.T) {
stack := NewStack[int]()
check := []int{}
t.Run("new stack", func(t *testing.T) {
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("push 1", func(t *testing.T) {
check = []int{1}
stack.Push(1)
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("peek 1", func(t *testing.T) {
v, err := stack.Peek()
if err != nil {
t.Fatalf("unexpected error %v", err)
}
if v != 1 {
t.Fatalf("got %d expected 1", v)
}
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("push 2", func(t *testing.T) {
check = []int{1, 2}
stack.Push(2)
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("pop 2", func(t *testing.T) {
check = []int{1}
val, err := stack.Pop()
if err != nil {
t.Fatalf("got unexpected error %v", err)
}
if val != 2 {
t.Fatalf("pop returned %d, expected 2", val)
}
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
check = []int{}
t.Run("pop 1", func(t *testing.T) {
val, err := stack.Pop()
if err != nil {
t.Fatalf("got unexpected error %v", err)
}
if val != 1 {
t.Fatalf("pop returned %d, expected 1", val)
}
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("peek empty", func(t *testing.T) {
_, err := stack.Peek()
if err == nil {
t.Fatal("did not get expected error")
}
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
t.Run("pop empty", func(t *testing.T) {
val, err := stack.Pop()
if err == nil {
t.Fatal("expected error from empty stack")
}
if val != 0 {
t.Fatal("empty stack pop should have returned zero value")
}
if !checkStack(stack, check) {
t.Fatalf("got %#v, expected %#v", stack, check)
}
})
}