加入收藏 | 设为首页 | 会员中心 | 我要投稿 西安站长网 (https://www.029zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

Python开发必备:如何建立一个优秀的项目工程环境

发布时间:2019-09-04 05:23:06 所属栏目:建站 来源:虫虫安全
导读:副标题#e# 在程序开发时候一套好的开发环境和工具栈,可以帮我们极大的提高开发的效率,避免把大量时间浪费在周边琐事上。本文以Python为例,教大家如何快速打造优秀的Python项目开发环境:内容涵盖了模块依赖管理、代码风格管理、调试测试管理和Git版本管

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

Python开发必备:如何建立一个优秀的项目工程环境

可以使用pipenv添加测试工具包及扩展:

  1. pipenv install pytest pytest-cov --dev 

Pytest框架可以让编写小测试变得容易,而且支持以扩展的方式提供更加复杂的功能。下面是pytest网站的一个简单示例:

  1. # content of test_sample.py 
  2. def inc(x): 
  3. return x + 1 
  4. def test_answer(): 
  5. assert inc(3) == 5 

通过以下命令测试

  1. pipenv run pytest 

结果如下:

Python开发必备:如何建立一个优秀的项目工程环境

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

Python开发必备:如何建立一个优秀的项目工程环境

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添加配置:

  1. [tool:pytest] 
  2. testpaths=test 

单元覆盖率的项目配置需要创建一个新文件.coveragerc返回应用程序代码的覆盖率统计信息,配置示例如下:

  1. [run] 
  2. source = 项目 
  3. [report] 
  4. exclude_lines = 
  5. pragma: no cover 
  6. def __repr__ 
  7. if self.debug 
  8. raise AssertionError 
  9. raise NotImplementedError 
  10. if 0: 
  11. if __name__ == .__main__.: 

然后再工程中运行一下命令,测试项目的覆盖率

  1. 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测试覆盖率检查:

  1. repos: 
  2. - repo: local 
  3. hooks: 
  4. - id: isort 
  5. name: isort 
  6. stages: [commit] 
  7. language: system 
  8. entry: pipenv run isort 
  9. types: [python] 
  10. - id: black 
  11. name: black 
  12. stages: [commit] 
  13. language: system 
  14. entry: pipenv run black 
  15. types: [python] 
  16. - id: flake8 
  17. name: flake8 
  18. stages: [commit] 
  19. language: system 
  20. entry: pipenv run flake8 
  21. types: [python] 
  22. exclude: setup.py 
  23. - id: mypy 
  24. name: mypy 
  25. stages: [commit] 
  26. language: system 
  27. entry: pipenv run mypy 
  28. types: [python] 
  29. pass_filenames: false 
  30. - id: pytest 
  31. name: pytest 
  32. stages: [commit] 
  33. language: system 
  34. entry: pipenv run pytest 
  35. types: [python] 
  36. - id: pytest-cov 
  37. name: pytest 
  38. stages: [push] 
  39. language: system 
  40. entry: pipenv run pytest --cov --cov-fail-under=100 
  41. types: [python] 

(编辑:西安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读