-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
280 lines (244 loc) · 6.23 KB
/
app.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
271
272
273
274
275
276
277
278
279
280
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"github.com/manifoldco/promptui"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "chester"
app.Usage = "Automate your snapshot testing!"
app.Commands = []cli.Command{
{
Name: "init",
Usage: "initialize chester",
Action: initchester,
},
{
Name: "create",
Usage: "create a test",
Action: create,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "silent",
Usage: "silent mode",
},
},
},
{
Name: "test",
Usage: "run the tests",
Action: test,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "silent",
Usage: "silent mode",
},
},
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
func initchester(c *cli.Context) error {
if _, err := os.Stat("__chester__"); err != nil {
if os.IsNotExist(err) {
// initialize.
os.Mkdir("__chester__", os.ModePerm)
os.Mkdir("__chester__/tests", os.ModePerm)
} else {
fmt.Println("chester is already initialized")
}
} else {
fmt.Println("chester is already initialized")
}
return nil
}
func create(c *cli.Context) error {
// We expect a bash input like
// echo "hello world"
// curl -X GET api/path
// python process_files.py
arg := c.Args().Get(0)
if arg == "" {
log.Fatal("Must specify a command or a directory containing command.sh")
}
// First check if it's a folder with command.sh inside it
// Else run it as a command itself.
var runDir = ""
var command = ""
if _, err := os.Stat(filepath.Join(arg, "command.sh")); !os.IsNotExist(err) {
// run from here!
runDir = arg
command = "./command.sh"
} else {
// They passed in a string command directly.
runDir = ""
command = arg
}
var commandResult = runCommandFromDir(command, runDir)
printWithBorder("Output", commandResult)
result := "Create"
if !c.Bool("silent") {
prompt := promptui.Select{
Label: "Create Test?",
Items: []string{"Create", "Exit"},
}
_, result2, err := prompt.Run()
result = result2
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return nil
}
}
if result == "Create" {
// Create the snapshot.
createTest(runDir, arg, commandResult)
} else {
return nil
}
return nil
}
func createTest(runDir, arg, commandResult string) {
fmt.Println("Creating a test with command: ", arg)
files, err := ioutil.ReadDir("./__chester__/tests")
if err != nil {
log.Fatal(err)
}
var id = 1
for _, f := range files {
i, err := strconv.Atoi(f.Name())
if err != nil {
continue
}
if i >= id {
id = i + 1
}
}
testDir := filepath.Join("__chester__/tests/", strconv.Itoa(id))
runTestDir := filepath.Join(testDir, "run_test")
os.MkdirAll(runTestDir, os.ModePerm)
if runDir == "" {
// arg should be written to file
file, err := os.Create(runTestDir + "/command.sh")
if err != nil {
log.Fatal("Cannot create file", err)
}
defer file.Close()
fmt.Fprintf(file, arg)
} else {
// arg is a folder, it's contents should be copied over
filesToCopy, _ := filepath.Glob(filepath.Join(arg, "/*"))
for _, f := range filesToCopy {
cpCmd := exec.Command("cp", "-r", f, filepath.Join(runTestDir, "/"))
output, err := cpCmd.CombinedOutput()
if err != nil {
fmt.Println(string(output))
log.Fatal(err)
}
}
}
file, err := os.Create(testDir + "/expected_output.txt")
if err != nil {
log.Fatal("Cannot create file", err)
}
defer file.Close()
fmt.Fprintf(file, commandResult)
fmt.Println("Test created! Run tests with `chester test`")
}
func runCommandFromDir(command, dir string) string {
// Runs the command and returns the output
cmd := exec.Command("sh", "-c", command)
cmd.Dir = dir
stdoutStderr, _ := cmd.CombinedOutput()
return string(stdoutStderr)
}
func runCommand(command string) string {
return runCommandFromDir(command, "")
}
func test(c *cli.Context) {
// Goes through all the tests and makes sure the outputs are the same.
files, err := ioutil.ReadDir("./__chester__/tests")
if err != nil {
log.Fatal(err)
}
allTestsPassing := true
for _, f := range files {
allTestsPassing = allTestsPassing && runTest(f.Name(), c.Bool("silent"))
}
if allTestsPassing {
os.Exit(0)
} else {
os.Exit(1)
}
}
func runTest(testID string, silentMode bool) bool {
testDir := "./__chester__/tests/" + testID
runTestDir := filepath.Join(testDir, "run_test")
command, err := ioutil.ReadFile(filepath.Join(runTestDir, "command.sh"))
if err != nil {
log.Fatal(err)
}
bytes, err := ioutil.ReadFile(testDir + "/expected_output.txt")
if err != nil {
log.Fatal(err)
}
expectedOutput := string(bytes)
var actualOutput = runCommandFromDir(string(command), runTestDir)
if actualOutput == expectedOutput {
fmt.Println("Test ", testID, ": passed")
return true
}
// The test failed.
fmt.Println("Test ", testID, ": failed")
actualOutputFile := testDir + "/actual_output.txt"
ioutil.WriteFile(actualOutputFile, []byte(actualOutput), os.ModePerm)
var gitDiff = runCommandFromDir("git -c color.ui=always diff --no-index expected_output.txt actual_output.txt", testDir)
os.Remove(actualOutputFile)
fmt.Println(gitDiff)
// If it's JSON, try to print the paths to help the developer reconcile it.
jsonMessage := jsonDiffMessage(expectedOutput, actualOutput)
if jsonMessage != "" {
fmt.Println(jsonMessage)
}
result := "Skip"
if !silentMode {
prompt := promptui.Select{
Label: "Options",
Items: []string{"Skip", "Update Expected Output", "Delete Test", "Exit"},
}
_, result2, err := prompt.Run()
result = result2
if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return false
}
}
if result == "Exit" {
os.Exit(1)
} else if result == "Skip" {
fmt.Println("Skipping")
} else if result == "Delete Test" {
os.RemoveAll(testDir)
} else if result == "Update Expected Output" {
ioutil.WriteFile(testDir+"/expected_output.txt", []byte(actualOutput), os.ModePerm)
}
return false
}
func printWithBorder(title, content string) {
var border = "========================================================="
title = " " + title + " "
var titleIdx = (len(border) - len(title)) / 2
var titleWithBorder = border[0:titleIdx] + title + border[titleIdx+len(title):]
fmt.Println(titleWithBorder)
fmt.Println(content)
fmt.Println(border)
}