Python3完全新手小白的学习手册 12代码测试
文章目录
- 使用pip安装pytest
- 清华源使用
- 安装pytest
- 测试函数
- 单元测试和测试用例
因为代码是人写的,只要有人参与的事物都会出现错误,所以每个程序员都必须经常测试自己的代码,先于用户发现自己的问题。
本章将学习pytest模块,如何使用pytest模块。pytest模块,不仅能帮助你快速而轻松地编写测试,而且能持续支持随项目增大而变得复杂的测试。
Python 默认不包含 pytest,因此你将学习如何安装外部库。
使用pip安装pytest
因为pip服务器在国外,使用默认pip源会很慢,所以这里推荐使用清华源安装,在国内的体验会比较快。因为阿里源的使用文档没有更新,使用方法有问题。所以这里推荐使用清华源。
清华源使用
临时使用
pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple 包名或者模块名
复制中文前的内容,到系统终端让后+空格+包名或者模块名,就可以使用清华源下载pip模块或者包了。
这里并不推荐将清华源改为默认源,因为镜像源有同步延迟的问题,使用镜像源未必能保证是最新版本的模块。
安装pytest
使用清华源安装代码
pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple pytest
只要复制上面的代码到系统终端中回车运行就可以安装pytest了
测试函数
这是一个普通方法,就是将被测试的方法。
def get_formatted_name(first, last):"""生成格式规范的姓名"""full_name = f"{first} {last}"return full_name.title()
使用上面那个方法的代码
from name_function import get_formatted_nameprint("输入q退出")
while True:first = input("请输入第一个名字")if first == "q":breaklast = input("请输入第二个名字")if last == "q":breakformatted_name = get_formatted_name(first, last)print(f"formatted_name name:{formatted_name}")
以上还没有开始设计单元测试的的内容,都还是使用常规的方式在进行测试。
使用方法进行测试函数。
单元测试和测试用例
测试文件的名称很重要,必须以 test_打头。当你让 pytest 运行测试时,它将查找以 test_打头的文件,并运行其中的所有测试。
test_name_function.py
from name_function import get_formatted_namedef test_first_name():formatted_name = get_formatted_name("Janis", "Joplin")assert formatted_name == 'Janis Joplin'
第一,测试函数必须以test_ 打头。在测试过程中,pytest 将找出并运行所有以 test_ 打头的函数。第二,测试函数的名称应该比典型的函数名更长,更具描述性。
断言(assertion)就是声称满足特定的条件:这里声称 formatted_name 的值为 ‘Janis Joplin’。