我有一個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'>,當我嘗試將新值記錄到 setter 內部的終端時,它說child是<class 'NoneType'>,但是Node當我之后記錄它時,該值確實根據物件本身而改變。
我一直在嘗試使用 PyCharm 除錯器來仔細查看,但不幸的是,我在另一個檔案中使用了與除錯器中使用的類相同的類名,因此它不再起作用。
uj5u.com熱心網友回復:
我發現了這個問題,但希望能解釋一下為什么/如何解決這個問題。顯然,問題出在 setterNone每次被呼叫時都會得到一個型別,所以我將 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'>..
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/393324.html
標籤:Python 蟒蛇-3.x 单元测试 类型错误 二传手
上一篇:提高用資料填充熊貓資料框的速度
