前言
用過unittest的童鞋都知道,有兩個前置方法,兩個后置方法;分別是
- setup()
- setupclass()
- teardown()
- teardownclass()
pytest也貼心的提供了類似setup、teardown的方法,并且還超過四個,一共有十種
- 模塊級別:setup_module、teardown_module
- 函數級別:setup_function、teardown_function,不在類中的方法
- 類級別:setup_class、teardown_class
- 方法級別:setup_method、teardown_method
- 方法細化級別:setup、teardown
代碼
用過unittest的童鞋,對這個前置、后置方法應該不陌生了,我們直接來看代碼和運行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = __time__ = 2020-04-06 11:40 __author__ = 小菠蘿測試筆記 __blog__ = https://www.cnblogs.com/poloyy/ """ import pytest def setup_module(): print ( "=====整個.py模塊開始前只執行一次:打開瀏覽器=====" ) def teardown_module(): print ( "=====整個.py模塊結束后只執行一次:關閉瀏覽器=====" ) def setup_function(): print ( "===每個函數級別用例開始前都執行setup_function===" ) def teardown_function(): print ( "===每個函數級別用例結束后都執行teardown_function====" ) def test_one(): print ( "one" ) def test_two(): print ( "two" ) class testcase(): def setup_class( self ): print ( "====整個測試類開始前只執行一次setup_class====" ) def teardown_class( self ): print ( "====整個測試類結束后只執行一次teardown_class====" ) def setup_method( self ): print ( "==類里面每個用例執行前都會執行setup_method==" ) def teardown_method( self ): print ( "==類里面每個用例結束后都會執行teardown_method==" ) def setup( self ): print ( "=類里面每個用例執行前都會執行setup=" ) def teardown( self ): print ( "=類里面每個用例結束后都會執行teardown=" ) def test_three( self ): print ( "three" ) |
1
2
3
4
5
6
|
def test_four( self ): print ( "four" ) if __name__ = = '__main__' : pytest.main([ "-q" , "-s" , "-ra" , "setup_teardown.py" ]) |
執行結果
到此這篇關于pytest實現setup和teardown的詳細使用詳解的文章就介紹到這了,更多相關pytest setup和teardown內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/poloyy/p/12641991.html