golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/httpdl/httpdl_test.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package httpdl 6 7 import ( 8 "net/http" 9 "net/http/httptest" 10 "os" 11 "path/filepath" 12 "strings" 13 "testing" 14 "time" 15 ) 16 17 func TestDownload(t *testing.T) { 18 defer resetHooks() 19 20 someTime := time.Unix(1462292149, 0) 21 const someContent = "this is some content" 22 23 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 24 http.ServeContent(w, r, "foo.txt", someTime, strings.NewReader(someContent)) 25 })) 26 defer ts.Close() 27 28 tmpDir, err := os.MkdirTemp("", "dl") 29 if err != nil { 30 t.Fatal(err) 31 } 32 defer os.RemoveAll(tmpDir) 33 dstFile := filepath.Join(tmpDir, "foo.txt") 34 35 hitCurPath := false 36 hookIsCurrent = func() { hitCurPath = true } 37 38 // First. 39 if err := Download(dstFile, ts.URL+"/foo.txt"); err != nil { 40 t.Fatal(err) 41 } 42 if hitCurPath { 43 t.Fatal("first should've actually downloaded") 44 } 45 if fi, err := os.Stat(dstFile); err != nil { 46 t.Fatal(err) 47 } else if !fi.ModTime().Equal(someTime) { 48 t.Fatalf("modtime = %v; want %v", fi.ModTime(), someTime) 49 } else if fi.Size() != int64(len(someContent)) { 50 t.Fatalf("size = %v; want %v", fi.Size(), len(someContent)) 51 } 52 53 // Second. 54 if err := Download(dstFile, ts.URL+"/foo.txt"); err != nil { 55 t.Fatal(err) 56 } 57 if !hitCurPath { 58 t.Fatal("second shouldn't have downloaded") 59 } 60 61 // Then touch to invalidate. 62 os.Chtimes(dstFile, time.Now(), time.Now()) 63 hitCurPath = false // reset 64 if err := Download(dstFile, ts.URL+"/foo.txt"); err != nil { 65 t.Fatal(err) 66 } 67 if hitCurPath { 68 t.Fatal("should've re-downloaded after modtime change") 69 } 70 71 // Also check re-download on size change. 72 os.WriteFile(dstFile, []byte(someContent+someContent), 0644) 73 os.Chtimes(dstFile, someTime, someTime) 74 if err := Download(dstFile, ts.URL+"/foo.txt"); err != nil { 75 t.Fatal(err) 76 } 77 if hitCurPath { 78 t.Fatal("should've re-downloaded after size change") 79 } 80 }