github.com/bhameyie/otto@v0.2.1-0.20160406174117-16052efa52ec/helper/bindata/data_test.go (about) 1 package bindata 2 3 import ( 4 "bytes" 5 "crypto/md5" 6 "io" 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 "reflect" 11 "testing" 12 13 "github.com/hashicorp/otto/helper/bindata/test-pkg" 14 ) 15 16 func TestDataCopyDir(t *testing.T) { 17 cases := []struct { 18 Dir string 19 }{ 20 {"copy-dir-basic"}, 21 {"copy-dir-extends"}, 22 {"copy-dir-extends-var"}, 23 {"copy-dir-include"}, 24 {"copy-dir-shared"}, 25 } 26 27 for _, tc := range cases { 28 d := testData() 29 30 func() { 31 td, err := ioutil.TempDir("", "otto") 32 if err != nil { 33 t.Fatalf("err: %s", err) 34 } 35 defer os.RemoveAll(td) 36 37 dir := filepath.Join("test-data", tc.Dir) 38 if err := d.CopyDir(td, dir); err != nil { 39 t.Fatalf("err: %s", err) 40 } 41 42 testCompareDir(t, td, dir+"-expected") 43 }() 44 } 45 } 46 47 func testData() *Data { 48 return &Data{ 49 Asset: Asset, 50 AssetDir: AssetDir, 51 Context: map[string]interface{}{ 52 "value": "foo", 53 }, 54 SharedExtends: map[string]*Data{ 55 "foo": &Data{ 56 Asset: testpkg.Asset, 57 AssetDir: testpkg.AssetDir, 58 }, 59 }, 60 } 61 } 62 63 func testCompareDir(t *testing.T, a string, b string) { 64 f, err := os.Open(a) 65 if err != nil { 66 t.Fatalf("err: %s", err) 67 } 68 defer f.Close() 69 70 if _, err := os.Stat(b); err != nil { 71 t.Fatalf("doesn't exist: %s", err) 72 } 73 74 fis, err := f.Readdir(-1) 75 if err != nil { 76 t.Fatalf("err: %s", err) 77 } 78 79 for _, fi := range fis { 80 aPath := filepath.Join(a, fi.Name()) 81 bPath := filepath.Join(b, fi.Name()) 82 if filepath.Ext(bPath) == ".tpl" { 83 bPath = bPath[:len(bPath)-len(".tpl")] 84 } 85 86 if fi.IsDir() { 87 testCompareDir(t, aPath, bPath) 88 continue 89 } 90 91 hash := md5.New() 92 93 // Hash A 94 var aReal bytes.Buffer 95 af, err := os.Open(aPath) 96 if err != nil { 97 t.Fatalf("err: %s", err) 98 } 99 _, err = io.Copy(io.MultiWriter(&aReal, hash), af) 100 af.Close() 101 if err != nil { 102 t.Fatalf("err: %s", err) 103 } 104 aHash := hash.Sum(nil) 105 106 // Hash B 107 hash.Reset() 108 bf, err := os.Open(bPath) 109 if err != nil { 110 t.Fatalf("err: %s", err) 111 } 112 _, err = io.Copy(hash, bf) 113 bf.Close() 114 if err != nil { 115 t.Fatalf("err: %s", err) 116 } 117 bHash := hash.Sum(nil) 118 119 if !reflect.DeepEqual(aHash, bHash) { 120 t.Fatalf("difference: %s\n\n%s", aPath, aReal.String()) 121 } 122 } 123 }