首先说下为何要学pytest,在此以前相信你们已经掌握了python里面的unittest单元测试框架,那再学一个框架确定是须要学习时间成本的。 刚开始个人心里是拒绝的,我想我用unittest也能完成自动化测试,干吗要去学pytest呢?最近看到愈来愈多的招聘要求会pytest框架了,也有小伙伴出去面试说会unittest框架被鄙视的。 因此学此框架应该至少有如下2个理由,第一条已经足够:html
python鄙视链:pytest 鄙视 > unittest 鄙视 > robotframework 鄙视 > 记流水帐 鄙视 > "hello world"小白python
pytest是python的一种单元测试框架,与python自带的unittest测试框架相似,可是比unittest框架使用起来更简洁,效率更高。根据pytest的官方网站介绍,它具备以下特色:面试
1.安装方法session
pip install -U pytest框架
2.pip show pytest查看安装版本函数
pip show pytest工具
3.也能够pytest --version查看安装的版本单元测试
pytest --version学习
This is pytest version 3.6.3, imported from d:\soft\python3.6\lib\site-packages\ pytest.py
1.新建一个test_sample.py文件,写如下代码测试
# content of test_sample.py def func(x): return x +1 def test_answer(): assert func(3)==5
2.打开test_sample.py所在的文件夹,cmd窗口输入:pytest(或者输入py.test也能够)
D:\YOYO>pytest ============================= test session starts ============================= platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0 rootdir: D:\YOYO, inifile: collected 1 item test_sample.py F [100%] ================================== FAILURES =================================== _________________________________ test_answer _________________________________ def test_answer(): > assert func(3)==5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:6: AssertionError ========================== 1 failed in 0.19 seconds ===========================
3.pytest运行规则:查找当前目录及其子目录下以test_*.py或*_test.py文件,找到文件后,在文件中找到以test开头函数并执行。
1.前面是写的一个test开头的测试函数,当用例用多个的时候,写函数就不太合适了。这时能够把多个测试用例,写到一个测试类里。
# test_class.py class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check')
2.pytest会找到符合规则(test_.py和_test.py)全部测试,所以它发现两个test_前缀功能。 若是只想运行其中一个,能够指定传递文件名test_class.py来运行模块: 备注: -q, --quiet decrease verbosity( 显示简单结果)
py.test -q test_class.py
D:\YOYO>py.test -q test_class.py .F [100%] ================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________ self = <test_class.TestClass object at 0x00000000039F1828> def test_two(self): x = "hello" > assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check') test_class.py:11: AssertionError 1 failed, 1 passed in 0.04 seconds
第一次测试经过,第二次测试失败。 您能够在断言中轻松查看失败的缘由。
__init__
方法---------------------------------pytest结合selenium自动化完整版-------------------------
全书购买地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b
做者:上海-悠悠 QQ交流群:874033608
也能够关注下个人我的公众号:yoyoketang