最近写Python的测试代码需要用到代码覆盖率,
Coverage安装
$ python -m pip install coverage
除了使用命令行,还可以在python代码中直接调用coverage模块执行代码覆盖率的统计。使用方法也非常简单:
客户端案例代码hello.py
# coding=utf-8
from tornado.web import RequestHandler, Application
import tornado.ioloop
class MainHandler(RequestHandler):
def get(self):
self.write("Hello, world")
class PostMainHandler(RequestHandler):
def post(self):
self.write( "Post arg1: %s, arg2: %s"% (self.get_argument("arg1",""), self.get_argument("arg2","")))
application = Application([
(r"/", MainHandler),(r"/post", PostMainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
服务器端代码test.py
# coding=utf-8
import unittest
from tornado.testing import AsyncHTTPTestCase
from hello import application
import coverage
class TestMain(AsyncHTTPTestCase):
def get_app(self):
return application
def test_main(self):
response = self.fetch('/')
print(response.body)
self.assertEqual(response.code, 200)
self.assertEqual(response.body, b'Hello, world')
def test_post(self):
cov = coverage.coverage(branch=True)
cov.start()
response = self.fetch("/post", method="POST", body="arg1=foo&arg2=bar")
print(response.body)
self.assertEqual(response.code, 200)
self.assertEqual(response.body, b"Post arg1: foo, arg2: bar")
cov.stop()
cov.report(skip_empty=True)
cov.html_report(directory="test-html-result")
#cov.xml_report(outfile="./testresult.xml")
if __name__ == '__main__':
unittest.main()
结果展示

参数介绍
run() – 运行Python程序并且收集执行数据
report() – 报告覆盖率结果
html() – 生成覆盖率结果的HTML列表且带注释
xml() – 生成一份覆盖率结果的XML报告
annotate() – 使用覆盖结果注释源文件
erase() – 擦除以前收集的覆盖率数据
combine() – 将许多数据文件组合在一起
debug() – 获取诊断信息
网友评论