github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/builtin/providers/archive/zip_archiver_test.go (about) 1 package archive 2 3 import ( 4 "archive/zip" 5 "io/ioutil" 6 "testing" 7 ) 8 9 func TestZipArchiver_Content(t *testing.T) { 10 zipfilepath := "archive-content.zip" 11 archiver := NewZipArchiver(zipfilepath) 12 if err := archiver.ArchiveContent([]byte("This is some content"), "content.txt"); err != nil { 13 t.Fatalf("unexpected error: %s", err) 14 } 15 16 ensureContents(t, zipfilepath, map[string][]byte{ 17 "content.txt": []byte("This is some content"), 18 }) 19 } 20 21 func TestZipArchiver_File(t *testing.T) { 22 zipfilepath := "archive-file.zip" 23 archiver := NewZipArchiver(zipfilepath) 24 if err := archiver.ArchiveFile("./test-fixtures/test-file.txt"); err != nil { 25 t.Fatalf("unexpected error: %s", err) 26 } 27 28 ensureContents(t, zipfilepath, map[string][]byte{ 29 "test-file.txt": []byte("This is test content"), 30 }) 31 } 32 33 func TestZipArchiver_Dir(t *testing.T) { 34 zipfilepath := "archive-dir.zip" 35 archiver := NewZipArchiver(zipfilepath) 36 if err := archiver.ArchiveDir("./test-fixtures/test-dir"); err != nil { 37 t.Fatalf("unexpected error: %s", err) 38 } 39 40 ensureContents(t, zipfilepath, map[string][]byte{ 41 "file1.txt": []byte("This is file 1"), 42 "file2.txt": []byte("This is file 2"), 43 "file3.txt": []byte("This is file 3"), 44 }) 45 } 46 47 func TestZipArchiver_Multiple(t *testing.T) { 48 zipfilepath := "archive-content.zip" 49 content := map[string][]byte{ 50 "file1.txt": []byte("This is file 1"), 51 "file2.txt": []byte("This is file 2"), 52 "file3.txt": []byte("This is file 3"), 53 } 54 55 archiver := NewZipArchiver(zipfilepath) 56 if err := archiver.ArchiveMultiple(content); err != nil { 57 t.Fatalf("unexpected error: %s", err) 58 } 59 60 ensureContents(t, zipfilepath, content) 61 62 } 63 64 func ensureContents(t *testing.T, zipfilepath string, wants map[string][]byte) { 65 r, err := zip.OpenReader(zipfilepath) 66 if err != nil { 67 t.Fatalf("could not open zip file: %s", err) 68 } 69 defer r.Close() 70 71 if len(r.File) != len(wants) { 72 t.Errorf("mismatched file count, got %d, want %d", len(r.File), len(wants)) 73 } 74 for _, cf := range r.File { 75 ensureContent(t, wants, cf) 76 } 77 } 78 79 func ensureContent(t *testing.T, wants map[string][]byte, got *zip.File) { 80 want, ok := wants[got.Name] 81 if !ok { 82 t.Errorf("additional file in zip: %s", got.Name) 83 return 84 } 85 86 r, err := got.Open() 87 if err != nil { 88 t.Errorf("could not open file: %s", err) 89 } 90 defer r.Close() 91 gotContentBytes, err := ioutil.ReadAll(r) 92 if err != nil { 93 t.Errorf("could not read file: %s", err) 94 } 95 96 wantContent := string(want) 97 gotContent := string(gotContentBytes) 98 if gotContent != wantContent { 99 t.Errorf("mismatched content\ngot\n%s\nwant\n%s", gotContent, wantContent) 100 } 101 }