forked from MediaMath/grim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrim_test.go
270 lines (214 loc) · 7.75 KB
/
grim_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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package grim
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Copyright 2015 MediaMath <http://www.mediamath.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
func TestTruncatedGrimServerID(t *testing.T) {
var buf bytes.Buffer
logger := log.New(&buf, "", log.Lshortfile)
tempDir, err := ioutil.TempDir("", "TestTruncatedGrimServerID")
if err != nil {
t.Errorf("|%v|", err)
}
defer os.RemoveAll(tempDir)
// GrimQueueName is set to be 20 chars long, which should get truncated
configJS := `{"GrimQueueName":"12345678901234567890","AWSRegion":"empty","AWSKey":"empty","AWSSecret":"empty"}`
ioutil.WriteFile(filepath.Join(tempDir, "config.json"), []byte(configJS), 0644)
g := &Instance{
configRoot: &tempDir,
queue: nil,
}
g.PrepareGrimQueue(logger)
message := fmt.Sprintf("%v", &buf)
if !strings.Contains(message, buildTruncatedMessage("GrimQueueName")) {
t.Errorf("Failed to log truncation of grimServerID")
}
}
func TestTimeOutConfig(t *testing.T) {
if testing.Short() {
t.Skipf("Skipping prepare test in short mode.")
}
tempDir, err := ioutil.TempDir("", "TestTimeOut")
if err != nil {
t.Errorf("|%v|", err)
}
defer os.RemoveAll(tempDir)
configJS := `{"Timeout":4,"AWSRegion":"empty","AWSKey":"empty","AWSSecret":"empty"}`
ioutil.WriteFile(filepath.Join(tempDir, "config.json"), []byte(configJS), 0644)
config, err := getEffectiveGlobalConfig(tempDir)
if err != nil {
t.Errorf("|%v|", err)
}
config.resultRoot = tempDir
if config.timeout == int(defaultTimeout.Seconds()) {
t.Errorf("Failed to use non default timeout time")
}
err = doWaitAction(config, testOwner, testRepo, 2)
if err != nil {
t.Errorf("Failed to not timeout")
}
}
func doWaitAction(config *effectiveConfig, owner, repo string, wait int) error {
return onHookBuild("not-used", config, hookEvent{Owner: owner, Repo: repo}, nil, func(r string, resultPath string, c *effectiveConfig, h hookEvent, s string) (*executeResult, string, error) {
time.Sleep(time.Duration(wait) * time.Second)
return &executeResult{}, "", nil
})
}
func TestBuildRef(t *testing.T) {
if testing.Short() {
t.Skipf("Skipping prepare test in short mode.")
}
owner := "MediaMath"
repo := "grim"
ref := "test" //special grim branch
clonePath := "go/src/github.com/MediaMath/grim"
temp, _ := ioutil.TempDir("", "TestBuildRef")
configRoot := filepath.Join(temp, "config")
os.MkdirAll(filepath.Join(configRoot, owner, repo), 0700)
grimConfigTemplate := `{
"ResultRoot": "%v",
"WorkspaceRoot": "%v",
"AWSRegion": "bogus",
"AWSKey": "bogus",
"AWSSecret": "bogus"
}`
grimJs := fmt.Sprintf(grimConfigTemplate, filepath.Join(temp, "results"), filepath.Join(temp, "ws"))
ioutil.WriteFile(filepath.Join(configRoot, "config.json"), []byte(grimJs), 0644)
localConfigTemplate := `{
"PathToCloneIn": "%v"
}`
localJs := fmt.Sprintf(localConfigTemplate, clonePath)
ioutil.WriteFile(filepath.Join(configRoot, owner, repo, "config.json"), []byte(localJs), 0644)
var g Instance
g.SetConfigRoot(configRoot)
logfile, err := os.OpenFile(filepath.Join(temp, "log.txt"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
t.Fatalf("error opening file: %v", err)
}
logger := log.New(logfile, "", log.Ldate|log.Ltime)
buildErr := g.BuildRef(owner, repo, ref, logger)
logfile.Close()
if buildErr != nil {
t.Errorf("%v: %v", temp, buildErr)
}
if !t.Failed() {
os.RemoveAll(temp)
}
}
var testOwner = "MediaMath"
var testRepo = "grim"
func TestOnActionFailure(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "results-dir-failure")
defer os.RemoveAll(tempDir)
doNothingAction(tempDir, testOwner, testRepo, 123, nil)
if _, err := resultsDirectoryExists(tempDir, testOwner, testRepo); err != nil {
t.Errorf("|%v|", err)
}
}
func TestOnActionError(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "results-dir-error")
defer os.RemoveAll(tempDir)
doNothingAction(tempDir, testOwner, testRepo, 0, fmt.Errorf("Bad Bad thing happened"))
if _, err := resultsDirectoryExists(tempDir, testOwner, testRepo); err != nil {
t.Errorf("|%v|", err)
}
}
func TestResultsDirectoryCreatedInOnHook(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "results-dir-success")
defer os.RemoveAll(tempDir)
doNothingAction(tempDir, testOwner, testRepo, 0, nil)
if _, err := resultsDirectoryExists(tempDir, testOwner, testRepo); err != nil {
t.Errorf("|%v|", err)
}
}
func TestHookGetsLogged(t *testing.T) {
tempDir, _ := ioutil.TempDir("", "results-dir-success")
defer os.RemoveAll(tempDir)
hook := hookEvent{Owner: testOwner, Repo: testRepo, StatusRef: "fooooooooooooooooooo"}
err := onHookBuild("not-used", &effectiveConfig{resultRoot: tempDir}, hook, nil, func(r string, resultPath string, c *effectiveConfig, h hookEvent, s string) (*executeResult, string, error) {
return &executeResult{ExitCode: 0}, "", nil
})
if err != nil {
t.Fatalf("%v", err)
}
results, _ := resultsDirectoryExists(tempDir, testOwner, testRepo)
hookFile := filepath.Join(results, "hook.json")
if _, err := os.Stat(hookFile); os.IsNotExist(err) {
t.Errorf("%s was not created.", hookFile)
}
jsonHookFile, readerr := ioutil.ReadFile(hookFile)
if readerr != nil {
t.Errorf("Error reading file %v", readerr)
}
var parsed hookEvent
parseErr := json.Unmarshal(jsonHookFile, &parsed)
if parseErr != nil {
t.Errorf("Error parsing: %v", parseErr)
}
if hook.Owner != parsed.Owner || hook.Repo != parsed.Repo || hook.StatusRef != parsed.StatusRef {
t.Errorf("Did not match:\n%v\n%v", hook, parsed)
}
}
func TestShouldSkip(t *testing.T) {
var skipTests = []struct {
in *hookEvent
retn bool // True for nil, False for not nil
}{
{&hookEvent{Deleted: true}, false},
{&hookEvent{Deleted: true, EventName: "push"}, false},
{&hookEvent{Deleted: true, EventName: "pull_request"}, false},
{&hookEvent{Deleted: true, EventName: "pull_request", Action: "reopened"}, false},
{&hookEvent{EventName: "push"}, true},
{&hookEvent{EventName: "push", Action: "opened"}, true},
{&hookEvent{EventName: "push", Action: "doesn't matter"}, true},
{&hookEvent{EventName: "pull_request", Action: "opened"}, true},
{&hookEvent{EventName: "pull_request", Action: "reopened"}, true},
{&hookEvent{EventName: "pull_request", Action: "synchronize"}, true},
{&hookEvent{EventName: "pull_request", Action: "matters"}, false},
{&hookEvent{EventName: "issue", Action: "opened"}, false},
}
for _, sT := range skipTests {
message := shouldSkip(sT.in)
if XOR(message == nil, sT.retn) {
t.Errorf("Failed test for hook with params<Deleted:%t,EventName:%v,Action:%v> with message:%d", sT.in.Deleted, sT.in.EventName, sT.in.Action, message)
}
}
}
func XOR(a, b bool) bool {
return a != b
}
func doNothingAction(tempDir, owner, repo string, exitCode int, returnedErr error) error {
return onHookBuild("not-used", &effectiveConfig{resultRoot: tempDir}, hookEvent{Owner: owner, Repo: repo}, nil, func(r string, resultPath string, c *effectiveConfig, h hookEvent, s string) (*executeResult, string, error) {
return &executeResult{ExitCode: exitCode}, "", returnedErr
})
}
func resultsDirectoryExists(tempDir, owner, repo string) (string, error) {
files, err := ioutil.ReadDir(tempDir)
if err != nil {
return "", err
}
var fileNames []string
for _, stat := range files {
fileNames = append(fileNames, stat.Name())
}
repoResults := filepath.Join(tempDir, owner, repo)
if _, err := os.Stat(repoResults); os.IsNotExist(err) {
return "", fmt.Errorf("%s was not created: %s", repoResults, fileNames)
}
baseFiles, err := ioutil.ReadDir(repoResults)
if len(baseFiles) != 1 {
return "", fmt.Errorf("Did not create base name in repo results")
}
return filepath.Join(repoResults, baseFiles[0].Name()), nil
}