Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

golang 实时获取测试覆盖率 #26

Open
myml opened this issue Aug 11, 2019 · 0 comments
Open

golang 实时获取测试覆盖率 #26

myml opened this issue Aug 11, 2019 · 0 comments
Labels

Comments

@myml
Copy link
Owner

myml commented Aug 11, 2019

使用未导出字段

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"reflect"
	"sync"
	"testing"
	"unsafe"
)

func TestRunMain(t *testing.T) {
	main()
}

func TestMain(m *testing.M) {
	flag.Set("test.coverprofile", "c.out")

	mux := http.NewServeMux()
	mux.HandleFunc("/coverprofile", func(resp http.ResponseWriter, req *http.Request) {
		log.Printf("coverage %v", testing.Coverage())
	})
	mux.HandleFunc("/shutdown", func(resp http.ResponseWriter, req *http.Request) {
		err := srv.Shutdown(context.TODO())
		if err != nil {
			fmt.Fprint(resp, err)
			resp.WriteHeader(500)
		}
	})
	go func() {
		for {
			code := m.Run()
			log.Println("code", code)

			v := reflect.ValueOf(m).Elem()
			afterOnce := v.FieldByName("afterOnce")
			afterOnce = reflect.NewAt(afterOnce.Type(), unsafe.Pointer(afterOnce.UnsafeAddr())).Elem()
			afterOnce.Set(reflect.ValueOf(sync.Once{}))
		}
	}()
	http.ListenAndServe(":9222", mux)
}

使用未导出函数

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/http"
	"testing"
	_ "unsafe"
)

//go:linkname coverReport testing.coverReport
func coverReport()

func TestRunMain(t *testing.T) {
	main()
}

func TestMain(m *testing.M) {
	flag.Set("test.coverprofile", "c.out")

	mux := http.NewServeMux()
	mux.HandleFunc("/coverprofile", func(resp http.ResponseWriter, req *http.Request) {
		log.Printf("coverage %v", testing.Coverage())
	})
	mux.HandleFunc("/coverReport", func(resp http.ResponseWriter, req *http.Request) {
		coverReport()
	})
	mux.HandleFunc("/shutdown", func(resp http.ResponseWriter, req *http.Request) {
		err := srv.Shutdown(context.TODO())
		if err != nil {
			fmt.Fprint(resp, err)
			resp.WriteHeader(500)
		}
	})
	go func() {
		m.Run()
	}()
	http.ListenAndServe(":9222", mux)
}
@myml myml added the golang label Aug 11, 2019
@myml myml changed the title golang 测试覆盖率 golang 即时获取测试覆盖率 Dec 10, 2021
@myml myml changed the title golang 即时获取测试覆盖率 golang 实时获取测试覆盖率 Dec 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant