I recently started to play again with go, and my task at the moment is to implement a service (that will run on k8s) that should act as a gRPC server.
As per requirements, at the moment, I need to implement an healthcheck endpoint for my service, and this should be tested: what I've done is:
func main() {
server := startHTTPServer()
defer server.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
<-c
log.Println("Stopped")
}
func startHTTPServer() *http.Server {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
server := &http.Server{
Addr: net.JoinHostPort("", strconv.Itoa(livelinessPort)),
}
go server.ListenAndServe()
return server
}
and I tested in this way, following this article:
func TestMain(m *testing.M) {
flag.Parse()
wg := setup()
result := m.Run()
shutdown(wg)
os.Exit(result)
}
func shutdown(wg *sync.WaitGroup) {
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
wg.Wait()
}
func setup() *sync.WaitGroup{
os.Setenv("APP_ENV", EnvTest)
wg := &sync.WaitGroup{}
startMainProcess(wg)
return wg
}
func startMainProcess(wg *sync.WaitGroup) {
go func() {
wg.Add(1)
defer wg.Done()
main()
}()
}
func TestK8SHealth(t *testing.T) {
res, err := http.Get("http://:8080/")
if err != nil {
t.Errorf("Unexpected API error: %s", err)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("Unexpected status code: %d", res.StatusCode)
return
}
}
and so far so good:
$ go test
PASS
2018/08/13 09:23:16 Stopped
ok github.com/... 0.015s
Te problem is when I try to add the gRPC server in the main application, following gPRC go examples. I've added this to my main file
func main() {
[...]
startChecksServiceServer()
[...]
}
func startChecksServiceServer() *grpc.Server {
flag.Parse()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", serverPort))
if err != nil {
log.Fatalf("Starting gPRC server error: failed to listen port %d: %v", serverPort, err)
}
grpcServer := grpc.NewServer()
pb.RegisterChecksServiceServer(grpcServer, &checksServiceServer{})
grpcServer.Serve(lis)
log.Println("Started grpc server")
return grpcServer
}
but now when I run the test, it fails after the actual test was run, when the interrupt signal is sent.
$ go test
PASS
signal: interrupt
FAIL github.com/... 0.016s
I made some tests and this is not depending by the actual test (as it pass with a test function that just return
, and it's working while running the test suite using goLand:
GOROOT=/usr/local/go #gosetup
GOPATH=/Users/marco/Documents/projects/go #gosetup
/usr/local/go/bin/go test -c -i -o /private/var/folders/jh/znhv9f090yb7y390dckb23s00000gn/T/[...] #gosetup
/usr/local/go/bin/go tool test2json -t /private/var/folders/jh/znhv9f090yb7y390dckb23s00000gn/T/[...] -test.v -test.run
^TestK8SHealth$ #gosetup
=== RUN TestK8SHealth
--- PASS: TestK8SHealth (0.00s)
PASS
Process finished with exit code 1
Aucun commentaire:
Enregistrer un commentaire