title: Python unit tests having unintended side affects on class
body: <p>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.</p>
  <p>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.</p>
  <p>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?</p>
  <p>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:</p>
  <pre><code>def setUp(self):
      &quot;&quot;&quot;
      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)
      &quot;&quot;&quot;
  
      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):
      &quot;&quot;&quot;
      Test that the sample tree returns the correct imbalance
      &quot;&quot;&quot;
      assert_equal(self.A.get_imbalance(), 4, &quot;A has an imbalance of 4&quot;)
      assert_equal(self.C.get_imbalance(), 10, &quot;C has an imbalance of 10&quot;)
      assert_equal(self.D.get_imbalance(), 0, &quot;D has no imbalance&quot;)
      assert_equal(self.B.get_imbalance(), 0, &quot;B has no imbalance&quot;)
  
  def test_update_weight(self):
      &quot;&quot;&quot;
      Test that the sample tree updates the weight correctly
      &quot;&quot;&quot;
      #self.A.update_weight(10)
      assert_equal(self.A.get_imbalance(), 4, &quot;A has an imbalance of 4&quot;)
      assert_equal(self.C.get_imbalance(), 10, &quot;C has an imbalance of 10&quot;)
      assert_equal(self.D.get_imbalance(), 0, &quot;D has no imbalance&quot;)
      assert_equal(self.B.get_imbalance(), 0, &quot;B has no imbalance&quot;)
  </code></pre>
  <p>Exactly the same! But the second yields the default value created in <strong>init</strong> for the relevant var whereas the one above returns the correct value. Hope that gives a better idea.</p>