Advertisement
Guest User

Untitled

a guest
Mar 24th, 2023
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. Can you write a unit test to test the code you just wrote?
  2.  
  3. Sure, here's an example unit test in Python using the built-in unittest module:
  4.  
  5. import unittest
  6.  
  7. class TestValidateTree(unittest.TestCase):
  8. def test_valid_tree(self):
  9. # Valid tree with 1 as root and 2 and 3 as children
  10. nodes = [{'val': 1, 'left': 2, 'right': 3}, {'val': 2, 'left': None, 'right': None}, {'val': 3, 'left': None, 'right': None}]
  11. self.assertTrue(validate_tree(nodes))
  12.  
  13. # Valid tree with 5 as root and 2 and 7 as children
  14. nodes = [{'val': 5, 'left': 2, 'right': 7}, {'val': 2, 'left': None, 'right': None}, {'val': 7, 'left': None, 'right': None}]
  15. self.assertTrue(validate_tree(nodes))
  16.  
  17. def test_invalid_tree(self):
  18. # Invalid tree with two root nodes
  19. nodes = [{'val': 1, 'left': None, 'right': None}, {'val': 2, 'left': None, 'right': None}, {'val': 3, 'left': None, 'right': None}]
  20. self.assertFalse(validate_tree(nodes))
  21.  
  22. # Invalid tree with a node having two children, but no parent
  23. nodes = [{'val': 1, 'left': None, 'right': 2}, {'val': 3, 'left': None, 'right': None}, {'val': 2, 'left': 4, 'right': 5},
  24. {'val': 4, 'left': None, 'right': None}, {'val': 5, 'left': None, 'right': None}]
  25. self.assertFalse(validate_tree(nodes))
  26.  
  27. # Invalid tree with a node having only one child, but no parent
  28. nodes = [{'val': 1, 'left': None, 'right': 2}, {'val': 3, 'left': None, 'right': None}, {'val': 2, 'left': None, 'right': None},
  29. {'val': 4, 'left': None, 'right': None}]
  30. self.assertFalse(validate_tree(nodes))
  31.  
  32. if __name__ == '__main__':
  33. unittest.main()
  34. The test class TestValidateTree defines two test methods, test_valid_tree and test_invalid_tree , which test whether the validate_tree function correctly identifies a valid binary tree (i.e., one root node and no loops) and invalid binary trees (i.e., multiple root nodes, nodes with two children but no parent, and nodes with only one child but no parent).
  35.  
  36. The test_valid_tree method creates two valid binary trees with different node values and children, and calls the validate_tree function with the tree nodes. The method asserts that the validate_tree function returns True for these valid trees.
  37.  
  38. The test_invalid_tree method creates three invalid binary trees, one with two root nodes, one with a node having two children but no parent, and one with a node having only one child but no parent. The method calls the validate_tree function with these trees and asserts that the function returns False .
  39.  
  40. Finally, the unittest.main() call runs the test case.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement