pytest
入门
安装
pip install pytest
运行
鼠标指向函数右键点击运行
tests\test2.py F # 失败
tests\test1.py . # 成功
测试函数
断言
assert a == b
assert a <= b
跳过测试
@pytest.mark.skip(reason='the code unfinshed')
def test_connect():
pass
@pytest.mark.skipif(version < '0.2.0',
reason='the version must be over 0.2')
def test_api():
pass
参数化
@pytest.mark.parametrize('passwd',
['123456',
'abcdefdfs',
'as52345fasdf4'])
def test_passwd_length(passwd):
assert len(passwd) >= 8
test_parametrize.py
# 多参数
@pytest.mark.parametrize('user, passwd',
[('jack', 'abcdefgh'),
('tom', 'a123456a')])
def test_passwd_md5(user, passwd):
assert len(user)<8 and len(passwd)>=8
Fixture
作用域
@pytest.fixture(scope='function') #函数
def func_scope():
pass
@pytest.fixture(scope='module') #文件
def mod_scope():
pass
@pytest.fixture(scope='session') #会话,最高
def sess_scope():
pass
@pytest.fixture(scope='class')
def class_scope():
pass
预处理
# 无参默认函数级别
@pytest.fixture()
def postcode():
return '010'
#函数调用时先运行 postcode()
def test_postcode(postcode):
assert postcode == '010'
后处理
@pytest.fixture()
def db():
print('Connection successful') #函数执行前调用
yield
print('Connection closed') #函数执行后调用
def search_user(user_id):
d = {
'001': 'xiaoming'
}
return d[user_id]
def test_search(db):
assert search_user('001') == 'xiaoming'
自动执行
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
@pytest.fixture(scope='session', autouse=True)
def timer_session_scope():
start = time.time()
print('\nstart: {}'.format(time.strftime(DATE_FORMAT, time.localtime(start))))
yield
finished = time.time()
print('finished: {}'.format(time.strftime(DATE_FORMAT, time.localtime(finished))))
print('Total time cost: {:.3f}s'.format(finished - start))
@pytest.fixture(autouse=True)
def timer_function_scope():
start = time.time()
yield
print(' Time cost: {:.3f}s'.format(time.time() - start))
def test_1():
time.sleep(1)
def test_2():
time.sleep(2)
============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.6.1, py-1.5.2, pluggy-0.6.0
rootdir: F:\self-repo\learning-pytest, inifile:
collected 2 items
tests\fixture\test_autouse.py
start: 2018-06-12 10:16:27
. Time cost: 1.003s.
. Time cost: 2.003s.
finished: 2018-06-12 10:16:30
Total time cost: 3.016s.
========================== 2 passed in 3.11 seconds ===========================