1、用例編寫規則python
1.unittest提供了test cases、test suites、test fixtures、test runner相關的類,讓測試更加明確、方便、可控。使用unittest編寫用例,必須遵照如下規則:session
(1)測試文件必須先import unittest框架
(2)測試類必須繼承unittest.TestCase函數
(3)測試方法必須以「test_」開頭測試
(4)測試類必需要有unittest.main()方法ui
2.pytest是python的第三方測試框架,是基於unittest的擴展框架,比unittest更簡潔,更高效。使用pytest編寫用例,必須遵照如下規則:spa
(1)測試文件名必須以「test_」開頭或者"_test"結尾(如:test_ab.py)插件
(2)測試方法必須以「test_」開頭。code
(3)測試類命名以"Test"開頭。繼承
總結: unittest :用例格式--複雜,不能兼容pytest用例;
pytest: 用例格式--簡單,能夠兼容unittest用例;
2、用例前置和後置
1.unittest提供了setUp/tearDown,只能針對全部用例。
2.pytest提供了模塊級、函數級、類級、方法級的setup/teardown,比unittest的setUp/tearDown更靈活。
模塊級(setup_module/teardown_module)開始於模塊始末,全局的
函數級(setup_function/teardown_function)只對函數用例生效(不在類中)
類級(setup_class/teardown_class)只在類中先後運行一次(在類中)
方法級(setup_method/teardown_method)開始於方法始末(在類中)
類裏面的(setup/teardown)運行在調用方法的先後
pytest還能夠在函數前加@pytest.fixture()裝飾器,在測試用例中使用fixture函數。fixture的使用範圍能夠是function,module,class,session。
firture相對於setup和teardown來講有如下幾點優點:
3、斷言
1.unittest提供了assertEqual、assertIn、assertTrue、assertFalse。
2.pytest直接使用assert 表達式。
4、報告
1.unittest使用HTMLTestRunnerNew庫。
2.pytest有pytest-HTML、allure插件。
5、失敗重跑
一、unittest無此功能。
二、pytest支持用例執行失敗重跑,pytest-rerunfailures插件。
6、參數化
一、unittest需依賴ddt庫,
二、pytest直接使用 @pytest.mark.parametrize 裝飾器。