44package commands
55
66import (
7+ "log"
78 "os"
9+ "os/exec"
10+ "path"
11+ "path/filepath"
812 "sync"
913 "testing"
1014
1115 cmdtest "github.com/google/go-cmdtest"
1216 "github.com/spf13/cobra"
1317 "github.com/stretchr/testify/require"
14- "go.mondoo.com/cnquery/v11/apps/cnquery/cmd"
1518)
1619
1720var once sync.Once
21+ var testDir string
1822var cnqueryCmd * cobra.Command
1923
2024func setup () {
21- var err error
22- cnqueryCmd , err = cmd .BuildRootCmd ()
25+ // build cnquery
26+ if err := exec .Command ("go" , "build" , "../../apps/cnquery/cnquery.go" ).Run (); err != nil {
27+ log .Fatalf ("building cnquery: %v" , err )
28+ }
29+
30+ // install local provider
31+ if err := exec .Command ("bash" , "-c" , "cd ../.. && make providers/build/os providers/install/os" ).Run (); err != nil {
32+ log .Fatalf ("building os provider: %v" , err )
33+ }
34+
35+ // create a fake directory to use for testing purposes (providers, config, etc.)
36+ dir , err := os .MkdirTemp ("" , "mondoo" )
37+ if err != nil {
38+ log .Fatalf ("creating directory: %v" , err )
39+ }
40+ testDir = dir
41+
42+ // provider install places the provider in the "$(HOME)/.config/mondoo/providers/${$@_NAME}") but we
43+ // want to test it in isolation. Therefore, we copy the provider to the current directory .providers
44+ osProviderPath := filepath .Join (testDir , "os" )
45+ if err := os .MkdirAll (osProviderPath , 0755 ); err != nil {
46+ log .Fatalf ("creating directory: %v" , err )
47+ }
48+
49+ distPath , err := filepath .Abs ("../../providers/os/dist" )
2350 if err != nil {
24- panic (err )
51+ log .Fatalf ("unable to expand dist path: %v" , err )
52+ }
53+
54+ if err := os .CopyFS (osProviderPath , os .DirFS (distPath )); err != nil {
55+ log .Fatalf ("copying provider: %v" , err )
2556 }
2657}
2758
@@ -35,13 +66,15 @@ func TestCompare(t *testing.T) {
3566 ts , err := cmdtest .Read ("testdata" )
3667 require .NoError (t , err )
3768
69+ // Set a fake config path to avoid loading the real configuration
70+ // file from the system running this tests
71+ os .Setenv ("MONDOO_CONFIG_PATH" , path .Join (testDir , "foo" ))
72+ // Override providers path with the fake test directory
73+ os .Setenv ("PROVIDERS_PATH" , testDir )
74+ // Disable auto-update to avoid installing providers
75+ os .Setenv ("MONDOO_AUTO_UPDATE" , "false" )
76+
3877 ts .DisableLogging = true
39- ts .Commands ["cnquery" ] = cmdtest .InProcessProgram ("cnquery" , func () int {
40- err := cnqueryCmd .Execute ()
41- if err != nil {
42- return 1
43- }
44- return 0
45- })
78+ ts .Commands ["cnquery" ] = cmdtest .Program ("cnquery" )
4679 ts .Run (t , false ) // set to true to update test files
4780}
0 commit comments