Symmetric Binary Tree - New Tests by Refactoring

This article is part 4 of the series Symmetric Binary Tree

As always, you should start by writing some test

First, Let's write assert the takes level-based representation, build the tree and then assert that the binary tree is or is not symmetric as expected. This function has almost exactly as tree.symmetric we write before but it is using tree.symmetricA instead of tree.symmetric we want to test.

 def assertSymetricA(self, data: List[Union[int, None]], expected: bool ):
     assert ( tree.symmetricA(data) == expected )

So, we the same function with the function signature. We can create the test by duplicating the code of test_symetric . However, It is not the best practice. A better way is do some refactoring:

  • Let's test_symetric to symetric_test
  • The function should take a callback function assertFunc
  • we should call assertFunc instead of self.assertSymetric
 def symetric_test(self,assertFunc):
     assertFunc([], True)
     assertFunc([0], True)

Now, we can easily write the 2 test functions.

test functions
 def test_symetric(self):

 def test_symetricA(self):

The big advantage of this approach is that we can add and update asserts in one place and they tested in both tests

Let's run the tests again

 FAIL: test_symetricA (tests.symetric.TestSymetric)
 Ran 2 tests in 0.002s

 FAILED (failures=1)    

Yes, One test fails and one successed. This is expected as we did not the code for symetricA.

In the next part, we finished to solve the part 2 of the quiz