我正在我的Ubuntu 12.04.1笔记本电脑上运行go 1.0.3,遇到了一个问题,如果我在main()中运行一些代码,它的行为与使用go test运行它时有很大不同。
以下是我的示例:
来自main.go
当我在命令行中运行"go run main.go"时,我可以看到来自URL的图片边界,并且可以使用main.go中的一个函数将其保存为jpg文件。然而,当我从htmlutil包中运行"go test"时,我会遇到以下错误:
什么原因导致问题只在单元测试中失败?我做错了什么?
我唯一的猜测是,在测试场景中,html.Get() 没有返回所有的数据,但我仍然不明白为什么会发生这种情况。
以下是我的示例:
来自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.go中:
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
}
当我在命令行中运行"go run main.go"时,我可以看到来自URL的图片边界,并且可以使用main.go中的一个函数将其保存为jpg文件。然而,当我从htmlutil包中运行"go test"时,我会遇到以下错误:
There was a problem "image: unknown format"
什么原因导致问题只在单元测试中失败?我做错了什么?
我唯一的猜测是,在测试场景中,html.Get() 没有返回所有的数据,但我仍然不明白为什么会发生这种情况。