首页 > 其他 > 详细

pytest框架之--setup,保证可用的最全的讲解

时间:2021-07-19 22:35:08      阅读:36      评论:0      收藏:0      [点我收藏+]

pytest里面的setup和teardown有以下几种:

  • 模块级(setup_module)开始于模块
import pytest
# 模块中的方法
def setup_module():
    print(
        "setup_module:整个test_module.py模块只执行一次"
    )
# 测试模块中的用例1
def test_one():
    print("正在执行测试模块----test_one")
# 测试模块中的用例2
def test_two():
    print("正在执行测试模块----test_two")

运行结果:

setup_module--》 test_one
setup_module--》 test_two
  • 函数级(setup_function) 只对函数用例生效(不在类中)
#test_Pytest.py文件
#coding=utf-8

import pytest

def setup_function():
        print("setup_function方法执行")

def test_one():
        print("test_one方法执行")
        assert 1==1

def test_two():
        print("test_two方法执行")
        assert "o" in "love"


if __name__=="__main__":
    pytest.main([‘-s‘,‘test_Pytest.py‘])

运行结果

setup_function--》 test_one--》 test_two
  • 类级(setup_class) 只在类中前运行一次(在类中)
import pytest
class TestClass:
 
    def setup_class(self):                    # 仅类开始之前执行一次
        print("---setup_class---")

    def test_one(self):
        print("test_a")
 
    def test_two(self):
        print("test_b")
 
if __name__ == "__main__":
    pytest.main(["-s","pytest_class.py"])

运行结果:

setup_class--》 test_one--》 test_two
  • 方法级(setup_method)开始于方法(在类中)
# coding:utf-8
import pytest

class Test():

    def setup_method(self):
        print(‘setup_method‘)

    def test_one(self):
        print(‘test_one‘)

    def test_two(self):
        print(‘ test_two‘)


if __name__ == ‘__main__‘:
    pytest.main([‘-s‘,‘test_pytest.py‘])

运行结果

setup_method--》 test_one
setup_method--》 test_two
  • 类里面的(setup)运行在调用方法的前
import pytest

def setup():
    print(‘setup‘)

def test_one():
    print(‘test_one‘)

def test_two():
    print(‘test_two‘)

if __name__ == ‘__main__‘:
    pytest.main([‘-s‘,‘test_pytest.py‘])

运行结果

setup--》 test_one
setup--》 test_two

pytest框架之--setup,保证可用的最全的讲解

原文:https://blog.51cto.com/u_13025170/3134205

(0)
(0)
   
举报
评论 一句话评论(0
分享档案
最新文章
教程昨日排行
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!