-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathresolver_test.go
More file actions
313 lines (268 loc) · 10.7 KB
/
Copy pathresolver_test.go
File metadata and controls
313 lines (268 loc) · 10.7 KB
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
package source
import (
"archive/zip"
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
errUtils "github.com/cloudposse/atmos/errors"
"github.com/cloudposse/atmos/pkg/generator/templates"
"github.com/cloudposse/atmos/pkg/schema"
)
const sampleScaffold = `apiVersion: atmos/v1
kind: AtmosScaffoldConfig
metadata:
name: sample
spec:
fields:
- name: project_name
type: input
default: demo
`
// writeSampleTemplate creates a minimal on-disk scaffold template and returns its directory.
func writeSampleTemplate(t *testing.T) string {
t.Helper()
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, "scaffold.yaml"), []byte(sampleScaffold), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(dir, "file.txt"), []byte("hello"), 0o600))
return dir
}
func TestIsTemplateSource(t *testing.T) {
assert.True(t, IsTemplateSource("github.com/acme/template"))
assert.True(t, IsTemplateSource("git::https://example.com/acme/template.git"))
assert.True(t, IsTemplateSource("./local-template"))
assert.True(t, IsTemplateSource("/tmp/local-template"))
assert.False(t, IsTemplateSource("aws/landing-zone"))
assert.False(t, IsTemplateSource("basic"))
}
func TestWithRef(t *testing.T) {
assert.Equal(t, "github.com/acme/template?ref=v1.2.3", WithRef("github.com/acme/template", "v1.2.3"))
assert.Equal(t, "github.com/acme/template//scaffold?ref=v1.2.3", WithRef("github.com/acme/template//scaffold", "v1.2.3"))
assert.Equal(t, "github.com/acme/template?depth=1&ref=v1.2.3", WithRef("github.com/acme/template?depth=1", "v1.2.3"))
assert.Equal(t, "github.com/acme/template?ref=main", WithRef("github.com/acme/template?ref=main", "v1.2.3"))
assert.Equal(t, "./local", WithRef("./local", "v1.2.3"))
}
func hasSampleFile(files []templates.File) bool {
for _, f := range files {
if f.Path == "file.txt" {
return true
}
}
return false
}
func TestResolve_LocalPath(t *testing.T) {
dir := writeSampleTemplate(t)
cfg, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "sample", dir, time.Minute)
require.NoError(t, err)
require.NotNil(t, cleanup)
defer cleanup()
require.NotNil(t, cfg)
assert.True(t, hasSampleFile(cfg.Files), "local template files must be loaded")
assert.Equal(t, dir, cfg.Source, "local sources must record the original path")
}
func TestResolve_LocalPathDefaultTimeout(t *testing.T) {
dir := writeSampleTemplate(t)
cfg, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "sample", dir, 0)
require.NoError(t, err)
defer cleanup()
require.NotNil(t, cfg)
assert.True(t, hasSampleFile(cfg.Files))
}
func TestResolve_FileURI(t *testing.T) {
dir := writeSampleTemplate(t)
cfg, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "sample", "file://"+dir, time.Minute)
require.NoError(t, err)
defer cleanup()
require.NotNil(t, cfg)
assert.True(t, hasSampleFile(cfg.Files))
}
func TestResolve_BadLocalPathReturnsLoadError(t *testing.T) {
_, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "missing", filepath.Join(t.TempDir(), "missing"), time.Minute)
require.Error(t, err)
require.NotNil(t, cleanup)
cleanup()
}
func TestResolve_LocalPathMissingScaffoldConfig(t *testing.T) {
dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, "README.md"), []byte("not a scaffold"), 0o600))
_, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "missing-scaffold", dir, time.Minute)
require.Error(t, err)
assert.ErrorIs(t, err, errUtils.ErrScaffoldConfigMissing)
require.NotNil(t, cleanup)
cleanup()
}
func TestResolve_OCIUnsupported(t *testing.T) {
_, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "x", "oci://ghcr.io/cloudposse/x:latest", time.Minute)
require.Error(t, err)
assert.ErrorIs(t, err, errUtils.ErrScaffoldSourceUnsupported)
require.NotNil(t, cleanup)
cleanup()
}
func TestResolve_RemoteFetchFailureCleansUp(t *testing.T) {
_, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "x", "git::file:///definitely/not/a/repo", time.Millisecond)
require.Error(t, err)
assert.ErrorIs(t, err, errUtils.ErrScaffoldFetchSource)
require.NotNil(t, cleanup)
cleanup()
}
func TestHydrate_NoopForFullConfig(t *testing.T) {
stub := &templates.Configuration{Name: "x", Files: []templates.File{{Path: "a"}}}
cleanup, err := Hydrate(stub, "")
require.NoError(t, err)
require.NotNil(t, cleanup)
cleanup()
assert.Len(t, stub.Files, 1, "full configs are returned unchanged")
}
func TestHydrate_NoopForEmptySource(t *testing.T) {
stub := &templates.Configuration{Name: "x"}
cleanup, err := Hydrate(stub, "")
require.NoError(t, err)
cleanup()
assert.Empty(t, stub.Files)
}
func TestHydrate_LocalStub(t *testing.T) {
dir := writeSampleTemplate(t)
stub := &templates.Configuration{Name: "sample", Source: dir}
cleanup, err := Hydrate(stub, "")
require.NoError(t, err)
defer cleanup()
assert.True(t, hasSampleFile(stub.Files), "local stub must be hydrated from its source")
assert.Equal(t, dir, stub.Source, "hydrate's *stub = *resolved copy must preserve the original source")
}
func TestHydrate_LocalStubError(t *testing.T) {
stub := &templates.Configuration{Name: "missing", Source: filepath.Join(t.TempDir(), "missing")}
cleanup, err := Hydrate(stub, "")
require.Error(t, err)
require.NotNil(t, cleanup)
cleanup()
}
// requireGit skips the test when the git binary is unavailable, matching the
// inline-skip convention used elsewhere in the codebase for git-backed tests.
func requireGit(t *testing.T) {
t.Helper()
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git binary not found on PATH")
}
}
// initSourceTestGitRepo creates a local git repository on branch "main" with the given
// files committed, mirroring the local-git-fixture pattern used by
// tests/cli_remote_imports_test.go and pkg/stack/imports/remote_test.go.
func initSourceTestGitRepo(t *testing.T, files map[string]string) string {
t.Helper()
repoDir := t.TempDir()
runSourceTestGit(t, repoDir, "init")
runSourceTestGit(t, repoDir, "checkout", "-b", "main")
runSourceTestGit(t, repoDir, "config", "user.email", "test@example.com")
runSourceTestGit(t, repoDir, "config", "user.name", "Test User")
for name, content := range files {
path := filepath.Join(repoDir, filepath.FromSlash(name))
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
}
runSourceTestGit(t, repoDir, "add", ".")
runSourceTestGit(t, repoDir, "commit", "-m", "initial")
return repoDir
}
func runSourceTestGit(t *testing.T, dir string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
require.NoError(t, err, "git %v failed: %s", args, string(out))
}
func sourceTestGitFileURI(path string) string {
cleaned := filepath.ToSlash(filepath.Clean(path))
if filepath.VolumeName(path) != "" && cleaned != "" && cleaned[0] != '/' {
cleaned = "/" + cleaned
}
return (&url.URL{Scheme: "file", Path: cleaned}).String()
}
// TestResolve_RemoteGitSubdirSuccess exercises the remote-fetch branch of Resolve
// (resolver.go's go-getter path) against a real local git remote using go-getter's
// //subdir?ref= syntax — the exact mechanism `atmos init aws/app` relies on. No prior
// test drove a successful fetch through this path; every other scaffold test sets
// ATMOS_SCAFFOLD_SOURCE_OVERRIDE and bypasses it entirely.
func TestResolve_RemoteGitSubdirSuccess(t *testing.T) {
requireGit(t)
repoDir := initSourceTestGitRepo(t, map[string]string{
"aws/app/scaffold.yaml": sampleScaffold,
"aws/app/file.txt": "hello",
})
src := "git::" + sourceTestGitFileURI(repoDir) + "//aws/app?ref=main"
cfg, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "aws/app", src, time.Minute)
require.NoError(t, err)
require.NotNil(t, cleanup)
defer cleanup()
require.NotNil(t, cfg)
assert.True(t, hasSampleFile(cfg.Files), "remote git subdir template files must be loaded")
}
// zipArchive builds an in-memory ZIP archive containing the given files.
// go-getter's HTTP getter unpacks a recognized archive extension (.zip
// included) directly, so serving one over httptest.Server exercises a real
// remote (ClientModeDir) fetch through resolveRemote without needing git or
// any other external binary.
func zipArchive(t *testing.T, files map[string]string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range files {
w, err := zw.Create(name)
require.NoError(t, err)
_, err = w.Write([]byte(content))
require.NoError(t, err)
}
require.NoError(t, zw.Close())
return buf.Bytes()
}
// TestResolve_RemoteRecordsOriginalSource pins the bug where a remote
// (git::/https://) scaffold source ended up with Configuration.Source (and
// therefore the persisted spec.source in .atmos/scaffold.yaml) set to the
// ephemeral os.MkdirTemp download directory instead of the original source
// string. That tempdir is removed by cleanup() as soon as the command
// finishes, leaving spec.source pointing at nothing.
//
// Serves a ZIP archive from a local httptest.Server rather than using a git
// fixture: the ".zip" extension is enough for go-getter's HTTP getter to
// unpack it into the temp dir on its own, so this test never shells out to
// git (or any other external binary) and stays hermetic/cross-platform.
func TestResolve_RemoteRecordsOriginalSource(t *testing.T) {
archive := zipArchive(t, map[string]string{
"scaffold.yaml": sampleScaffold,
"file.txt": "hello",
})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/zip")
_, _ = w.Write(archive)
}))
defer server.Close()
src := server.URL + "/template.zip"
cfg, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "sample", src, time.Minute)
require.NoError(t, err)
require.NotNil(t, cleanup)
defer cleanup()
require.NotNil(t, cfg)
assert.True(t, hasSampleFile(cfg.Files), "remote archive template files must be loaded")
assert.Equal(t, src, cfg.Source, "remote sources must record the original source string, not the ephemeral fetch tempdir")
}
// TestResolve_RemoteGitSubdirMissing pins the exact failure mode reported for
// `atmos init aws/app`: a valid git remote whose requested //subdir does not exist.
func TestResolve_RemoteGitSubdirMissing(t *testing.T) {
requireGit(t)
repoDir := initSourceTestGitRepo(t, map[string]string{
"aws/app/scaffold.yaml": sampleScaffold,
"aws/app/file.txt": "hello",
})
src := "git::" + sourceTestGitFileURI(repoDir) + "//aws/missing?ref=main"
_, cleanup, err := Resolve(&schema.AtmosConfiguration{}, "aws/missing", src, time.Minute)
require.Error(t, err)
assert.ErrorIs(t, err, errUtils.ErrScaffoldFetchSource)
require.NotNil(t, cleanup)
cleanup()
}