在不调用类的初始值设定项的情况下测试类

2024-05-17 06:35:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是在不调用其初始值设定项的情况下测试类(因为初始值设定项有一些副作用,我想防止该测试发生)

我可以通过test_1中的代码实现这一点,它本身就可以很好地工作。但是,它似乎以某种方式污染了init/new方法,因为test_2test_1之后运行时失败,原因是:

TypeError: object.__new__() takes exactly one argument (the type to instantiate)

单独运行每个测试时,它们都通过

你知道这里发生了什么吗?我如何解决这个问题,也就是说,在模拟和测试之后如何正确地重置init/new方法

import pytest


# The class to test:
class A:
    def __init__(self, x):
        self.x = x


def test_1(mocker):
    """First test uses the class without triggering the initializer."""
    # Create object without triggering the initializer:
    a = A.__new__(A)
    # Store away the old methods:
    new_orig = A.__new__
    init_orig = A.__init__
    # Mock new/init methods:
    mocker.patch.object(A, "__new__", return_value=a)
    mocker.patch.object(A, "__init__", return_value=None)
    # Do the test:
    res = A()
    # ...
    # Restore new/init methods:
    A.__init__ = init_orig
    A.__new__ = new_orig


def test_2():
    """Second test uses the class as intended."""
    A(2)

Tags: theto方法testselfnewobjectinit
1条回答
网友
1楼 · 发布于 2024-05-17 06:35:01

如果您只想避免调用__init__,那么可以使用以下代码,而无需在__new__中进行修补

import pytest


# The class to test:
class A:
    def __init__(self, x):
        self.x = x


def test_1(mocker):
    """First test uses the class without triggering the initializer."""
    mocker.patch.object(A, "__init__", return_value=None)
    # Do the test:
    res = A()
    with pytest.raises(AttributeError):
        print(res.x)
    # ...


def test_2():
    """Second test uses the class as intended."""
    a = A(2)
    assert(a.x == 2)

也不需要存储新的/init方法

相关问题 更多 >