-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
main_test.go
279 lines (257 loc) · 6.72 KB
/
main_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
271
272
273
274
275
276
277
278
279
package main
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
gitHTTP "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/johnstarich/go/gopages/cmd"
"github.com/johnstarich/go/gopages/internal/flags"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMain(t *testing.T) {
t.Parallel()
cmd.SetupTestExiter(t)
assert.Panics(t, main)
}
func TestMainArgs(t *testing.T) {
t.Parallel()
cmd.SetupTestExiter(t)
tmp, err := os.MkdirTemp("", "")
require.NoError(t, err)
defer os.RemoveAll(tmp)
for _, tc := range []struct {
description string
runnerErr error
wdErr error
args []string
expectErr string
}{
{
description: "bad flag usage",
args: []string{"-not-a-flag"},
expectErr: "Attempted to exit with exit code 2",
},
{
description: "request usage",
args: []string{"-help"},
},
{
description: "getwd error",
wdErr: errors.New("some error"),
expectErr: "Failed to get current directory: some error",
},
{
description: "runner failed",
runnerErr: errors.New("some error"),
expectErr: "Attempted to exit with exit code 1",
},
} {
tc := tc // enable parallel sub-tests
t.Run(tc.description, func(t *testing.T) {
t.Parallel()
runner := func(string, flags.Args) error {
return tc.runnerErr
}
getWD := func() (string, error) {
return tmp, tc.wdErr
}
runTest := func() {
mainArgs(runner, getWD, tc.args...)
}
if tc.expectErr != "" {
assert.PanicsWithError(t, tc.expectErr, runTest)
return
}
assert.NotPanics(t, runTest)
})
}
}
func TestRun(t *testing.T) { //nolint:paralleltest // TODO: Remove chdir, use a io/fs.FS implementation to work around billy's limitations.
//nolint:paralleltest // TODO: Remove chdir, use a io/fs.FS implementation to work around billy's limitations.
for _, tc := range []testRunTestCase{
{
description: "happy path, no flags",
},
{
description: "happy path, gh-pages",
args: []string{"-gh-pages"},
skip: os.Getenv("CI") == "true" && runtime.GOOS == "windows", // Windows in CI can't handle temp files with working directory ones because they're on different drive letters.
},
} {
t.Run(tc.description, func(t *testing.T) {
testRun(t, tc)
})
}
}
type testRunTestCase struct {
description string
args []string
expectErr string
skip bool
}
func testRun(t *testing.T, tc testRunTestCase) {
if tc.skip {
t.Skip("Skipped by test case param")
}
// create dummy repo to enable cloning
ghPagesDir, err := os.MkdirTemp("", "")
require.NoError(t, err)
defer os.RemoveAll(ghPagesDir)
const defaultBranch = "refs/heads/main"
ghPagesRepo, err := git.PlainInitWithOptions(ghPagesDir, &git.PlainInitOptions{
InitOptions: git.InitOptions{
DefaultBranch: defaultBranch,
},
})
require.NoError(t, err)
workTree, err := ghPagesRepo.Worktree()
require.NoError(t, err)
_, err = workTree.Commit("Initial commit", &git.CommitOptions{
Author: commitAuthor(),
AllowEmptyCommits: true,
})
require.NoError(t, err)
require.NoError(t, workTree.Checkout(&git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(ghPagesBranch),
Create: true,
}))
require.NoError(t, workTree.Checkout(&git.CheckoutOptions{
Branch: defaultBranch,
}))
modulePath, err := os.MkdirTemp("", "")
require.NoError(t, err)
defer os.RemoveAll(modulePath)
wd, err := os.Getwd()
require.NoError(t, err)
require.NoError(t, os.Chdir(modulePath))
defer func() {
require.NoError(t, os.Chdir(wd))
}()
// prepare origin remote pointing to dummy repo
_, err = git.PlainClone(modulePath, false, &git.CloneOptions{
URL: ghPagesDir,
})
require.NoError(t, err)
writeFile := func(path, contents string) {
path = filepath.Join(modulePath, path)
err := os.MkdirAll(filepath.Dir(path), 0o700)
require.NoError(t, err)
err = os.WriteFile(path, []byte(contents), 0o600)
require.NoError(t, err)
}
writeFile("go.mod", `module thing`)
writeFile("main.go", `
package main
func main() {
println("Hello world")
}
`)
writeFile("lib/lib.go", `
package lib
// Hello says hi
func Hello() {
println("Hello world")
}
`)
args, _, err := flags.Parse(tc.args...)
require.NoError(t, err)
err = run(modulePath, args)
if tc.expectErr != "" {
assert.EqualError(t, err, tc.expectErr)
return
}
require.NoError(t, err)
var foundLib bool
var fileNames []string
if contains(tc.args, "-gh-pages") {
// fetch the new head commit and walk the files in the diff
require.NoError(t, workTree.Checkout(&git.CheckoutOptions{
Branch: plumbing.NewBranchReferenceName(ghPagesBranch),
}))
head, err := ghPagesRepo.Head()
require.NoError(t, err)
headCommit, err := ghPagesRepo.CommitObject(head.Hash())
require.NoError(t, err)
files, err := headCommit.Files()
require.NoError(t, err)
err = files.ForEach(func(f *object.File) error {
name := filepath.ToSlash(f.Name)
name = strings.TrimPrefix(name, "dist/")
if strings.HasPrefix(name, "lib") {
foundLib = true
} else {
fileNames = append(fileNames, name)
}
return nil
})
require.NoError(t, err)
} else {
err := filepath.Walk(modulePath, func(path string, info os.FileInfo, err error) error {
prefix := filepath.Join(modulePath, "dist")
prefix, absErr := filepath.Abs(prefix)
if absErr != nil {
return absErr
}
prefix += string(filepath.Separator)
name := strings.TrimPrefix(path, prefix)
if err == nil &&
!info.IsDir() &&
!filepath.IsAbs(name) {
if strings.HasPrefix(name, "lib") {
foundLib = true
} else {
fileNames = append(fileNames, filepath.ToSlash(name))
}
}
return nil
})
require.NoError(t, err)
}
require.NoError(t, err)
assert.True(t, foundLib)
assert.Equal(t, []string{
"404.html",
"index.html",
"pkg/index.html",
"pkg/thing/index.html",
"pkg/thing/lib/index.html",
"src/index.html",
"src/thing/index.html",
"src/thing/lib/index.html",
"src/thing/lib/lib.go.html",
"src/thing/main.go.html",
}, fileNames)
}
func contains(strs []string, s string) bool {
for _, str := range strs {
if str == s {
return true
}
}
return false
}
func TestAuth(t *testing.T) {
t.Parallel()
t.Run("no auth flags", func(t *testing.T) {
t.Parallel()
basicAuth, ok := getAuth(flags.Args{})
assert.Nil(t, basicAuth)
assert.False(t, ok)
})
t.Run("basic auth flags", func(t *testing.T) {
t.Parallel()
basicAuth, ok := getAuth(flags.Args{
GitHubPagesToken: "token",
GitHubPagesUser: "user",
})
assert.Equal(t, &gitHTTP.BasicAuth{Username: "user", Password: "token"}, basicAuth)
assert.True(t, ok)
})
}