【发布时间】:2021-05-18 16:21:15
【问题描述】:
我正在学习有关 Go 的教程,并且我有实际的文件树:
.
├── arrays
├── concurrency
├── di
├── hello-world
├── integers
├── iteration
├── maps
├── mocking
├── pointers
├── racer
└── structs
如果我在所有文件夹文件中运行测试,它们都可以工作,但名为 racer 的文件夹除外, 运行测试给我以下错误:
# runtime/cgo
cgo: exec /missing-cc: fork/exec /missing-cc: no such file or directory
FAIL github.com/Gabriel2233/go-with-tests/racer [build failed]
这与我在文件中所做的事情有关吗?这是测试文件
package racer
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestRacer(t *testing.T) {
slowServer := makeDelayedServer(20 * time.Millisecond)
fastServer := makeDelayedServer(0 * time.Millisecond)
defer slowServer.Close()
defer fastServer.Close()
slowURL := slowServer.URL
fastURL := fastServer.URL
want := fastURL
got := Racer(slowURL, fastURL)
if got != want {
t.Errorf("got %q, want %q", got, want)
}
t.Run("returns error if race takes more than 10s", func(t *testing.T) {
serverA := makeDelayedServer(time.Second * 11)
serverB := makeDelayedServer(time.Second * 12)
defer serverA.Close()
defer serverB.Close()
_, err := Racer(serverA.URL, serverB.URL)
if err == nil {
t.Error("expected an error but didn't get one")
}
})
}
func makeDelayedServer(delay time.Duration) *httptest.Server {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(delay * time.Millisecond)
w.WriteHeader(http.StatusOK)
})
server := httptest.NewServer(handler)
return server
}
这是racer.go 文件
package racer
import (
"net/http"
"time"
)
func Racer(a, b string) (winner string) {
select {
case <-ping(a):
return a
case <-ping(b):
return b
}
}
func ping(url string) chan struct{} {
ch := make(chan struct{})
go func() {
http.Get(url)
close(ch)
}()
return ch
}
func measureResponseTime(url string) time.Duration {
start := time.Now()
http.Get(url)
return time.Since(start)
}
我在树中创建了第二个目录,我意识到使用 go 包 httptest 的两个文件夹都给了我上面提到的问题中相同的错误
【问题讨论】:
-
racer目录下还有哪些文件?我的意思是那些没有.go扩展的人。 -
错误消息是关于 cgo(编写调用 C 代码的 Go 代码的方式)无法找到 C 编译器。您在上面显示的文件似乎没有使用 cgo,因此我假设某些未显示的依赖项或文件正在使用它。它会在文件顶部显示
import "C"。 -
目录下只有两个文件:
racer.go和racer_test.go -
我需要在哪里导入“C”?我尝试了这两个文件并得到了另一个运行时错误
标签: go testing runtime-error tdd