unittest导出html报告的方式有哪些
时间: 2023-08-16 16:06:04 浏览: 86
unittest 可以通过以下方式导出 HTML 报告:
1. 使用 unittest 自带的 HTMLTestRunner 模块,它可以将测试结果以 HTML 报告的形式输出。不过需要注意的是,HTMLTestRunner 模块仅支持 Python 2.x 版本,不支持 Python 3.x 版本。
2. 使用第三方库,如 HTMLTestRunner_PY3、pytest-html、BeautifulReport 等。它们可以在 Python 3.x 中使用,并且提供了更多的功能。
下面是使用 HTMLTestRunner_PY3、pytest-html、BeautifulReport 导出 HTML 报告的示例:
- 使用 HTMLTestRunner_PY3:
```python
import unittest
import HtmlTestRunner
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='example_dir'))
```
- 使用 pytest-html:
```python
import pytest
def test_upper():
assert 'foo'.upper() == 'FOO'
def test_isupper():
assert 'FOO'.isupper()
assert not 'Foo'.isupper()
def test_split():
s = 'hello world'
assert s.split() == ['hello', 'world']
# check that s.split fails when the separator is not a string
with pytest.raises(TypeError):
s.split(2)
```
执行以下命令:
```
pytest --html=report.html
```
- 使用 BeautifulReport:
```python
import unittest
from BeautifulReport import BeautifulReport
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestStringMethods('test_upper'))
suite.addTest(TestStringMethods('test_isupper'))
suite.addTest(TestStringMethods('test_split'))
BeautifulReport(suite).report(filename='example.html', description='example')
```
执行以上测试用例,会在当前目录下生成 HTML 报告文件。