func TestImageHandler(t *testing.T) { client, proxy, l := oneShotProxy(t) defer l.Close() football := getImage("test_data/football.png", t) proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { return football })) resp, err := client.Get(localFile("test_data/panda.png")) if err != nil { t.Fatal("Cannot get panda.png", err) } img, _, err := image.Decode(resp.Body) if err != nil { t.Error("decode", err) } else { compareImage(football, img, t) } // and again resp, err = client.Get(localFile("test_data/panda.png")) if err != nil { t.Fatal("Cannot get panda.png", err) } img, _, err = image.Decode(resp.Body) if err != nil { t.Error("decode", err) } else { compareImage(football, img, t) } }
func getImage(file string, t *testing.T) image.Image { newimage, err := ioutil.ReadFile(file) if err != nil { t.Fatal("Cannot read file", file, err) } img, _, err := image.Decode(bytes.NewReader(newimage)) if err != nil { t.Fatal("Cannot decode image", file, err) } return img }
func TestReplaceImage(t *testing.T) { client, proxy, l := oneShotProxy(t) defer l.Close() panda := getImage("test_data/panda.png", t) football := getImage("test_data/football.png", t) proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { return football })) proxy.OnResponse(goproxy.UrlIs("/test_data/football.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image { return panda })) imgByPandaReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/panda.png"), client, t))) fatalOnErr(err, "decode panda", t) compareImage(football, imgByPandaReq, t) imgByFootballReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/football.png"), client, t))) fatalOnErr(err, "decode football", t) compareImage(panda, imgByFootballReq, t) }