...
1 package clidoc
2
3 import (
4 "bytes"
5 "io/fs"
6 "os"
7 "path/filepath"
8 "testing"
9
10 "github.com/spf13/cobra"
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 )
14
15 func noopRun(_ *cobra.Command, _ []string) {}
16
17 var (
18 root = &cobra.Command{Use: "root", Run: noopRun}
19 child1 = &cobra.Command{Use: "child1", Run: noopRun}
20 child2 = &cobra.Command{Use: "child2", Run: noopRun}
21 subChild1 = &cobra.Command{Use: "subChild1", Run: noopRun}
22 )
23
24 func snapshotDir(t *testing.T, path ...string) (assertNoChange func(t *testing.T)) {
25 var (
26 as []func(*testing.T)
27 fps []string
28 )
29
30 require.NoError(t, filepath.WalkDir(filepath.Join(path...), func(path string, d fs.DirEntry, err error) error {
31 require.NoError(t, err, path)
32 if !d.IsDir() {
33 fps = append(fps, path)
34 as = append(as, snapshotFile(t, path))
35 }
36 return nil
37 }))
38
39 return func(t *testing.T) {
40 fileN := 0
41 require.NoError(t, filepath.WalkDir(filepath.Join(path...), func(path string, d fs.DirEntry, err error) error {
42 require.NoError(t, err)
43 if !d.IsDir() {
44 assert.Contains(t, fps, path)
45 fileN++
46 }
47 return nil
48 }))
49 assert.Equal(t, len(fps), fileN)
50
51 for _, a := range as {
52 a(t)
53 }
54 }
55 }
56
57 func snapshotFile(t *testing.T, path ...string) (assertNoChange func(t *testing.T)) {
58 pre, err := os.ReadFile(filepath.Join(path...))
59 require.NoError(t, err)
60 pre = bytes.ReplaceAll(pre, []byte("\r\n"), []byte("\n"))
61
62 return func(t *testing.T) {
63 post, err := os.ReadFile(filepath.Join(path...))
64 require.NoError(t, err)
65
66 assert.Equal(t, string(pre), string(post))
67 }
68 }
69
70 func TestGenerate(t *testing.T) {
71 child1.AddCommand(subChild1)
72 root.AddCommand(child1, child2)
73
74 assertNoChange := snapshotDir(t, "testdata")
75 require.NoError(t, Generate(root, []string{"testdata"}))
76 assertNoChange(t)
77 }
78
View as plain text