????7?????????(race detection)
??????????goroutine???????????????????????????goroutine?????????д????????????????????data race????
???????Э?????????bug??Go?????????????????????????
???????????-race???go tool??????????????
????$ go test -race mypkg    // to test the package
????$ go run -race mysrc.go  // to run the source file
????$ go build -race mycmd   // to build the command
????$ go install -race mypkg // to install the package
?????????????????????????
???????????
//testrace.go
package main
import "fmt"
import "time"
func main() {
var i int = 0
go func() {
for {
i++
fmt.Println("subroutine: i = "?? i)
time.Sleep(1 * time.Second)
}
}()
for {
i++
fmt.Println("mainroutine: i = "?? i)
time.Sleep(1 * time.Second)
}
}
$go run -race testrace.go
mainroutine: i =  1
==================
WARNING: DATA RACE
Read by goroutine 5:
main.func·001()
/Users/tony/Test/Go/testrace.go:10 +0×49
Previous write by main goroutine:
main.main()
/Users/tony/Test/Go/testrace.go:17 +0xd5
Goroutine 5 (running) created at:
main.main()
/Users/tony/Test/Go/testrace.go:14 +0xaf
==================
subroutine: i =  2
mainroutine: i =  3
subroutine: i =  4
mainroutine: i =  5
subroutine: i =  6
mainroutine: i =  7
subroutine: i =  8
????8???????????testing with concurrency)
???????????????????????????????sleep??嶯?????????????sleep???????Ч??
????????????????”????“??
??????????????Go????????????Щ?????????sleep?????????????????????
????9????t??????????vet???????
????vet??????????????г???????????????
????– ?????printf???
????– ????????tag
????– ?????????????range???????
????– ???????????
????– ???????????
????– ???????mutex
????????
??????÷?????
????go vet [package]
????10???????????
????golang?д???????????????????????????????????ζ?????????????????δ????????????????????????????????????????
???????????$GOROOT/src/pkg/path/path_test.go??path.go????path????????
????11??????????
??????Щ???????????????????????????в????????????????package foo_test?£?????????package foo???
???????????????????????????磺
????– testing?????fmt
????– fmt????????????????testing??
????– ?????fmt?????????????fmt_test???£?????????????testing???????????????fmt????
????12??Mocks??fakes
?????????????????interface??Go??????????mock??fake????????
???????磬??????????д????????????????????????????????
????func Parser(f *os.File) error
??????????????????д???????interface????????:
????func Parser(r io.Reader) error
??????bytes.Buffer??strings.Reader?????*os.File??????io.Reader????
????13??????????
??????Щ??????????????????????????????????????????????????磺
????func Crasher() {
????fmt.Println("Going down in flames!")
????os.Exit(1)
????}
?????????????????????????????????????????????в????
func TestCrasher(t *testing.T) {
if os.Getenv("BE_CRASHER") == "1" {
Crasher()
return
}
cmd := exec.Command(os.Args[0]?? "-test.run=TestCrasher")
cmd.Env = append(os.Environ()?? "BE_CRASHER=1")
err := cmd.Run()
if e?? ok := err.(*exec.ExitError); ok && !e.Success() {
return
}
t.Fatalf("process ran with err %v?? want exit status 1"?? err)
}