python - Python:为所有测试方法模拟一次补丁类?
问题描述
考虑这个例子:
模块.py:
class LST:
x = [1]
class T:
def __init__(self, times):
self.times = times
def t1(self):
return LST.x * self.times
def t2(self):
return LST.x * (self.times+1)
def t3(self):
return LST.x * (self.times+2)
测试.py:
from mock import patch
import unittest
import module
@patch('module.LST')
class TestM(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestM, cls).setUpClass()
cls.t = module.T(1)
def test_01(self, LST):
LST.x = [2]
self.assertEqual([2], self.t.t1())
def test_02(self, LST):
LST.x = [2]
self.assertEqual([2, 2], self.t.t2())
def test_03(self, LST):
LST.x = [2]
self.assertEqual([2, 2, 2], self.t.t3())
我只想LST
用补丁修改类一次,因为相同的修改将用于所有测试。
是否可以只修改一次然后将其用于所有方法?所以我不需要LST.x = [2]
在每个方法调用上重复自己吗?
解决方案
怎么样:
from mock import patch
import unittest
import module
class TestM(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestM, cls).setUpClass()
cls.t = module.T(1)
cls.patcher = patch('module.LST')
LST = cls.patcher.start()
LST.x = [2]
@classmethod
def tearDownClass(cls):
cls.patcher.stop()
def test_01(self):
self.assertEqual([2], self.t.t1())
def test_02(self):
self.assertEqual([2, 2], self.t.t2())
def test_03(self):
self.assertEqual([2, 2, 2], self.t.t3())
基本思想是您可以手动控制该修补行为。
推荐阅读
- vuejs2 - 使用 Axios 进行开玩笑测试时出现“请求失败,状态码为 404”错误
- c# - Web API 中间件意外短路
- regex - 在数组中使用 REGEXEXTRACT,搜索多列
- python - 为什么我的 python 串行代码不起作用,而从 arduino 串行监视器发送相同的数据?
- c# - 调试 CLR 挂起
- python - 如何在不导入的情况下从 python 文件中获取函数
- java - 如何在滚动折叠时将 recyclerview 推送到下方(后面)AppbarLayout
- docker - Docker 运行 -v 将卷从 Windows 主机链接到 linux 容器
- actionscript-3 - 如何让定时器倒计时 AS3
- dart - Dart VM 初始化失败:快照不兼容