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