關於pytest的簡單用法(一)


1.安裝

pip install pytest

2.    pytest 可以運行doctests和unittests

3.    運行pytest

  1. def test_numbers_3_4():
  2. print 'test_numbers_3_4 <============================ actual test code'
  3. assert 3*4 == 12
  4. def test_strings_a_3():
  5. print 'test_strings_a_3 <============================ actual test code'
  6. 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)開始於方法始末(在類中)

代碼:

  1. def setup_module(module):
  2. print ("setup_module module:%s" % module.__name__)
  3. def teardown_module(module):
  4. print ("teardown_module module:%s" % module.__name__)
  5. def setup_function(function):
  6. print ("setup_function function:%s" % function.__name__)
  7. def teardown_function(function):
  8. print ("teardown_function function:%s" % function.__name__)
  9. def test_numbers_3_4():
  10. print 'test_numbers_3_4 <============================ actual test code'
  11. assert 3*4 == 12
  12. def test_strings_a_3():
  13. print 'test_strings_a_3 <============================ actual test code'
  14. assert 'a'*3 == 'aaa'
  15. class TestUM:
  16. def setup(self):
  17. print ("setup class:TestStuff")
  18. def teardown(self):
  19. print ("teardown class:TestStuff")
  20. def setup_class(cls):
  21. print ("setup_class class:%s" % cls.__name__)
  22. def teardown_class(cls):
  23. print ("teardown_class class:%s" % cls.__name__)
  24. def setup_method(self, method):
  25. print ("setup_method method:%s" % method.__name__)
  26. def teardown_method(self, method):
  27. print ("teardown_method method:%s" % method.__name__)
  28. def test_numbers_5_6(self):
  29. print 'test_numbers_5_6 <============================ actual test code'
  30. assert 5*6 == 30
  31. def test_strings_b_2(self):
  32. print 'test_strings_b_2 <============================ actual test code'
  33. 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(也可以自動查找)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章