forked from keybase/client
/
test_common.go
425 lines (355 loc) · 9.36 KB
/
test_common.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
// +build !production
package libkb
import (
"crypto/rand"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"sync"
"testing"
"golang.org/x/net/context"
"github.com/keybase/client/go/gregor"
"github.com/keybase/client/go/logger"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
// TestConfig tracks libkb config during a test
type TestConfig struct {
configFileName string
}
func (c *TestConfig) GetConfigFileName() string { return c.configFileName }
func (c *TestConfig) InitTest(t *testing.T, initConfig string) {
G.Log = logger.NewTestLogger(t)
G.Init()
var f *os.File
var err error
if f, err = ioutil.TempFile(os.TempDir(), "testconfig"); err != nil {
t.Fatalf("couldn't create temp file: %s", err)
}
c.configFileName = f.Name()
if _, err = f.WriteString(initConfig); err != nil {
t.Fatalf("couldn't write config file: %s", err)
}
f.Close()
// XXX: The global G prevents us from running tests in parallel
G.Env.Test.ConfigFilename = c.configFileName
if err = G.ConfigureConfig(); err != nil {
t.Fatalf("couldn't configure the config: %s", err)
}
}
func (c *TestConfig) CleanTest() {
if c.configFileName != "" {
os.Remove(c.configFileName)
}
}
// TestOutput is a mock interface for capturing and testing output
type TestOutput struct {
expected string
t *testing.T
called *bool
}
func NewTestOutput(e string, t *testing.T, c *bool) TestOutput {
return TestOutput{e, t, c}
}
func (to TestOutput) Write(p []byte) (n int, err error) {
output := string(p)
if to.expected != output {
to.t.Errorf("Expected output %s, got %s", to.expected, output)
}
*to.called = true
return len(p), nil
}
type TestContext struct {
G *GlobalContext
PrevGlobal *GlobalContext
Tp TestParameters
// TODO: Rename this to TB.
T testing.TB
}
func (tc *TestContext) Cleanup() {
tc.G.Log.Debug("global context shutdown:")
tc.G.Shutdown()
if len(tc.Tp.Home) > 0 {
tc.G.Log.Debug("cleaning up %s", tc.Tp.Home)
os.RemoveAll(tc.Tp.Home)
tc.G.Log.Debug("clearing stored secrets:")
tc.ClearAllStoredSecrets()
}
tc.G.Log.Debug("cleanup complete")
}
func (tc TestContext) MoveGpgKeyringTo(dst TestContext) error {
mv := func(f string) (err error) {
return os.Rename(path.Join(tc.Tp.GPGHome, f), filepath.Join(dst.Tp.GPGHome, f))
}
if err := mv("secring.gpg"); err != nil {
return err
}
if err := mv("pubring.gpg"); err != nil {
return err
}
return nil
}
func (tc *TestContext) GenerateGPGKeyring(ids ...string) error {
tc.T.Logf("generating gpg keyring in %s", tc.Tp.GPGHome)
fsk, err := os.Create(path.Join(tc.Tp.GPGHome, "secring.gpg"))
if err != nil {
return err
}
defer fsk.Close()
fpk, err := os.Create(path.Join(tc.Tp.GPGHome, "pubring.gpg"))
if err != nil {
return err
}
defer fpk.Close()
for _, id := range ids {
bundle, err := tc.MakePGPKey(id)
if err != nil {
return err
}
err = bundle.Entity.SerializePrivate(fsk, nil)
if err != nil {
return err
}
err = bundle.Entity.Serialize(fpk)
if err != nil {
return err
}
}
return nil
}
func (tc *TestContext) MakePGPKey(id string) (*PGPKeyBundle, error) {
arg := PGPGenArg{
PrimaryBits: 1024,
SubkeyBits: 1024,
PGPUids: []string{id},
}
arg.Init()
arg.CreatePGPIDs()
return GeneratePGPKeyBundle(tc.G, arg, tc.G.UI.GetLogUI())
}
// ResetLoginStateForTest simulates a shutdown and restart (for client
// state). Used by tests that need to clear out cached login state
// without logging out.
func (tc *TestContext) ResetLoginState() {
tc.G.createLoginState()
}
func (tc TestContext) ClearAllStoredSecrets() error {
usernames, err := tc.G.GetUsersWithStoredSecrets()
if err != nil {
return err
}
for _, username := range usernames {
nu := NewNormalizedUsername(username)
err = ClearStoredSecret(tc.G, nu)
if err != nil {
return err
}
}
return nil
}
var setupTestMu sync.Mutex
func setupTestContext(tb testing.TB, name string, tcPrev *TestContext) (tc TestContext, err error) {
setupTestMu.Lock()
defer setupTestMu.Unlock()
g := NewGlobalContext()
// In debugging mode, dump all log, don't use the test logger.
// We only use the environment variable to discover debug mode
if val, _ := getEnvBool("KEYBASE_DEBUG"); !val {
g.Log = logger.NewTestLogger(tb)
}
buf := make([]byte, 5)
if _, err = rand.Read(buf); err != nil {
return
}
// Uniquify name, since multiple tests may use the same name.
name = fmt.Sprintf("%s_%s", name, hex.EncodeToString(buf))
g.Init()
g.Log.Debug("SetupTest %s", name)
// Set up our testing parameters. We might add others later on
if tcPrev != nil {
tc.Tp = tcPrev.Tp
} else if tc.Tp.Home, err = ioutil.TempDir(os.TempDir(), name); err != nil {
return
}
g.Log.Debug("SetupTest home directory: %s", tc.Tp.Home)
// might as well be the same directory...
tc.Tp.GPGHome = tc.Tp.Home
tc.Tp.GPGOptions = []string{"--homedir=" + tc.Tp.GPGHome}
tc.Tp.Debug = false
tc.Tp.Devel = true
tc.Tp.DevelName = name
g.Env.Test = tc.Tp
// SecretStoreFile needs test home directory
g.SecretStoreAll = NewSecretStoreLocked(g)
g.ConfigureLogging()
if err = g.ConfigureAPI(); err != nil {
return
}
// use stub engine for external api
g.XAPI = NewStubAPIEngine()
if err = g.ConfigureConfig(); err != nil {
return
}
if err = g.ConfigureTimers(); err != nil {
return
}
if err = g.ConfigureCaches(); err != nil {
return
}
if err = g.ConfigureMerkleClient(); err != nil {
return
}
g.UI = &nullui{gctx: g}
if err = g.UI.Configure(); err != nil {
return
}
if err = g.ConfigureKeyring(); err != nil {
return
}
g.GregorDismisser = &FakeGregorDismisser{}
tc.PrevGlobal = G
G = g
tc.G = g
tc.T = tb
if G.SecretStoreAll == nil {
G.SecretStoreAll = &SecretStoreLocked{SecretStoreAll: NewTestSecretStoreAll(G, G)}
}
return
}
func SetupTest(tb testing.TB, name string, depth int) (tc TestContext) {
var err error
tc, err = setupTestContext(tb, name, nil)
if err != nil {
tb.Fatal(err)
}
if os.Getenv("KEYBASE_LOG_SETUPTEST_FUNCS") != "" {
pc, file, line, ok := runtime.Caller(depth)
if ok {
fn := runtime.FuncForPC(pc)
fmt.Fprintf(os.Stderr, "- SetupTest %s %s:%d\n", filepath.Base(fn.Name()), filepath.Base(file), line)
}
}
return tc
}
func (tc *TestContext) SetRuntimeDir(s string) {
tc.Tp.RuntimeDir = s
tc.G.Env.Test.RuntimeDir = s
}
func (tc TestContext) Clone() (ret TestContext) {
var err error
ret, err = setupTestContext(tc.T, "", &tc)
if err != nil {
tc.T.Fatal(err)
}
return ret
}
type nullui struct {
gctx *GlobalContext
}
func (n *nullui) Printf(f string, args ...interface{}) (int, error) {
return fmt.Printf(f, args...)
}
func (n *nullui) PrintfStderr(f string, args ...interface{}) (int, error) {
return fmt.Fprintf(os.Stderr, f, args...)
}
func (n *nullui) GetDumbOutputUI() DumbOutputUI {
return n
}
func (n *nullui) GetIdentifyUI() IdentifyUI {
return nil
}
func (n *nullui) GetIdentifyTrackUI() IdentifyUI {
return nil
}
func (n *nullui) GetLoginUI() LoginUI {
return nil
}
func (n *nullui) GetTerminalUI() TerminalUI {
return nil
}
func (n *nullui) GetSecretUI() SecretUI {
return nil
}
func (n *nullui) GetProveUI() ProveUI {
return nil
}
func (n *nullui) GetGPGUI() GPGUI {
return nil
}
func (n *nullui) GetLogUI() LogUI {
return n.gctx.Log
}
func (n *nullui) GetPgpUI() PgpUI {
return nil
}
func (n *nullui) GetProvisionUI(KexRole) ProvisionUI {
return nil
}
func (n *nullui) Prompt(string, bool, Checker) (string, error) {
return "", nil
}
func (n *nullui) PromptForConfirmation(prompt string) error {
return nil
}
func (n *nullui) Configure() error {
return nil
}
func (n *nullui) Shutdown() error {
return nil
}
type TestSecretUI struct {
Passphrase string
StoreSecret bool
CalledGetPassphrase bool
}
func (t *TestSecretUI) GetPassphrase(p keybase1.GUIEntryArg, terminal *keybase1.SecretEntryArg) (keybase1.GetPassphraseRes, error) {
t.CalledGetPassphrase = true
return keybase1.GetPassphraseRes{
Passphrase: t.Passphrase,
StoreSecret: t.StoreSecret,
}, nil
}
type TestCancelSecretUI struct {
CallCount int
}
func (t *TestCancelSecretUI) GetPassphrase(_ keybase1.GUIEntryArg, _ *keybase1.SecretEntryArg) (keybase1.GetPassphraseRes, error) {
t.CallCount++
return keybase1.GetPassphraseRes{}, InputCanceledError{}
}
type TestLoginUI struct {
Username string
RevokeBackup bool
CalledGetEmailOrUsername int
}
func (t *TestLoginUI) GetEmailOrUsername(_ context.Context, _ int) (string, error) {
t.CalledGetEmailOrUsername++
return t.Username, nil
}
func (t *TestLoginUI) PromptRevokePaperKeys(_ context.Context, arg keybase1.PromptRevokePaperKeysArg) (bool, error) {
return t.RevokeBackup, nil
}
func (t *TestLoginUI) DisplayPaperKeyPhrase(_ context.Context, arg keybase1.DisplayPaperKeyPhraseArg) error {
return nil
}
func (t *TestLoginUI) DisplayPrimaryPaperKey(_ context.Context, arg keybase1.DisplayPrimaryPaperKeyArg) error {
return nil
}
type TestLoginCancelUI struct {
TestLoginUI
}
func (t *TestLoginCancelUI) GetEmailOrUsername(_ context.Context, _ int) (string, error) {
return "", InputCanceledError{}
}
type FakeGregorDismisser struct {
dismissedIDs []gregor.MsgID
}
var _ GregorDismisser = (*FakeGregorDismisser)(nil)
func (f *FakeGregorDismisser) DismissItem(id gregor.MsgID) error {
f.dismissedIDs = append(f.dismissedIDs, id)
return nil
}