Python:为所有测试方法模拟补丁类一次?

标签 python mocking python-unittest python-mock

考虑这个例子:

模块.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())

基本思想是您可以手动控制修补行为。

关于Python:为所有测试方法模拟补丁类一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603202/

相关文章:

javascript - JEST 模拟是否可能被彼此覆盖?

python - 将测试标记为从 pytest 中的 fixture 内部通过

python - Flask 分页链接格式不正确

python - llvmlite 安装失败。构建 llvmlite 时出错

python - sys.exit 对多线程到底做了什么?

PHPUnit:如何保存传递给 stub 方法的参数

python - 在 python 中访问包含 matlab 类的 .mat 文件

spring-boot - Mockito MockedStatic when() "Cannot resolve method"

python - 如何在 python 中为变量赋值编写单元测试?

python - Unittest 子测试中的局部变量未定义