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

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

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.

.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

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

你可以尝试这样做:

.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 "测试覆盖率: $(testcoverage)"
	@echo "测试阈值: $(threshold)"
	@echo "-----------------------"

	@if [ "$(shell echo "$(testcoverage) < $(threshold)" | bc -l)" -eq 1 ]; then \
		echo "请添加更多单元测试或将阈值调整为较低的值。"; \
		echo "失败"; \
		exit 1; \
	else \
		echo "通过"; \
	fi
英文:

You can try this

.PHONY: lint

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

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

check-coverage:
	@echo &quot;Test coverage: $(testcoverage)&quot;
	@echo &quot;Test Threshold: $(threshold)&quot;
	@echo &quot;-----------------------&quot;

	@if [ &quot;$(shell echo &quot;$(testcoverage) &lt; $(threshold)&quot; | bc -l)&quot; -eq 1 ]; then \
		echo &quot;Please add more unit tests or adjust the threshold to a lower value.&quot;; \
		echo &quot;Failed&quot;; \
		exit 1; \
	else \
		echo &quot;OK&quot;; \
	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:

确定