我在我的Ubuntu 12.04.1筆記本電腦上運行go 1.0.3,並且我偶然發現了一個問題,如果我在main()中運行一些代碼,如果我使用go test進行測試,則會更加不同。Go代碼在去測試和去運行中的行爲不同
這裏是我的例子:
從main.go
package main
import (
"image"
"image/jpeg"
"fmt"
"myproj/htmlutil"
[some imports removed]
)
func main() {
img, err := htmlutil.GetResizedImageFromWeb("http://img.foodnetwork.com/FOOD/2011/05/04/FNM_060111-OOT-B005_s4x3.jpg")
if err != nil {
fmt.Println("There was a problem ",err)
}
fmt.Println("Bounds were ",img.Bounds())
}
從的Myproj/htmlutil_test.go
package htmlutil
import (
"image"
"fmt"
"testing"
[some imports removed]
)
func TestGetImageFromURL(t *testing.T){
img, err := GetResizedImageFromWeb("http://img.foodnetwork.com/FOOD/2011/05/04/FNM_060111-OOT-B005_s4x3.jpg")
if err != nil {
t.Fatalf("There was a problem %q",err)
}
fmt.Println("Bounds were ",img.Bounds())
}
,他們調用)功能,GetResizedImageFromWeb(,是的Myproj/htmlutil 。去:
package htmlutil
import (
"errors"
"fmt"
"image"
"io/ioutil"
"net/http"
[some imports removed]
)
func GetResizedImageFromWeb(imageURL string) (image.Image, error) {
resp, err := http.Get(imageURL)
if err != nil {
return nil, errors.New(fmt.Sprint("There was a problem reading the site %q Debug[%s]",imageURL, err))
}
defer resp.Body.Close()
//Decode the image using image's general purpose decoder
image, s, err := image.Decode(resp.Body)
if err != nil {
return nil, err
}
return resizeImage(image), nil
}
當我跑 「去運行main.go」 從命令行,我可以從url中看到圖像的邊界,如果我想在main.go中使用函數,可以將它保存爲磁盤上的jpg文件。
There was a problem "image: unknown format"
什麼原因造成的問題,只在單元測試失敗:然而,當我運行從htmlutil包,我得到以下錯誤「去測試」?我究竟做錯了什麼?
我唯一的猜測是,由於什麼原因,html.Get()沒有返回測試場景中的所有數據,但我仍然爲什麼會發生這種情況而感到困惑。