一、pytest安装
二、pytest API
三、pytest example
创建第一个test
新建项目,新建文件test.py
写入四行代码:
import pytest
def func(x):
return x + 1
def test_func():
assert func(3) == 5
在cmd执行命令:
pytest C:\Users\xxxx\xxxx\src\test.py
得到如下结果:
test抓取异常
《pytest会运行当前目录及子目录中所有test_*.py or *_test.py格式的文件》
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
cmd运行:
pytest C:\Users\xxxx\xxxx\src\test.py
结果:
1 passed in 0.12s
把test集成的class中:
import pytest
class TestClass:
def testone(self):
x = 'this'
assert 'h' in x
def testtwo(self):
x = 'hello'
assert hasattr(x, "check")
命令:
pytest C:\Users\xxxx\xxxx\src\test.py
结果:
申请一个临时目录用于功能测试
代码:
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
命令:
pytest C:\Users\xxxx\xxxx\src\test.py
结果: