forked from 1Password/shell-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimporter_test_helper.go
80 lines (65 loc) · 2.23 KB
/
importer_test_helper.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
package plugintest
import (
"context"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/1Password/shell-plugins/sdk"
"github.com/stretchr/testify/assert"
)
// TestImporter will run the importer for each specified case, mounting the specified files in a temp dir,
// setting the environment variables, and configuring the home path using the temp dir.
func TestImporter(t *testing.T, importer sdk.Importer, cases map[string]ImportCase) {
t.Helper()
for name, c := range cases {
t.Run(name, func(t *testing.T) {
if c.ExpectedOutput != nil && len(c.ExpectedCandidates) > 0 {
t.Fatal("ExpectedOutput and ExpectedCandidates can't both be set in the same test case")
}
for envVarName, value := range c.Environment {
t.Setenv(envVarName, value)
}
fsRoot := t.TempDir()
in := sdk.ImportInput{
HomeDir: filepath.Join(fsRoot, "~"),
RootDir: fsRoot,
}
for path, contents := range c.Files {
path = filepath.Join(fsRoot, path)
err := os.MkdirAll(filepath.Dir(path), 0700)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile(path, []byte(contents), 0600)
if err != nil {
t.Fatal(err)
}
}
ctx := context.Background()
out := sdk.ImportOutput{}
importer(ctx, in, &out)
description := fmt.Sprintf("Import: %s", name)
if c.ExpectedOutput != nil {
assert.Equal(t, *c.ExpectedOutput, out, description)
} else {
assert.ElementsMatch(t, c.ExpectedCandidates, out.AllCandidates(), description)
}
for envVarName := range c.Environment {
t.Setenv(envVarName, "")
}
})
}
}
type ImportCase struct {
// Environment can be used to set environment variables for the importer test.
Environment map[string]string
// Files can be used to set files for the importer test, using the format: path -> contents.
// For example: ~/.config/my-pugin/config -> '{"foo":"bar"}'. This is useful in conjunction with the
// LoadFixture helper.
Files map[string]string
// ExpectedCandidates is a shorthand to set the expected import candidates. Mutually exclusive with ExpectedOutput.
ExpectedCandidates []sdk.ImportCandidate
// ExpectedOutput can be used to set the exact expected import output. Mutually exclusive with ExpectedCandidates.
ExpectedOutput *sdk.ImportOutput
}