如何将 Golang 测试用例的测试覆盖率值与特定阈值进行比较?

huangapple go评论160阅读模式
英文:

How to compare test-coverage value with specific threshold for Golang test cases

问题

我想获取测试覆盖率并与用户定义的阈值进行比较。我在Makefile中尝试了下面的代码,参考了这个链接1。链接中的代码是写在.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 "请添加更多单元测试或将阈值调整为较低的值。";
echo "失败"
exit 1
else
echo "通过";
fi

即使我的totaltestcoverage为40,它也不会打印任何内容,并且输出结果为"通过"。

有人可以帮我找到更好的方法来获取测试覆盖率并与用户定义的阈值进行比较吗?

提前感谢。

英文:

I want to get the test coverage and compare with user defined threshold. I tried below code in makefile I am referring this link. It is written in .yml file but I am trying to write it in a Makefile.

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

It does not print anything on echo ${totaltestcoverage} and gives answer OK even if my totaltestcoverage is 40.

Can anyone please help me with a better way to get the test coverage and compare with user defined threshold?

Thanks in advance.

答案1

得分: 1

你可以尝试这样做:

  1. .PHONY: lint
  2. testcoverage := $(shell go tool cover -func=coverage.out | grep total | grep -Eo '[0-9]+\.[0-9]+')
  3. threshold = 50
  4. test:
  5. @go test -coverprofile=coverage.out -covermode=count ./...
  6. check-coverage:
  7. @echo "测试覆盖率: $(testcoverage)"
  8. @echo "测试阈值: $(threshold)"
  9. @echo "-----------------------"
  10. @if [ "$(shell echo "$(testcoverage) < $(threshold)" | bc -l)" -eq 1 ]; then \
  11. echo "请添加更多单元测试或将阈值调整为较低的值。"; \
  12. echo "失败"; \
  13. exit 1; \
  14. else \
  15. echo "通过"; \
  16. fi
英文:

You can try this

  1. .PHONY: lint
  2. testcoverage := $(shell go tool cover -func=coverage.out | grep total | grep -Eo &#39;[0-9]+\.[0-9]+&#39;)
  3. threshold = 50
  4. test:
  5. @go test -coverprofile=coverage.out -covermode=count ./...
  6. check-coverage:
  7. @echo &quot;Test coverage: $(testcoverage)&quot;
  8. @echo &quot;Test Threshold: $(threshold)&quot;
  9. @echo &quot;-----------------------&quot;
  10. @if [ &quot;$(shell echo &quot;$(testcoverage) &lt; $(threshold)&quot; | bc -l)&quot; -eq 1 ]; then \
  11. echo &quot;Please add more unit tests or adjust the threshold to a lower value.&quot;; \
  12. echo &quot;Failed&quot;; \
  13. exit 1; \
  14. else \
  15. echo &quot;OK&quot;; \
  16. fi

huangapple
  • 本文由 发表于 2023年6月30日 02:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定