Python: 模拟补丁 class 对所有测试方法一次?
Python: mock patch class once for all test methods?
考虑这个例子:
module.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)
test.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
class 一次,因为相同的修改将用于所有测试。
是否可以只修改一次然后对所有方法重复使用?所以我不需要在每次方法调用时重复 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())
基本思想是您可以手动控制修补行为。
考虑这个例子:
module.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)
test.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
class 一次,因为相同的修改将用于所有测试。
是否可以只修改一次然后对所有方法重复使用?所以我不需要在每次方法调用时重复 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())
基本思想是您可以手动控制修补行为。