2.pytest_用例设计和运行规则

用例设计原则

  • 文件名以test_*.py文件和*_test.py
  • test_开头的函数
  • Test开头的类
  • test_开头的方法
  • 所有的包pakege必须要有__init__.py文件

help帮助

1.查看pytest命令行参数,可以用pytest -h 或pytest --help查看

D:YOYO\
    __init__.py
    
    test_class.py
        #  content of  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')
                
            def test_three(self):
                a = "hello"
                b = "hello world"
                assert a in b
            
    test_sample.py
        #  content of  test_sample.py
        def func(x):
            return x +1
    
        def test_answer():
            assert func(3)==5


执行测试用例

cmd执行pytest用例有三种方法,以下三种方法都可以,一般推荐第一个

  • pytest
  • py.test
  • python -m pytest

如果不带参数,在某个文件夹下执行时,它会查找该文件夹下所有的符合条件的用例(查看用例设计原则)

执行用例规则

1.执行某个目录下所有的用例

pytest 文件名/

2.执行某一个py文件下用例

pytest 脚本名称.py

3.-k 按关键字匹配

pytest -k "MyClass and not method"

这将运行包含与给定字符串表达式匹配的名称的测试,其中包括Python
使用文件名,类名和函数名作为变量的运算符。 上面的例子将运行
TestMyClass.test_something但不运行TestMyClass.test_method_simple

-x 遇到错误时停止测试

pytest -x test_class.py

从运行结果可以看出,本来有3个用例,第二个用例失败后就没继续往下执行了

class TestClass:
    def test_one(self):
        x = "wwj"
        assert 'x' in x
    def test_two(self):
        x=4
        assert 2+2 == x

运行结果:

E:\workspace\python\0510APIDemo\pytestDemo>pytest -x test_cl
ass.py
=================== test session starts ===================
platform win32 -- Python 3.7.4, pytest-5.4.3, py-1.9.0, plug
gy-0.13.1
rootdir: E:\workspace\python\0510APIDemo\pytestDemo
collected 2 items                                          

test_class.py F

======================== FAILURES =========================
___________________ TestClass.test_one ____________________

self = <test_class.TestClass object at 0x000002B3B74B7648>

    def test_one(self):
        x = "wwj"
>       assert 'x' in x
E       AssertionError: assert 'x' in 'wwj'

test_class.py:4: AssertionError
================= short test summary info =================
FAILED test_class.py::TestClass::test_one - AssertionErro...

!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!
==================== 1 failed in 0.27s ====================

错误数量达到某个数量就停止执行

--maxfail=num
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值