前面介绍的是在cmd中执行pytest,平常我们一般都是通过编译器(如pycharm)来编写用例的,写完用例后,需要调试看看是否能运行,如果每次都切换到cmd中执行,太麻烦。

因此,这一节来说下怎么在代码中执行pytest。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

需要先导入pytest,并通过pytest.main()来执行。

import pytest
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

if __name__ == '__main__':
    pytest.main()

默认是执行当前脚本所在目录下的所有用例。

Pytest学习笔记(三) 在代码中运行pytest 随笔 第1张

当然,也可以加参数来指定运行规则,参数必须放在列表或元组中

import pytest
class TestClass(object):
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

    def test_three(self):
        assert 3 == 5

if __name__ == '__main__':
    pytest.main(['-q','--maxfail=1','test_class.py'])

Pytest学习笔记(三) 在代码中运行pytest 随笔 第2张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄