跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

embed_test.go

528 行 · 13.2 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limatmpl
5
6import (
7 "fmt"
8 "os"
9 "reflect"
10 "strings"
11 "testing"
12
13 "github.com/sirupsen/logrus"
14 "gotest.tools/v3/assert"
15 "gotest.tools/v3/assert/cmp"
16
17 "github.com/lima-vm/lima/v2/pkg/limatype"
18 "github.com/lima-vm/lima/v2/pkg/limayaml"
19)
20
21type embedTestCase struct {
22 description string
23 template string
24 base string
25 expected string
26}
27
28// Notes:
29// * When the template starts with "#" then the comparison will be textual instead of structural.
30// This is required to verify comment handling.
31// * If the description starts with "TODO" then the test is expected to fail (until it is fixed).
32// * If the description starts with "ERROR" then the test is expected to fail with an error containing the expected string.
33// * base is split on "---\n" and stored as base0.yaml, base1.yaml, ... in the same dir as the template.
34// * If any base template starts with "#!" then the extension will be .sh instead of .yaml.
35// * The template is automatically prefixed with "base: base0.yaml" unless base0 is a script.
36// * All line comments will be separated by 2 spaces from the value on output.
37// * Merge order of additionalDisks, mounts, and networks depends on the logic in the
38// combineListEntries() functions and will not follow the order of the base template(s).
39
40var embedTestCases = []embedTestCase{
41 {
42 "Empty template",
43 "",
44 "vmType: qemu",
45 "vmType: qemu",
46 },
47 {
48 "Base doesn't override existing values",
49 "vmType: vz",
50 "{arch: aarch64, vmType: qemu}",
51 "{arch: aarch64, vmType: vz}",
52 },
53 {
54 "Comments are copied over as well",
55 `#
56# VM Type is QEMU
57vmType: qemu # QEMU
58`,
59 `
60# Arch is x86_64
61arch: x86_64 # X86
62`,
63 `
64# VM Type is QEMU
65vmType: qemu # QEMU
66# Arch is x86_64
67arch: x86_64 # X86
68`,
69 },
70 {
71 "mountTypesUnsupported are concatenated and duplicates removed",
72 "mountTypesUnsupported: [9p,reverse-sshfs]",
73 "mountTypesUnsupported: [9p,virtiofs]",
74 "mountTypesUnsupported: [9p,reverse-sshfs,virtiofs]",
75 },
76 {
77 "minimumLimaVersion (including comments) is updated when the base version is higher",
78 `#
79# Works with Lima 0.8.0 and later
80minimumLimaVersion: 0.8.0 # needs 0.8.0
81`,
82 `
83# Requires at least 1.0.2
84minimumLimaVersion: 1.0.2 # or later
85`,
86 `
87# Requires at least 1.0.2
88minimumLimaVersion: 1.0.2 # or later
89`,
90 },
91 {
92 "vmOpts.qmu.minimumVersion is updated when the base version is higher",
93 "vmOpts: {qemu: {minimumVersion: 8.2.1}}",
94 "vmOpts: {qemu: {minimumVersion: 9.1.0}}",
95 "vmOpts: {qemu: {minimumVersion: 9.1.0}}",
96 },
97 {
98 "dns list is not appended, but the highest priority one is picked",
99 "dns: [1.1.1.1]",
100 "dns: [8.8.8.8, 1.2.3.4]",
101 "dns: [1.1.1.1]",
102 },
103 {
104 "dns is copied from base when template has no dns",
105 "",
106 "dns: [1.1.1.1, 8.8.8.8]",
107 "dns: [1.1.1.1, 8.8.8.8]",
108 },
109 {
110 "dns is copied from base when template has empty list",
111 "dns: []",
112 "dns: [1.1.1.1, 8.8.8.8]",
113 "dns: [1.1.1.1, 8.8.8.8]",
114 },
115 {
116 "Update comments on existing maps and lists that don't have comments yet",
117 `#
118additionalDisks:
119- name: disk1 # One
120`,
121 `
122# Mount additional disks
123additionalDisks: # comment
124# This is disk2
125- name: disk2 # Two
126`,
127 `
128# Mount additional disks
129additionalDisks: # comment
130- name: disk1 # One
131# This is disk2
132- name: disk2 # Two
133`,
134 },
135 {
136 "probes and provision scripts are prepended instead of appended",
137 "probes: [{script: 1}]\nprovision: [{script: One}]",
138 "probes: [{script: 2}]\nprovision: [{script: Two}]",
139 "probes: [{script: 2},{script: 1}]\nprovision: [{script: Two},{script: One}]",
140 },
141 {
142 "additionalDisks append, but merge fields on shared name",
143 "additionalDisks: [{name: disk1}]",
144 "additionalDisks: [{name: disk2},{name: disk1, format: true}]",
145 "additionalDisks: [{name: disk1, format: true},{name: disk2}]",
146 },
147 {
148 // This test fails because there are 2 spurious newlines in the merged output
149 "TODO mounts append, but merge fields on shared mountPoint",
150 `#
151# My mounts
152mounts:
153- location: loc1 # mountPoint loc1
154- location: loc1
155 mountPoint: loc2
156`,
157 `
158mounts:
159# will update mountPoint loc2
160- location: loc1
161 mountPoint: loc2
162 writable: true
163 # SSHFS
164 sshfs: # ssh
165 followSymlinks: true
166# will create new mountPoint loc3
167- location: loc1
168 mountPoint: loc3
169 writable: true
170`,
171 `
172# My mounts
173mounts:
174- location: loc1 # mountPoint loc1
175# will update mountPoint loc2
176- location: loc1
177 mountPoint: loc2
178 writable: true
179 # SSHFS
180 sshfs: # ssh
181 followSymlinks: true
182# will create new mountPoint loc3
183- location: loc1
184 mountPoint: loc3
185 writable: true
186`,
187 },
188 {
189 // This entry can be deleted when the previous one no longer fails
190 "mounts append, but merge fields on shared mountPoint (no comments version)",
191 `mounts: [{location: loc1}, {location: loc1, mountPoint: loc2}]`,
192 `mounts: [{location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true, readonlyNames: [.git]}}, {location: loc1, mountPoint: loc3, writable: true}]`,
193 `mounts: [{location: loc1}, {location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true, readonlyNames: [.git]}}, {location: loc1, mountPoint: loc3, writable: true}]`,
194 },
195 {
196 "template: URLs are not embedded when embedAll is false",
197 // also tests file.url format
198 ``,
199 `
200base: template:default
201provision:
202- file:
203 url: template:provision.sh
204probes:
205- file:
206 url: template:probe.sh
207`,
208 `
209base: template:default
210provision:
211- file: template:provision.sh
212probes:
213- file: template:probe.sh
214`,
215 },
216 {
217 "ERROR Each template must only be embedded once",
218 `#
219arch: aarch64
220`,
221 `
222base: base0.yaml
223# failure would mean this test loops forever, not that it fails the test
224vmType: qemu
225`,
226 `base template loop detected`,
227 },
228 {
229 "ERROR All bases following template: bases must be template: URLs too when embedAll is false",
230 ``,
231 `base: [template:default, base1.yaml]`,
232 "after not embedding",
233 },
234 {
235 "ERROR All bases following template: bases must be template: URLs too when embedAll is false",
236 ``,
237 `
238base: [base1.yaml, base2.yaml]
239---
240base: template:default
241---
242base: baseX.yaml`,
243 "after not embedding",
244 },
245 {
246 "Bases are embedded depth-first",
247 `#`,
248 `
249base: [base1.yaml, {url: base2.yaml}] # also test file.url format
250additionalDisks: [disk0]
251---
252base: base3.yaml
253additionalDisks: [disk1]
254---
255additionalDisks: [disk2]
256---
257additionalDisks: [disk3]
258`,
259 `
260additionalDisks: [disk0, disk1, disk3, disk2]
261`,
262 },
263 {
264 "additionalDisks with name '*' are merged with all previous entries",
265 `
266additionalDisks:
267- name: disk1
268- name: disk2
269- name: disk3
270 format: false
271`,
272 `
273additionalDisks:
274- name: disk4
275- name: "*"
276 format: true # will apply to disk1, disk2, and disk4
277- name: disk5
278`,
279 `
280additionalDisks:
281- name: disk1
282 format: true
283- name: disk2
284 format: true
285- name: disk3
286 format: false
287- name: disk4
288 format: true
289- name: disk5
290`,
291 },
292 {
293 // This test fails because the yq commands don't handle comments properly; may need to be fixed in yq
294 "TODO additionalDisks will be upgraded from string to map",
295 `#
296additionalDisks:
297# my head comment
298- mine # my line comment
299`,
300 `
301# head comment
302additionalDisks: # line comment
303- name: "*"
304 format: true # formatting is good for you
305`,
306 `
307# head comment
308additionalDisks: # line comment
309# my head comment
310- name: mine # my line comment
311 format: true # formatting is good for you
312`,
313 },
314 {
315 // This entry can be deleted when the previous one no longer fails
316 "additionalDisks will be upgraded from string to map (no comments version)",
317 `additionalDisks: [mine]`,
318 `additionalDisks: [{name: "*", format: true}]`,
319 `additionalDisks: [{name: mine, format: true}]`,
320 },
321 {
322 "networks without interface name are not merged",
323 `
324networks:
325- interface: lima1
326`,
327 `
328networks:
329- interface: lima2
330# The metric will not be merged with anything
331- metric: 250
332- interface: lima1
333 metric: 100 # will be set on the first entry
334- interface: '*' # wildcard
335 metric: 123 # will be set on the first entry
336`,
337 `
338networks:
339- interface: lima1
340 metric: 100 # will be set on the first entry
341- interface: lima2
342 metric: 123 # will be set on the first entry
343# The metric will not be merged with anything
344- metric: 250
345`,
346 },
347 {
348 "Scripts are embedded with comments moved",
349 `#
350# Hi There!
351provision:
352# This script will be merged from an external file
353- file: base1.sh # This comment will move to the "script" key
354# This is just a data file
355- mode: data
356 file: base1.sh # This comment will move to the "content" key
357 path: /tmp/data
358- mode: yq
359 file: base1.sh # This comment will move to the "expression" key
360 path: /tmp/yq
361`,
362 `
363# base0.yaml is ignored
364---
365#!/usr/bin/env bash
366echo "This is base1.sh"
367`,
368 // TODO: the empty line after the `path` is unexpected
369 `
370# Hi There!
371provision:
372# This script will be merged from an external file
373- script: |- # This comment will move to the "script" key
374 #!/usr/bin/env bash
375 echo "This is base1.sh"
376# This is just a data file
377- mode: data
378 content: |- # This comment will move to the "content" key
379 #!/usr/bin/env bash
380 echo "This is base1.sh"
381 path: /tmp/data
382- mode: yq
383 expression: |- # This comment will move to the "expression" key
384 #!/usr/bin/env bash
385 echo "This is base1.sh"
386 path: /tmp/yq
387
388# base0.yaml is ignored
389`,
390 },
391 {
392 "Script files are embedded even when no base property exists",
393 "provision: [{file: base0.sh}]",
394 "#! my script",
395 `provision: [{script: "#! my script"}]`,
396 },
397 {
398 "ERROR base digest is not yet implemented",
399 "",
400 "base: [{url: base.yaml, digest: deafbad}]",
401 "not yet implemented",
402 },
403 {
404 "Image URLs will be converted into a template",
405 "",
406 "base: https://example.com/lima-linux-riscv64.img",
407 "{arch: riscv64, os: Linux, images: [{location: https://example.com/lima-linux-riscv64.img, arch: riscv64}]}",
408 },
409 {
410 "Binary files are base64 encoded",
411 `#
412provision:
413- mode: data
414 file: base1.sh # This comment will move to the "content" key
415 path: /tmp/data
416`,
417 // base1.sh is binary because it contains an audible bell character '\a'
418 "# base0.yaml is ignored\n---\n#!\a123456789012345678901234567890123456789012345678901234567890",
419 `
420provision:
421- mode: data
422 content: !!binary | # This comment will move to the "content" key
423 IyEHMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0
424 NTY3ODkw
425 path: /tmp/data
426
427# base0.yaml is ignored
428`,
429 },
430}
431
432func TestEmbed(t *testing.T) {
433 focus := os.Getenv("TEST_FOCUS")
434 for _, tc := range embedTestCases {
435 if focus != "" {
436 if !strings.Contains(tc.description, focus) {
437 continue
438 }
439 logrus.SetLevel(logrus.DebugLevel)
440 }
441 t.Run(tc.description, func(t *testing.T) { RunEmbedTest(t, tc) })
442 }
443 logrus.SetLevel(logrus.InfoLevel)
444}
445
446func RunEmbedTest(t *testing.T, tc embedTestCase) {
447 todo := strings.HasPrefix(tc.description, "TODO")
448 expectError := strings.HasPrefix(tc.description, "ERROR")
449 stringCompare := strings.HasPrefix(tc.template, "#")
450
451 // Normalize testcase data
452 tc.template = strings.TrimSpace(strings.TrimPrefix(tc.template, "#"))
453 tc.base = strings.TrimSpace(tc.base)
454 tc.expected = strings.TrimSpace(tc.expected)
455
456 // Change to temp directory so all template and script names don't include a slash.
457 t.Chdir(t.TempDir())
458
459 for i, base := range strings.Split(tc.base, "---\n") {
460 extension := ".yaml"
461 if strings.HasPrefix(base, "#!") {
462 extension = ".sh"
463 }
464 baseFilename := fmt.Sprintf("base%d%s", i, extension)
465 err := os.WriteFile(baseFilename, []byte(base), 0o600)
466 assert.NilError(t, err, tc.description)
467 }
468 tmpl := &Template{
469 Bytes: fmt.Appendf(nil, "base: base0.yaml\n%s", tc.template),
470 Locator: "tmpl.yaml",
471 }
472 // Don't include `base` property if base0 is a script
473 if strings.HasPrefix(tc.base, "#!") {
474 tmpl.Bytes = []byte(tc.template)
475 }
476 err := tmpl.Embed(t.Context(), false, false)
477 if expectError {
478 assert.ErrorContains(t, err, tc.expected, tc.description)
479 return
480 }
481 assert.NilError(t, err, tc.description)
482
483 if stringCompare {
484 actual := strings.TrimSpace(string(tmpl.Bytes))
485 if todo {
486 assert.Assert(t, actual != tc.expected, tc.description)
487 } else {
488 assert.Equal(t, actual, tc.expected, tc.description)
489 }
490 return
491 }
492
493 err = tmpl.Unmarshal()
494 assert.NilError(t, err, tc.description)
495
496 var expected limatype.LimaYAML
497 err = limayaml.Unmarshal([]byte(tc.expected), &expected, "expected")
498 assert.NilError(t, err, tc.description)
499
500 if todo {
501 // using reflect.DeepEqual because cmp.DeepEqual can't easily be negated
502 assert.Assert(t, !reflect.DeepEqual(tmpl.Config, &expected), tc.description)
503 } else {
504 assert.Assert(t, cmp.DeepEqual(tmpl.Config, &expected), tc.description)
505 }
506}
507
508func TestEncodeScriptReason(t *testing.T) {
509 maxLineLength = 8
510 t.Run("regular script", func(t *testing.T) {
511 reason := encodeScriptReason("0123456\n")
512 assert.Equal(t, reason, "")
513 })
514 t.Run("binary script", func(t *testing.T) {
515 reason := encodeScriptReason("abc\a123")
516 assert.Equal(t, reason, "unprintable character '\\a' at offset 3")
517 })
518 t.Run("contains a tab character", func(t *testing.T) {
519 // newline character is included in character count
520 reason := encodeScriptReason("foo\tbar")
521 assert.Equal(t, reason, "unprintable character '\\t' at offset 3")
522 })
523 t.Run("long line", func(t *testing.T) {
524 // newline character is included in character count
525 reason := encodeScriptReason("line 1\nline 2\n01234567\n")
526 assert.Equal(t, reason, "line 3 (offset 14) is longer than 8 characters")
527 })
528}