github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/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 ensureContents(t *testing.T, zipfilepath string, wants map[string][]byte) {
    48  	r, err := zip.OpenReader(zipfilepath)
    49  	if err != nil {
    50  		t.Fatalf("could not open zip file: %s", err)
    51  	}
    52  	defer r.Close()
    53  
    54  	if len(r.File) != len(wants) {
    55  		t.Errorf("mismatched file count, got %d, want %d", len(r.File), len(wants))
    56  	}
    57  	for _, cf := range r.File {
    58  		ensureContent(t, wants, cf)
    59  	}
    60  }
    61  
    62  func ensureContent(t *testing.T, wants map[string][]byte, got *zip.File) {
    63  	want, ok := wants[got.Name]
    64  	if !ok {
    65  		t.Errorf("additional file in zip: %s", got.Name)
    66  		return
    67  	}
    68  
    69  	r, err := got.Open()
    70  	if err != nil {
    71  		t.Errorf("could not open file: %s", err)
    72  	}
    73  	defer r.Close()
    74  	gotContentBytes, err := ioutil.ReadAll(r)
    75  	if err != nil {
    76  		t.Errorf("could not read file: %s", err)
    77  	}
    78  
    79  	wantContent := string(want)
    80  	gotContent := string(gotContentBytes)
    81  	if gotContent != wantContent {
    82  		t.Errorf("mismatched content\ngot\n%s\nwant\n%s", gotContent, wantContent)
    83  	}
    84  }