github.com/jdhenke/godel@v0.0.0-20161213181855-abeb3861bf0d/cmd/godel/install_test.go (about) 1 // Copyright 2016 Palantir Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package godel 16 17 import ( 18 "io/ioutil" 19 "net/http" 20 "net/http/httptest" 21 "path" 22 "testing" 23 24 "github.com/nmiyake/archiver" 25 "github.com/nmiyake/pkg/dirs" 26 "github.com/pkg/errors" 27 "github.com/stretchr/testify/assert" 28 "github.com/stretchr/testify/require" 29 ) 30 31 func TestDownload(t *testing.T) { 32 tmpDir, cleanup, err := dirs.TempDir("", "") 33 defer cleanup() 34 require.NoError(t, err) 35 36 tgzFile, err := ioutil.TempFile(tmpDir, "") 37 require.NoError(t, err) 38 err = tgzFile.Close() 39 require.NoError(t, err) 40 err = writeSimpleTestTgz(tgzFile.Name()) 41 require.NoError(t, err) 42 43 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 44 bytes, err := ioutil.ReadFile(tgzFile.Name()) 45 require.NoError(t, err) 46 _, err = w.Write(bytes) 47 require.NoError(t, err) 48 })) 49 defer ts.Close() 50 51 fileName, err := getPkg(remotePkg{ 52 Pkg: ts.URL, 53 }, tmpDir, ioutil.Discard) 54 require.NoError(t, err) 55 56 err = archiver.UntarGz(fileName, tmpDir) 57 require.NoError(t, err) 58 59 fileBytes, err := ioutil.ReadFile(path.Join(tmpDir, "test.txt")) 60 require.NoError(t, err) 61 62 assert.Equal(t, "Test file\n", string(fileBytes)) 63 } 64 65 func writeSimpleTestTgz(filePath string) error { 66 tmpDir, cleanup, err := dirs.TempDir("", "") 67 defer cleanup() 68 if err != nil { 69 return errors.Wrapf(err, "failed to create temp directory") 70 } 71 72 testFilePath := path.Join(tmpDir, "test.txt") 73 err = ioutil.WriteFile(testFilePath, []byte("Test file\n"), 0644) 74 if err != nil { 75 return errors.Wrapf(err, "failed to write file %s", testFilePath) 76 } 77 78 err = archiver.TarGz(filePath, []string{testFilePath}) 79 if err != nil { 80 return errors.Wrapf(err, "failed to compress tgz") 81 } 82 83 return nil 84 }