|
程序开发中,除了写代码外,另外一个重要的部分是单元测试。Python测试方面我们要介绍的工具有pytest。

可以使用pipenv添加测试工具包及扩展:
- pipenv install pytest pytest-cov --dev
Pytest框架可以让编写小测试变得容易,而且支持以扩展的方式提供更加复杂的功能。下面是pytest网站的一个简单示例:
- # content of test_sample.py
- def inc(x):
- return x + 1
- def test_answer():
- assert inc(3) == 5
通过以下命令测试
- pipenv run pytest
结果如下:

pytest-cov是pytest的单元测试行覆盖率的插件。pytets-cov的测试结果示例如下:

pytest还有很多的扩展插件:
pytest-cov: 单元测试覆盖率报告
pytest-django: 对Django框架的单元测框架
pytest-asyncio:对asyncio的支持
pytest-twisted: 对twisted框架的单元测框架
pytest-instafail: 发送错误时报告错误信息
pytest-bdd 测试驱动开发工具
pytest-konira 测试驱动开发工具
pytest-timeout: 支持超时功能
pytest-pep8: 支持PEP8检查
pytest-flakes: 结合pyflakes进行代码检查
更多插件可以查看github pytest-dev组织下的项目。
项目配置
项目中,所有的测试都应该放在test目录中,我需要给setup.cfg添加配置:
- [tool:pytest]
- testpaths=test
单元覆盖率的项目配置需要创建一个新文件.coveragerc返回应用程序代码的覆盖率统计信息,配置示例如下:
- [run]
- source = 项目
- [report]
- exclude_lines =
- pragma: no cover
- def __repr__
- if self.debug
- raise AssertionError
- raise NotImplementedError
- if 0:
- if __name__ == .__main__.:
然后再工程中运行一下命令,测试项目的覆盖率
- pipenv run pytest --cov --cov-fail-under =100
如果程序代码的测试覆盖率低于100%,就会报错。
Git pre-commit hook规范检查
Git hook可以让我们在提交或推送时执行检查脚本,脚本可以配置对项目镜像测试或者规范性检查。运行脚本。我们可以配置pre-commit hook允许轻松配置这些钩子,下面.pre-commit-config.yaml配置示例可以帮我们自动做代码规范化,包括isort检查、black检查、flake8检查、mypy静态类型检查、pytest测试、pytest-cov测试覆盖率检查:
- repos:
- - repo: local
- hooks:
- - id: isort
- name: isort
- stages: [commit]
- language: system
- entry: pipenv run isort
- types: [python]
- - id: black
- name: black
- stages: [commit]
- language: system
- entry: pipenv run black
- types: [python]
- - id: flake8
- name: flake8
- stages: [commit]
- language: system
- entry: pipenv run flake8
- types: [python]
- exclude: setup.py
- - id: mypy
- name: mypy
- stages: [commit]
- language: system
- entry: pipenv run mypy
- types: [python]
- pass_filenames: false
- - id: pytest
- name: pytest
- stages: [commit]
- language: system
- entry: pipenv run pytest
- types: [python]
- - id: pytest-cov
- name: pytest
- stages: [push]
- language: system
- entry: pipenv run pytest --cov --cov-fail-under=100
- types: [python]
(编辑:成都站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|