此外还有很多很好的第三方插件,请到http://plugincompat.herokuapp.com/ 和 https://pypi.python.org/pypi?%3Aaction=search&term=pytest-&submit=search 查找
import pytest
# content of test_sample.py
def func(x):returnx +1def test_answer():
assert func(3) ==5
import pytest
# content of test_class.pyclassTestClass:
def test_one(self):
x="this"assert'h'inx
def test_two(self):
x="hello"assert hasattr(x,'check')
import pytest
# content of test_class.pyclassTestClass:
def test_one(self):
print'one'x="this"assert'h'inx
def test_two(self):
print'two'x="hello"assert hasattr(x,'check')if__name__ =='__main__':
pytest.main("-q --html=a.html")
4、来个支持参数化的例子,参数化使用pytest.mark.parametrize的参数,第一个为变量的元组,第二个是变量赋值的元组列表,具体下面的章节会仔细介绍
# content of test_time.py
import pytestfromdatetime import datetime, timedelta
testdata=[
(datetime(2001,12,12), datetime(2001,12,11), timedelta(1)),
(datetime(2001,12,11), datetime(2001,12,12), timedelta(-1)),
]
@pytest.mark.parametrize("a,b,expected", testdata)
def test_timedistance_v0(a, b, expected):
diff= a -b
assert diff==expected
@pytest.mark.parametrize("a,b,expected", testdata, ids=["forward","backward"])
def test_timedistance_v1(a, b, expected):
diff= a -b
assert diff==expected
def idfn(val):ifisinstance(val, (datetime,)):
# notethiswouldn't show any hours/minutes/secondsreturnval.strftime('%Y%m%d')
@pytest.mark.parametrize("a,b,expected", testdata, ids=idfn)
def test_timedistance_v2(a, b, expected):
diff= a -b
assert diff== expected