github.com/dahs81/otto@v0.2.1-0.20160126165905-6400716cf085/scriptpack/scriptpack_test.go (about) 1 package scriptpack 2 3 import ( 4 "archive/tar" 5 "compress/gzip" 6 "io" 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 "reflect" 11 "sort" 12 "testing" 13 14 testBasic "github.com/hashicorp/otto/scriptpack/test-basic" 15 ) 16 17 func TestScriptPackWrite(t *testing.T) { 18 // Build the SP 19 sp := &ScriptPack{ 20 Name: "foo", 21 Data: testBasic.Bindata, 22 } 23 24 // Temporary dir to test contents 25 td, err := ioutil.TempDir("", "otto") 26 if err != nil { 27 t.Fatalf("err: %s", err) 28 } 29 defer os.RemoveAll(td) 30 31 // Write the data! 32 if err := sp.Write(td); err != nil { 33 t.Fatalf("err: %s", err) 34 } 35 36 // Verify some files exist 37 var path string 38 path = filepath.Join(td, sp.Name, "hello.txt") 39 if _, err := os.Stat(path); err != nil { 40 t.Fatalf("err: %s", err) 41 } 42 } 43 44 func TestScriptPackWriteArchive(t *testing.T) { 45 // Build the SP 46 sp := &ScriptPack{ 47 Name: "foo", 48 Data: testBasic.Bindata, 49 } 50 51 // Temporary dir to test contents 52 td, err := ioutil.TempDir("", "otto") 53 if err != nil { 54 t.Fatalf("err: %s", err) 55 } 56 defer os.RemoveAll(td) 57 58 // Write the data! 59 archivePath := filepath.Join(td, "foo.tar.gz") 60 if err := sp.WriteArchive(archivePath); err != nil { 61 t.Fatalf("err: %s", err) 62 } 63 64 // Verify some files exist 65 files := testArchive(t, archivePath, false) 66 expected := []string{"foo/", "foo/hello.txt", "main.sh"} 67 if !reflect.DeepEqual(files, expected) { 68 t.Fatalf("bad: %#v", files) 69 } 70 } 71 72 func testArchive(t *testing.T, path string, detailed bool) []string { 73 f, err := os.Open(path) 74 if err != nil { 75 t.Fatalf("err: %s", err) 76 } 77 defer f.Close() 78 79 gzipR, err := gzip.NewReader(f) 80 if err != nil { 81 t.Fatalf("err: %s", err) 82 } 83 tarR := tar.NewReader(gzipR) 84 85 // Read all the entries 86 result := make([]string, 0, 5) 87 for { 88 hdr, err := tarR.Next() 89 if err == io.EOF { 90 break 91 } 92 if err != nil { 93 t.Fatalf("err: %s", err) 94 } 95 96 text := hdr.Name 97 if detailed { 98 // Check if the file is executable. We use these stub names 99 // to compensate for umask differences in test environments 100 // and limitations in using "git clone". 101 if hdr.FileInfo().Mode()&0111 != 0 { 102 text = hdr.Name + "-exec" 103 } else { 104 text = hdr.Name + "-reg" 105 } 106 } 107 108 result = append(result, text) 109 } 110 111 sort.Strings(result) 112 return result 113 }