如何比较Golang测试用例的测试覆盖值与特定阈值

zujrkrfu  于 2023-08-01  发布在  Go
关注(0)|答案(1)|浏览(122)

我想获得测试覆盖率并与用户定义的阈值进行比较。我尝试了下面的代码在makefile我指的是这个link。它是写在.yml文件,但我试图写在一个Makefile。

.PHONY: lint    
testcoverage=$(go tool cover -func coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
echo ${testcoverage}
if (${testcoverage} -lt 50 ); then \
  echo "Please add more unit tests or adjust threshold to a lower value."; \
  echo "Failed"
  exit 1
else \
  echo "OK"; \
fi

字符串
它不会在echo ${totaltestcoverage}上打印任何内容,即使我的totaltestcoverage是40,它也会给出OK的答案。
任何人都可以请帮助我一个更好的方法来获得测试覆盖率和比较与用户定义的阈值?
先谢谢你。

rhfm7lfc

rhfm7lfc1#

你可以试试这个

.PHONY: lint

testcoverage := $(shell go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
threshold = 50

test:
    @go test -coverprofile=coverage.out -covermode=count  ./...

check-coverage:
    @echo "Test coverage: $(testcoverage)"
    @echo "Test Threshold: $(threshold)"
    @echo "-----------------------"

    @if [ "$(shell echo "$(testcoverage) < $(threshold)" | bc -l)" -eq 1 ]; then \
        echo "Please add more unit tests or adjust the threshold to a lower value."; \
        echo "Failed"; \
        exit 1; \
    else \
        echo "OK"; \
    fi

字符串

相关问题