@@ -16,7 +16,76 @@ limitations under the License.
1616
1717package cmd
1818
19+ import (
20+ "os"
21+ "path"
22+ "path/filepath"
23+ "testing"
24+
25+ homedir "github.com/mitchellh/go-homedir"
26+ )
27+
1928type testpair struct {
2029 input []string
2130 shouldError bool
2231}
32+
33+ func TestCacheDir (t * testing.T ) {
34+ homeDir , _ := homedir .Dir ()
35+ tests := []struct {
36+ name string
37+ cliFlag string
38+ envVar string
39+ expectedDir string
40+ imageName string
41+ }{
42+ // name, cliFlag, envVar, expectedDir
43+ {
44+ name : "default cache is at $HOME" ,
45+ cliFlag : "" ,
46+ envVar : "" ,
47+ expectedDir : filepath .Join (homeDir , ".container-diff" , "cache" ),
48+ imageName : "pancakes" ,
49+ },
50+ {
51+ name : "setting cache via --cache-dir" ,
52+ cliFlag : "/tmp" ,
53+ envVar : "" ,
54+ expectedDir : "/tmp/.container-diff/cache" ,
55+ imageName : "pancakes" ,
56+ },
57+ {
58+ name : "setting cache via CONTAINER_DIFF_CACHEDIR" ,
59+ cliFlag : "" ,
60+ envVar : "/tmp" ,
61+ expectedDir : "/tmp/.container-diff/cache" ,
62+ imageName : "pancakes" ,
63+ },
64+ {
65+ name : "command line --cache-dir takes preference to CONTAINER_DIFF_CACHEDIR" ,
66+ cliFlag : "/tmp" ,
67+ envVar : "/opt" ,
68+ expectedDir : "/tmp/.container-diff/cache" ,
69+ imageName : "pancakes" ,
70+ },
71+ }
72+
73+ for _ , tt := range tests {
74+ t .Run (tt .name , func (t * testing.T ) {
75+ // set any environment variables
76+ if tt .envVar != "" {
77+ os .Setenv ("CONTAINER_DIFF_CACHEDIR" , tt .envVar )
78+ }
79+ // Set global flag for cache based on --cache-dir
80+ cacheDir = tt .cliFlag
81+
82+ // call getCacheDir and make sure return is equal to expected
83+ actualDir , _ := getCacheDir (tt .imageName )
84+
85+ if path .Dir (actualDir ) != tt .expectedDir {
86+ t .Errorf ("%s\n Expected: %v\n Got: %v" , tt .name , tt .expectedDir , actualDir )
87+ }
88+ },
89+ )
90+ }
91+ }
0 commit comments