【问题标题】:Setter not throwing errors二传手不抛出错误
【发布时间】:2022-01-23 09:01:47
【问题描述】:

我有一个 Node 类,我想确保只接受其他 Node 对象作为其子对象,但在我的单元测试中从未提出 TypeError 。我正在使用 python 3。

class Node:

    def __init__(self, data):
        self._child = None
        self._data = data

    @property
    def child(self):
        return self._child

    @child.setter
    def child(self, child):
        if not isinstance(child, Node):
            raise TypeError(f"Children must be of type Node, not {type(child)}.")
        self._child = child

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data

测试

def test_node_child_error():
    node = Node(1)
    with pytest.raises(TypeError):
        node.child = 2

单元测试返回Failed: DID NOT RAISE <class 'TypeError'>,当我尝试将新值记录到设置器内部的终端时,它说child<class 'NoneType'>,但值确实会根据Node 对象本身而改变当我之后记录它时。

我一直在尝试使用 PyCharm 调试器仔细查看,但不幸的是,我在另一个文件中使用了与调试器中使用的类相同的类名,因此它不再工作了。

【问题讨论】:

  • 测试在我的机器上进行。我在您的代码中发现了两件事,您可以尝试修复它们并重试。在child 设置器中有一个名为right 的变量未定义,self._child 之间有一个空格(无论如何测试都对我有效)。你是如何运行测试的?我通过执行:pytest
  • right 显然应该是child
  • 那些只是复制我的代码的拼写错误。感谢您指出这一点,它们在我的代码中是正确的,并且测试仍然无法正常工作。
  • 无法复制。你确定你在__init__ 中有self._child = None,而不是self.child = None
  • (可以说,self._child = None 是错误的。setter 的重点是确保 self._child 不会收到无效值,并且您通过不使用 @ 中的 setter 来规避这一点987654342@.)

标签: python python-3.x unit-testing typeerror setter


【解决方案1】:

我发现了这个问题,但希望能解释一下为什么/如何解决这个问题。显然,问题出在 setter 每次调用时都会获得 None 类型,因此我将 setter 编辑为如下。

@child.setter
def child(self, child):
    if not isinstance(child, Node) and child is not None:
        raise TypeError(f"Children must be of type Node, not {type(child)}.")
    self._child = child

这不仅修复了我的测试用例,而且现在当我尝试故意抛出错误时,我得到了正确的错误消息 TypeError: Children must be of type Node, not <class 'int'>. 而不是 TypeError: Children must be of type Node, not <class 'None'>.

【讨论】:

  • 查看我对这个问题的评论。但是,如果 _child 属性的预期类型是 Optional[Node] 而不是 Node,则这是一个正确的设置器。
猜你喜欢
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 2021-11-06
  • 2011-05-04
  • 2016-02-23
相关资源
最近更新 更多