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


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