我正在为一项任务设计一棵树。此作业的一部分要求我们在节点级别更新树的“不平衡”。我有一个实例变量“不平衡”,它跟踪每个节点的情况。每次推入树时,我都必须更新这个变量。
当单元测试产生问题时:实例变量没有“重置”,或者在测试之间有不可预测的行为,因为(我相信)单元测试缓存类的方式。如果我在第一个测试下更改这个变量,它将通过所有断言,但在随后的测试中,它将失败,因为它在它们之间持久化并导致奇怪的问题。我还必须使用getter来访问节点的每个实例中的不平衡变量。
我知道如何解决这个问题,但不幸的是,我不能更改单元测试(它们是为分配而修正的),所以我如何跟踪和更改这个变量而不对其他单元测试产生副作用?
编辑:~完全公开~我只是为了诊断单元测试的问题而明确地分享这个信息,而不是寻求对实际数据结构的帮助。下面两个单元测试演示了奇怪的问题:
def setUp(self):
"""
Set up the tree to be used throughout the test
This is the tree given in the sample
A(5)
/ \
C(2) D(8)
/
B(10)
"""
self.A = Node(5)
self.B = Node(10)
self.C = Node(2)
self.D = Node(8)
self.C.add_left_child(self.B)
self.A.add_left_child(self.C)
self.A.add_right_child(self.D)
def test_get_imbalance(self):
"""
Test that the sample tree returns the correct imbalance
"""
assert_equal(self.A.get_imbalance(), 4, "A has an imbalance of 4")
assert_equal(self.C.get_imbalance(), 10, "C has an imbalance of 10")
assert_equal(self.D.get_imbalance(), 0, "D has no imbalance")
assert_equal(self.B.get_imbalance(), 0, "B has no imbalance")
def test_update_weight(self):
"""
Test that the sample tree updates the weight correctly
"""
#self.A.update_weight(10)
assert_equal(self.A.get_imbalance(), 4, "A has an imbalance of 4")
assert_equal(self.C.get_imbalance(), 10, "C has an imbalance of 10")
assert_equal(self.D.get_imbalance(), 0, "D has no imbalance")
assert_equal(self.B.get_imbalance(), 0, "B has no imbalance")完全一样!但是第二个值产生了在init中为相关的var创建的默认值,而上面的那个则返回正确的值。希望这能给你一个更好的想法。
发布于 2022-03-27 12:07:07
在setUp中,您可能希望使用深拷贝保存原始节点。
import copy
A_prime = copy.deepcopy(A)现在,如果A的值发生了变化,A_prime将不受影响。(因为它完全是一个新对象)
https://stackoverflow.com/questions/71635847
复制相似问题