一、创建一个test脚本
首先创建一个**.py**文件叫做test_sample.py,包含一个测试类,两个测试函数
class TestClass:
def test_one(self):
x = 'this'
assert 'h' in x
def test_two(self):
x = 'hello'
assert hasattr(x, 'check')
二、如何运行这个测试脚本
1. 使用Pycharm
Pycharm运行代码的方式有三种:
- 以xx.py脚本方式直接执行,当写的代码里面没用到unittest和pytest框架时,并且脚本名称不是以test_开头命名的,此时pycharm会以xx.py脚本方式运行;
- 当脚本命名为test_xx.py时,用到unittest框架,此时运行代码,pycharm会自动识别到以unittest方式运行;
- 以pytest方式运行,需要改该工程设置默认的运行器:file->Setting->Tools->Python Integrated Tools->项目名称->Default test runner->选择py.test
所以,当我们直接在Pycharm中运行上面脚本时,Pycharm会直接给出脚本的运行结果;
2. 使用pytest命令运行
当安装完成pytest包后,会生成一个叫pytest的命令。当在cmd中运行这个命令时,会自动执行该文件夹、以及该文件夹的子文件夹下所有以test_*.py or \*_test.py形式命名的文件。当然,也可以指定具体的测试用例,使用方法如下。
2.1 指定运行测试用例文件
pytest test_sample.py
2.2 在目录下执行测试用例
pytest testing/
2.3 运行一个测试类
pytest testing/test_sample.py::TestClass
2.4 运行一个测试用例
pytest testing/test_sample.py::TestClass::test_one