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 –vtest_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(也可以自动查找)