关于pytest的简单用法(一)

1.安装

       pip install pytest

2.    pytest 可以运行doctests和unittests

3.    运行pytest

def test_numbers_3_4():
    print 'test_numbers_3_4  <============================ actual test code'
    assert 3*4 == 12


def test_strings_a_3():
    print 'test_strings_a_3  <============================ actual test code'
    assert 'a'*3 == 'aaa'

切换到文件的当前目录运行python –m pytest test_num.py或者py.test test_num.py

用-v运行(-v显示运行的函数)python –m pytest –v test_num.py或者py.test –v test_num.py,

用-s运行显示内部的打印信息

4.    pytest的setup和teardown函数

1)模块级(setup_module/teardown_module)开始于模块始末

2)类级(setup_class/teardown_class)开始于类的始末

3)类里面的(setup/teardown)(运行在调用函数的前后)

4)功能级(setup_function/teardown_function)开始于功能函数始末(不在类中)

5)方法级(setup_method/teardown_method)开始于方法始末(在类中)

代码:

def setup_module(module):
    print ("setup_module      module:%s" % module.__name__)


def teardown_module(module):
    print ("teardown_module   module:%s" % module.__name__)


def setup_function(function):
    print ("setup_function    function:%s" % function.__name__)


def teardown_function(function):
    print ("teardown_function function:%s" % function.__name__)


def test_numbers_3_4():
    print 'test_numbers_3_4  <============================ actual test code'
    assert 3*4 == 12


def test_strings_a_3():
    print 'test_strings_a_3  <============================ actual test code'
    assert 'a'*3 == 'aaa'


class TestUM:
    def setup(self):
        print ("setup             class:TestStuff")

    def teardown(self):
        print ("teardown          class:TestStuff")

    def setup_class(cls):
        print ("setup_class       class:%s" % cls.__name__)

    def teardown_class(cls):
        print ("teardown_class    class:%s" % cls.__name__)

    def setup_method(self, method):
        print ("setup_method      method:%s" % method.__name__)

    def teardown_method(self, method):
        print ("teardown_method   method:%s" % method.__name__)

    def test_numbers_5_6(self):
        print 'test_numbers_5_6  <============================ actual test code'
        assert 5*6 == 30

    def test_strings_b_2(self):
        print 'test_strings_b_2  <============================ actual test code'
        assert 'b'*2 == 'bb'


输出:

 

5.    pytest可以自动查找module和文件中的测试用例,甚至unittests和doctests

module和function,method以‘test_’开头,class以‘Test’开头,文件中的话确保存在__init__.py文件

6.    pytest 运行unittests,py.test  test_unittest.py(也可以自动查找)

 

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值