我有一个 Python 项目,它使用 pytest-cov 进行单元测试和代码覆盖率测量。
我的项目的目录结构是:
rift-python
+- rift # The package under test
| +- __init__.py
| +- __main__.py
| +- cli_listen_handler.py
| +- cli_session_handler.py
| +- table.py
| +- ...lots more...
+- tests # The tests
| +- test_table.py
| +- test_sys_2n_l0_l1.py
| +- ...more...
+- README.md
+- .travis.yml
+- ...
我使用 Travis 运行pytest --cov=rift tests
每次签入,并使用 codecov 查看代码覆盖率结果。
被测包提供了一个命令行界面(CLI),它从标准输入读取命令并在标准输出上产生输出。它以python rift
.
测试目录包含两种类型的测试。
第一类测试是测试单个类的传统单元测试。例如,测试 test_table.py 导入 table.py,并执行传统的 pytest 测试(使用 assert 等)。代码覆盖率测量对这些测试按预期工作:codecov 准确报告 rift 包中的哪些行被或未被覆盖测试。
# test_table.py (codecov works)
import table
def test_simple_table():
tab = table.Table()
tab.add_row(['Animal', 'Legs'])
tab.add_rows([['Ant', 6]])
...
tab_str = tab.to_string()
assert (tab_str == "+--------+------+\n"
"| Animal | Legs |\n"
"+--------+------+\n"
"| Ant | 6 |\n"
"+--------+------+\n"
...
"+--------+------+\n")
第二种测试使用 pexpect:它用于pexpect.spawn("python rift")
启动 rift 包。然后它pexpect.sendline
用于将命令注入 CLI (stdin) 并用于pexpect.expect
检查 CLI (stdout) 上命令的输出。测试功能运行良好,但 codecov 没有报告这些测试的代码覆盖率。
# test_sys_2n_l0_l1.py (codecov does not pick up coverage of rift package)
# Greatly simplified example
import pexpect
def test_basic():
rift = pexpect.spawn("python rift")
rift.sendline("cli command")
rift.expect("expected output") # Throws exception if expected output not seen
问题:如何获得代码覆盖率测量结果以报告生成的裂痕包中的覆盖线,以使用 pexpect 进行第二类测试?
注意:我省略了几个我认为不相关的细节,完整的源代码在https://github.com/brunorijsman/rift-python(更新:这个 repo 现在包含答案中建议的工作解决方案)