[英]Python - How do I create a test function by using another function?
I'm having a hard time trying to use another function into a function that tests the function I added with print statements. 我很难尝试将另一个功能用于测试我在打印语句中添加的功能的功能。 For example with this function that reverses a string.
例如,使用此函数可以反转字符串。 I want to use print statements in another function that tests the reverse function, but I'm having a hard time understand how I can incorporate the is_reverse function into the testing function without adding parameters into the testing function.
我想在另一个测试反向函数的函数中使用print语句,但是我很难理解如何将is_reverse函数合并到测试函数中而不在测试函数中添加参数。
def is_reverse( st1, st2 ):
if len( st1 ) != len( st2 ):
return False
i = 0
j = len( st2 ) - 1
while j > 0:
if st1[i] != st2[j]:
return False
i += 1
j -= 1
return True
def test_is_reverse( ):
print( "is_reverse( \"hey\", \"yah\" ) == False.\"" )
print( "is_reverse( \"man\", \"nam\" ) == True.\"" )
One way to do it is to pass the function that you want to use to print the error messages as an argument to the test function. 一种方法是将要用于打印错误消息的函数作为参数传递给测试函数。
Something along the lines of: 类似于以下内容:
def my_print_func (errmsg):
print (errmsg)
def test_is_reverse(f ):
f( "is_reverse( \"hey\", \"yah\" ) == False.\"" )
f( "is_reverse( \"man\", \"nam\" ) == True.\"" )
To test, you do: 要测试,您可以执行以下操作:
test_is_reverse(my_print_func)
That said, you should avoid reinventing the wheel and use Python unittest framework, see https://docs.python.org/2/library/unittest.html 也就是说,您应该避免重新发明轮子并使用Python unittest框架,请参阅https://docs.python.org/2/library/unittest.html
You can setup a function to run your tests and print the results: 您可以设置一个功能来运行测试并打印结果:
def test_is_reverse(st1, st2):
# Define tests here, for example:
print st1, st2, is_reverse(st1,st2), is_reverse(st2, st1)
print is_reverse(st1,st1) == is_reverse(sty, st1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.