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
|
func TestGetWork(t *testing.T) {
//建立 basicWorkQueue 以及當假的 clock
q, clock := newTestBasicWorkQueue()
//queue加入 foo1 延遲時間 -1 分鐘
q.Enqueue(types.UID("foo1"), -1*time.Minute)
//queue加入 foo2 延遲時間 -1 分鐘
q.Enqueue(types.UID("foo2"), -1*time.Minute)
//queue加入 foo3 延遲時間 1 分鐘
q.Enqueue(types.UID("foo3"), 1*time.Minute)
//queue加入 foo4 延遲時間 - 分鐘
q.Enqueue(types.UID("foo4"), 1*time.Minute)
//預期取的可以從 queue 中拿到 "foo1" "foo2"
expected := []types.UID{types.UID("foo1"), types.UID("foo2")}
//比對預期得結果與實際的結果 , GetWork 從 queue 中拿資料,會取的延遲時間到的資料
//因為 foo1 foo2 延遲時間為 -1 分鐘,所以 getwork 可以拿到 foo1 foo2 的資料
compareResults(t, expected, q.GetWork())
//比對預期得結果與實際的結果 ,此時 foo1 foo2 已經從 queue 中 pop 出去了
//再去拿資料的時候由於其他資料還沒到延遲時間所以 get work 會是空的
compareResults(t, []types.UID{}, q.GetWork())
//將時間 mock 往後調整一個小時
clock.Step(time.Hour)
//預期取的可以從 queue 中拿到 "foo3" "foo4"
expected = []types.UID{types.UID("foo3"), types.UID("foo4")}
//此時 time 往後調整一個小時了
//比對預期得結果與實際的結果 , GetWork 從 queue 中拿資料,會取的延遲時間到的資料
//因為 foo3 foo4 延遲時間為 1 分鐘,所以 getwork 可以拿到 foo3 foo4 的資料
compareResults(t, expected, q.GetWork())
//比對預期得結果與實際的結果 ,此時 foo3 foo4 已經從 queue 中 pop 出去了
//再去拿資料的時候queue已經空了所以 get work 時會拿到空的資料
compareResults(t, []types.UID{}, q.GetWork())
}
//建立 queue 以及假的 clock (可以 mock 用)
func newTestBasicWorkQueue() (*basicWorkQueue, *clock.FakeClock) {
//建立假的 clock 可以 mock 用
fakeClock := clock.NewFakeClock(time.Now())
//建立 basicWorkQueue 物件設定 fake clock
wq := &basicWorkQueue{
clock: fakeClock,
queue: make(map[types.UID]time.Time),
}
return wq, fakeClock
}
//比對預期得結果與實際的結果
func compareResults(t *testing.T, expected, actual []types.UID) {
//建立一個 set
expectedSet := sets.NewString()
//將預期的答案放入 set
for _, u := range expected {
expectedSet.Insert(string(u))
}
//用來儲存實際上queue回傳資料用的set
actualSet := sets.NewString()
//將實際上queue回傳資料放入 set
for _, u := range actual {
actualSet.Insert(string(u))
}
//判斷 預期的答案 與實際的答案是否一致。
if !expectedSet.Equal(actualSet) {
t.Errorf("Expected %#v, got %#v", expectedSet.List(), actualSet.List())
}
}
|