package nvdmirror import ( "os" "path/filepath" "reflect" "testing" ) func TestNewJsonCache(t *testing.T) { passTests := []struct { name string vals map[string]map[string]string } {{ name: "empty", }, { name: "foobarbaz", vals: map[string]map[string]string { "foo": map[string]string { "bar": "baz", }, }, }} // create temp dir dir, err := os.MkdirTemp("", "TestNewJsonCache") if err != nil { t.Error(err) return } defer os.RemoveAll(dir) // dir = "testdata" for _, test := range(passTests) { t.Run(test.name, func(t *testing.T) { // build cache path path := filepath.Join(dir, test.name) { // load cache cache, err := NewJsonCache(path) if err != nil { t.Error(err) return } // set values for k, v := range(test.vals) { if err = cache.Set(k, v); err != nil { t.Error(err) return } } // close cache if err = cache.Close(); err != nil { t.Error(err) return } } { // open previously saved cache cache, err := NewJsonCache(path) if err != nil { t.Error(err) return } defer cache.Close() // check values for k, exp := range(test.vals) { if got, ok := cache.Get(k); !ok { t.Errorf("missing key: %s", k) return } else if !reflect.DeepEqual(got, exp) { t.Errorf("got %v, exp %v", got, exp) return } // delete entry if err = cache.Delete(k); err != nil { t.Error(err) return } // get entry again if got, ok := cache.Get(k); ok { t.Errorf("key: %s, got %v, exp missing", k, got) return } } // try accessing missing value if got, ok := cache.Get("some key that doesn't exist"); ok { t.Errorf("got %v, exp !ok", got) } // close cache, check for error if err = cache.Close(); err != nil { t.Error(err) return } if cache.dirty { t.Errorf("got dirty, exp clean") return } } }) } failNewTests := []string { "testdata/does/not/exist", "testdata/bad-data.json.gz", "testdata/bad-stat.json.gz", } for _, test := range(failNewTests) { t.Run(test, func(t *testing.T) { if got, err := NewJsonCache(test); err == nil { t.Errorf("got %v, exp err", got) } }) } failCloseTests := []string { "/dev/null", } testVals := map[string]string { "bar": "baz" } for _, test := range(failCloseTests) { t.Run(test, func(t *testing.T) { cache, err := NewJsonCache(test) if err != nil { t.Error(err) return } if err = cache.Set("foo", testVals); err != nil { t.Error(err) return } if err = cache.Close(); err == nil { t.Errorf("got success, exp error") } }) } }