I am programming a tree for an assignment. Part of this assignment requires us to update the 'imbalance' of the tree at a Node-level. I have an instance variable 'imbalance' that tracks this for each node. Each time I push to the tree I must update this variable.
When unit-testing this creates a problem: the instance variable is not 'reset' or otherwise has unpredictable behaviour between tests because (I believe) of the way the unit tests cache the class. If I change this variable under the first test it will pass all the assertions but on subsequent tests it will fail because it is persisting between them and causing weird problems. I also have to use a getter to access the imbalance variable from each instance of the node.
I know how to fix this, but unfortunately, I cannot change the unit tests (they are fixed for the assignment) so how do I keep track of this variable and change it without having side affects on other unit tests?
EDIT: ~ full disclosure ~ I'm only sharing this expressly for the purpose of diagnosing issues with the unit tests not to seek out help with the actual data structure. Here's two unit tests that demonstrate the odd issue:
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")
Exactly the same! But the second yields the default value created in init for the relevant var whereas the one above returns the correct value. Hope that gives a better idea.