IT story

Golang에서 코드 커버리지를 측정하는 방법은 무엇입니까?

hot-time 2020. 9. 7. 21:27
반응형

Golang에서 코드 커버리지를 측정하는 방법은 무엇입니까?


Go 단위 테스트를위한 코드 커버리지 생성에 성공한 사람이 있습니까? 웹에서 해당 도구를 찾을 수 없습니다.


참고 로 이동 1.2 (Q4 2013, RC1을 사용할 수는) 이제 표시됩니다 테스트 커버리지 결과 :

의 새로운 주요 기능 중 하나 는 이제 계산할 수 있고 별도로 설치된 새로운 " "프로그램의 도움으로 테스트 범위 결과를 표시 할 수go test 있다는 go tool cover 입니다.

cover도구는 go.tools하위 저장소의 일부입니다 . 실행하여 설치할 수 있습니다.

$ go get golang.org/x/tools/cmd/cover

커버 도구는 두 가지 작업을 수행합니다.

  • 먼저 " go test"에 -cover플래그 가 지정되면 자동으로 실행되어 패키지의 소스를 다시 작성하고 계측 문을 삽입합니다. 그런 다음 테스트가 컴파일되고 평소와 같이 실행되며 기본 커버리지 통계가보고됩니다.
$ go test -coverprofile fmtcoverage.html fmt
ok      fmt 0.060s  coverage: 91.4% of statements
$

둘째,보다 자세한 보고서의 경우 "테스트 진행"에 대한 다양한 플래그가 ""로 호출 된 커버 프로그램이 go tool cover분석 할 수있는 커버리지 프로필 파일을 생성 할 수 있습니다 .

Frank Shearar 다음과 같이 언급합니다 .

최신 버전의 Go (2013/09/19)는 다음을 사용합니다.

go test -coverprofile <filename> <package name>

커버리지 통계를 생성하고 분석하는 방법에 대한 자세한 내용은 명령을 실행하여 찾을 수 있습니다.

$ go help testflag
$ go tool cover -help

Ivan Black 은 의견에서 언급합니다 .

go test -coverprofile cover.out그런 다음 브라우저에서
go tool cover -html=cover.out -o cover.html열립니다 cover.html.

브라우저가 열릴 때까지 기다리지 않기 때문에이 별칭을 정의했습니다.

alias gc=grep -v -e " 1$" coverage.out

그건 난 그냥 입력 gc하고, 모든 라인의 목록이 없습니다 아직 적용 (여기를하십시오에 coverage.out선이 없습니다 "로 끝나는 1").


Go는 테스트 및 적용을위한 멋진 도구와 함께 제공됩니다. 모든 Go 도구는 잘 문서화 되어 있지만 공식 Go 블로그에서 The cover story 기사를go tool cover -help 읽는 것이 좋습니다 . 많은 예제가 있으며 강력히 추천합니다!

이 기능은 ~ / .bash_profile에 있습니다. (단지 터미널에 붙여 넣어 사용해 볼 수 있습니다).

cover () { 
    t="/tmp/go-cover.$$.tmp"
    go test -coverprofile=$t $@ && go tool cover -html=$t && unlink $t
}

그런 다음 cdgo 프로젝트 / 패키지 폴더에 cover. 그러면 현재 패키지의 각 파일에 대해 테스트되고 테스트되지 않은 코드를 보여주는 시각적 도구가 브라우저에 열립니다. 매우 유용한 명령! 아직 100 % 테스트되지 않은 것을 찾기 위해 강력히 추천합니다! 표시된 결과는 파일 당입니다. 왼쪽 상단의 드롭 다운에서 모든 파일에 대한 결과를 볼 수 있습니다.

이 명령을 사용하면 다음과 같은 패키지의 적용 범위를 확인할 수도 있습니다.

cover fmt

이 명령의 터미널 출력은 다음과 같습니다.

ok      fmt 0.031s  coverage: 91.9% of statements

브라우저에서이 도구가 테스트로 다루지 않은 모든 코드 줄이 빨간색으로 표시되는 것을 볼 수 있습니다.

여기에 이미지 설명 입력

It is also possible to just save the html coverage file instead of opening it in a browser. This is very useful in cases when your tests + coverage is run by CI tool like Jenkins. That way you can serve the coverage files from a central server and the whole team will be able to see the coverage results for each build.


It's right here, some docs here.

$ go tool
6a
6c
6g
6l
addr2line
api
cgo
cov
dist
ebnflint
fix
gotype
nm
objdump
pack
pprof
prof
vet
yacc
$ go tool cov -h
usage: cov [-lsv] [-g substring] [-m minlines] [6.out args...]
-g specifies pattern of interesting functions or files
go tool cov: exit status 1
$

I haven't used it, this is all I know.


In addition to the good answers above, I find these three lines to be the simplest way to get it (which includes all packages):

go test -v -coverprofile cover.out ./YOUR_CODE_FOLDER/...
go tool cover -html=cover.out -o cover.html
open cover.html

Note that in the HTML file you will find a dropdown button that will direct you to all files.


If you like to see the uncovered lines by function directly in a terminal I rewrote the cover tool for this purpose. It's available at https://github.com/gregoryv/uncover.

Usage

go get -u github.com/gregoryv/uncover/...
go test -coverprofile /tmp/c.out
uncover /tmp/c.out

Screenshot

여기에 이미지 설명 입력


Inspired by the help menus and other answers to this question, just run:

f=cover.out; if [ -f $f ]; then rm $f; fi; go test ./... -coverprofile $f && \
go tool cover -html $f

Test Coverage for Golang

go get github.com/axw/gocov/gocov go get -u gopkg.in/matm/v1/gocov-html

Check It is Installed Correctly And you have access from your Terminal

Run the Test Case

If you run the test case it will Reder the .json File Based on the file you will get the Code Coverage Report in .html file

gocov test >your_Coverage_report.json

Once Your Test case is done Generate a Report in .html File using .json

gocov-html your_Coverage_report.json >your_Coverage_report.html

Reference

GoTest Coverage Tool for go lang

Go Test Report Tool

Alternate Method

Go Native Test coverage

go test -coverprofile=coverage.out
go tool cover -html=coverage.out

A quick and easy way is to use the coverage tool that comes with built-in go :

$ go test -coverprofile cp.out // Emits the coverage in one liner percentage wise

After you execute the above command, if you wish to visually see the code coverage (like covered statements and missed etc)

$ go tool cover -html=cp.out

Note : You need to execute the above commands in the folder where you wish to see coverage


Try using gaia-docker/base-go-build Docker Image.

This is a Docker image that contains all you need in order to build and test coverage. Running test coverage inside a Docker container creates .cover folder with test coverage results of your project.

docker run --rm -v "$PWD":$PROJECT_PATH -w $PROJECT_PATH $BUILDER_IMAGE_NAME /go/script/coverage.sh

The test coverage script running on all projects' folders and generates, inside .cover folder junit and coverage reports for each folder, and a combine coverage report of all projects' tests.

Codecov also suggests a script that collect coverage results: multiple files


Coverage Report →

a) Run all the tests and enable coverage --> go test ./... -coverprofile coverage.out

b) Get coverage for individual functions as well as overall coverage → go tool cover -func coverage.out

c) See the lines covered and the ones not covered your tests → go tool cover -html=cover.out -o coverage.html Open The coverage.html file hereby generated in the browser and analyze the detailed coverage info.

참고 URL : https://stackoverflow.com/questions/10516662/how-to-measure-code-coverage-in-golang

반응형