我有一个在python中遍历二叉树并打印其节点的函数:
def preorder(tree: BinaryTree) -> None:
"""
Preorder recursive implementation
:param tree: passed binary tree object
:return: None
"""
if tree:
print(tree.get_root_val())
preorder(tree.get_left_child())
preorder(tree.get_right_child())
我如何编写单元测试来测试此功能?
您可以根据定义函数preorder()
的方式对其进行测试,例如打印节点的函数(内置函数),返回带有节点的字符串的函数(UDF函数)。对于打印节点的功能,这是我使用patch
中的unittest.mock
进行测试的方法:
from io import StringIO
import unittest
from unittest.mock import patch
#First, we create the Tree class:
class Tree():
def __init__(self, l, iz ,der ):
self.label = l #Label or value
self.left = iz #Left child
self.right = der #Right child
#We define the preorder function:
def preorder(tree):
if isinstance(tree, Tree): #Optional conditional
print(tree.label)
preorder(tree.left)
preorder(tree.right)
#We create 3 trees for the test:
P = Tree('p',None, None )
Q = Tree('q',None,P )
R = Tree('r', P, Q)
#We start the test:
class TestPreorder(unittest.TestCase):
def test(self):
with patch('sys.stdout', new = StringIO()) as preorderOutput: #we get the output of the function
preorder(P)
self.assertEqual(preorderOutput.getvalue(), 'p\n') #We make the test for the tree P
#We erase what's in the stdout. In this case we have 'p\n'
preorderOutput.truncate(0)
preorderOutput.seek(0)
#We make the test for th tree Q
preorder(Q)
self.assertEqual(preorderOutput.getvalue(), 'q\np\n')
#Again we erase what's in the stdout. In this case we have 'q\np\n'
preorderOutput.truncate(0)
preorderOutput.seek(0)
#Finally, we make the test for th tree R
preorder(R)
self.assertEqual(preorderOutput.getvalue(), 'r\np\nq\np\n')
#this is so that when running the code on the console, you can run it as 'python test.py' instead of 'python -m unittest.py'
if __name__ == '__main__':
unittest.main()
现在,不处理控制台输出的更好方法是定义函数以字符串形式返回节点的值(UDF函数),然后可以轻松对其进行测试。创建该功能后,可以在此unittest
中选中link。