🧱 Chunk is a download manager for slow and unstable servers
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Merge pull request #28 from cuducos/test-zip-archive

Adds test for ZIP archive download

authored by

Daniel Fireman and committed by
GitHub
6a7bf292 78be3922

+70
+70
downloader_test.go
··· 1 1 package chunk 2 2 3 3 import ( 4 + "archive/zip" 5 + "bytes" 4 6 "context" 5 7 "fmt" 8 + "io" 9 + "math/rand" 6 10 "net/http" 7 11 "net/http/httptest" 8 12 "os" 13 + "path/filepath" 9 14 "strings" 10 15 "sync/atomic" 11 16 "testing" ··· 93 98 } 94 99 if _, ok := <-ch; ok { 95 100 t.Error("expected channel closed, but did not get it") 101 + } 102 + } 103 + 104 + func TestDownload_ZIPArchive(t *testing.T) { 105 + tmp := t.TempDir() 106 + pth := filepath.Join(tmp, "archive.zip") 107 + expected := make([]byte, 1_000_000) 108 + for i := 0; i < 1_000_000; i++ { 109 + expected[i] = byte(97 + rand.Intn(122-97)) 110 + } 111 + 112 + // create a zip archive 113 + func() { 114 + z, err := os.Create(pth) 115 + if err != nil { 116 + t.Errorf("expected no error creating zip archive, got %s", err) 117 + } 118 + defer z.Close() 119 + w := zip.NewWriter(z) 120 + f, err := w.Create("file.txt") 121 + if err != nil { 122 + t.Errorf("expected no error creating archived file, got %s", err) 123 + } 124 + defer w.Close() 125 + if _, err := f.Write(expected); err != nil { 126 + t.Errorf("expected no error writing to archived file, got %s", err) 127 + } 128 + }() 129 + 130 + // create a server to serve the zip archive 131 + s := httptest.NewServer(http.HandlerFunc( 132 + func(w http.ResponseWriter, r *http.Request) { 133 + http.ServeFile(w, r, pth) 134 + }, 135 + )) 136 + defer s.Close() 137 + 138 + // download 139 + var got string 140 + defer os.Remove(got) 141 + for g := range DefaultDownloader().Download(s.URL + "/archive.zip") { 142 + fmt.Println(g) 143 + got = g.DownloadedFilePath 144 + if g.Error != nil { 145 + t.Errorf("expected no error during the download of the zip archive, got %s", g.Error) 146 + } 147 + } 148 + 149 + // unarchive and check contents 150 + a, err := zip.OpenReader(got) 151 + if err != nil { 152 + t.Errorf("expected no error opening downloaded zip archive %s, got %s", got, err) 153 + } 154 + defer a.Close() 155 + r, err := a.Open("file.txt") 156 + if err != nil { 157 + t.Errorf("expected no error reading downloaded zip archive, got %s", err) 158 + } 159 + defer r.Close() 160 + var b bytes.Buffer 161 + if _, err := io.Copy(&b, r); err != nil { 162 + t.Errorf("expected no error reading archived file, got %s", err) 163 + } 164 + if !bytes.Equal(expected, b.Bytes()) { 165 + t.Error("archived contents differ from expected") // not printing becasuse it's a lot of data 96 166 } 97 167 } 98 168