Go Code在go test和go run中表现不同

Kev*_*inL 6 jpeg get image http go

我在我的Ubuntu 12.04.1笔记本电脑上运行1.0.3并且我偶然发现了一个问题,如果我在main()中运行一些代码,它的行为与我使用go test运行它的方式有很大不同.

这是我的例子:
来自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())
}
Run Code Online (Sandbox Code Playgroud)

来自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())
}
Run Code Online (Sandbox Code Playgroud)

他们调用的函数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
}
Run Code Online (Sandbox Code Playgroud)

当我从命令行运行"go run main.go"时,我会从url看到图像的边界,如果我想在main.go中使用一个函数,可以将它保存为磁盘上的jpg文件.但是,当我从htmlutil包运行"go test"时,我收到以下错误:

There was a problem "image: unknown format"
Run Code Online (Sandbox Code Playgroud)

是什么导致问题只在单元测试中失败?我究竟做错了什么?

我唯一的猜测是,出于任何原因,html.Get()没有返回测试场景中的所有数据,但我仍然感到困惑,为什么会发生这种情况.

Kev*_*inL 2

我尝试了 rputikar 的解决方案(使用 t.Fatal() 而不是 fmt.Println()),但这没有帮助。

确实注意到 rputikar 对他的进口做了一些与我略有不同的事情。我在 htmlutil.go 中的导入如下所示:

package htmlutil    

import (
    "errors"
    "fmt"
    "image"
    "io/ioutil"
    [some imports removed]
    "net/http"
)
Run Code Online (Sandbox Code Playgroud)

但我的 main.go 和 rputikar 的 main_test.go 都包含一个额外的导入, "image/jpeg"。因此,我将其添加到我的 htmlutil.go 导入列表中并解决了问题。我想我会添加“_ image/png”“_ image/gif”只是为了面向未来