github.com/pbberlin/go-pwa@v0.0.0-20220328105622-7c26e0ca1ab8/pkg/static/handler_test.go (about) 1 package static 2 3 import ( 4 "bytes" 5 "compress/gzip" 6 "fmt" 7 "io" 8 "log" 9 "net/http" 10 "net/http/httptest" 11 "os" 12 "testing" 13 14 "github.com/pbberlin/go-pwa/pkg/cfg" 15 ) 16 17 func init() { 18 log.SetFlags(log.Lshortfile | log.Llongfile) 19 } 20 21 func TestMainGetH(t *testing.T) { 22 test(t, "GET") 23 } 24 25 func TestMainPostH(t *testing.T) { 26 // test(t, "POST") 27 } 28 29 func test(t *testing.T, method string) { 30 31 // 32 // app init stuff 33 _ = os.Chdir("../..") 34 wd, _ := os.Getwd() 35 t.Logf("working dir is %v", wd) 36 cfg.Headless(cfg.Load, "/config/load") // create version 37 cfg.Headless(PrepareStatic, "/prepare-static") // create versioned files 38 39 // 40 // 41 pth := fmt.Sprint("/favicon.ico") 42 postBody := &bytes.Buffer{} 43 44 req, err := http.NewRequest(method, pth, postBody) // <-- encoded payload 45 if err != nil { 46 t.Fatal(err) 47 } 48 req.Header.Add("Accept-Encoding", "gzip") 49 req.Header.Add("Accept", "image/x-icon") 50 51 // http.Client 52 53 w := httptest.NewRecorder() // satisfying http.ResponseWriter for recording 54 handler := http.HandlerFunc(staticDirsDefault.serveStatic) 55 56 handler.ServeHTTP(w, req) 57 58 if status := w.Code; status != http.StatusOK { 59 t.Errorf("%v: status code: got %v, want %v", pth, status, http.StatusOK) 60 } else { 61 t.Logf("%v: Response code OK", pth) 62 } 63 64 /* rsp := w.Result() 65 got, err := io.ReadAll(rsp.Body) 66 if err != nil { 67 t.Errorf("ReadAll failed: %v", err) 68 } 69 */ 70 gotZipped := w.Body.Bytes() 71 72 rdr, err := gzip.NewReader(bytes.NewBuffer(gotZipped)) 73 if err != nil { 74 t.Logf("could not read the response as gzip: %v", err) 75 } 76 defer rdr.Close() 77 78 got, err := io.ReadAll(rdr) 79 if err != nil { 80 t.Errorf("ReadAll failed: %v", err) 81 } 82 83 // compare the response body 84 pth2 := "./app-bucket/img/favicon.ico" 85 t.Logf("Reading from %v", pth2) 86 wnt, err := os.ReadFile(pth2) 87 if err != nil { 88 t.Fatal(err) 89 } 90 91 if !bytes.Contains(got, wnt) { 92 t.Errorf("%v: handler returned wrong img - got %v Bytes -- wnt %v Bytes", pth, len(got), len(wnt)) 93 for key, hdr := range w.HeaderMap { 94 t.Logf(" %-20v - %+v", key, hdr) 95 } 96 // ioutil.WriteFile(fmt.Sprintf("tmp-test_%v_want.html", method), []byte(expected), 0777) 97 // ioutil.WriteFile(fmt.Sprintf("tmp-test_%v_got.html", method), []byte(body), 0777) 98 } 99 }