github.com/HashDataInc/packer@v1.3.2/packer/cache_test.go (about) 1 package packer 2 3 import ( 4 "io/ioutil" 5 "os" 6 "strings" 7 "testing" 8 ) 9 10 type TestCache struct{} 11 12 func (TestCache) Lock(string) string { 13 return "" 14 } 15 16 func (TestCache) Unlock(string) {} 17 18 func (TestCache) RLock(string) (string, bool) { 19 return "", false 20 } 21 22 func (TestCache) RUnlock(string) {} 23 24 func TestFileCache_Implements(t *testing.T) { 25 var raw interface{} 26 raw = &FileCache{} 27 if _, ok := raw.(Cache); !ok { 28 t.Fatal("FileCache must be a Cache") 29 } 30 } 31 32 func TestFileCache(t *testing.T) { 33 cacheDir, err := ioutil.TempDir("", "packer") 34 if err != nil { 35 t.Fatalf("error creating temporary dir: %s", err) 36 } 37 defer os.RemoveAll(cacheDir) 38 39 cache := &FileCache{CacheDir: cacheDir} 40 41 // Test path with no extension (GH-716) 42 path := cache.Lock("/foo.bar/baz") 43 defer cache.Unlock("/foo.bar/baz") 44 if strings.Contains(path, ".bar") { 45 t.Fatalf("bad: %s", path) 46 } 47 48 // Test paths with a ? 49 path = cache.Lock("foo.ext?foo=bar.foo") 50 defer cache.Unlock("foo.ext?foo=bar.foo") 51 if !strings.HasSuffix(path, ".ext") { 52 t.Fatalf("bad extension with question mark: %s", path) 53 } 54 55 // Test normal paths 56 path = cache.Lock("foo.iso") 57 if !strings.HasSuffix(path, ".iso") { 58 t.Fatalf("path doesn't end with suffix '%s': '%s'", ".iso", path) 59 } 60 61 err = ioutil.WriteFile(path, []byte("data"), 0666) 62 if err != nil { 63 t.Fatalf("error writing: %s", err) 64 } 65 66 cache.Unlock("foo.iso") 67 68 path, ok := cache.RLock("foo.iso") 69 if !ok { 70 t.Fatal("cache says key doesn't exist") 71 } 72 defer cache.RUnlock("foo.iso") 73 74 data, err := ioutil.ReadFile(path) 75 if err != nil { 76 t.Fatalf("error reading file: %s", err) 77 } 78 79 if string(data) != "data" { 80 t.Fatalf("unknown data: %s", data) 81 } 82 }