我目前正在为类编写测试函数,以测试提供的解决方案代码提供的案例。但是我遇到了一个问题,当我不想要它时执行print语句。
这是我正在测试的解决方案:
def alphapinDecode(tone):
phone_num = ''
if checkTone(tone): #or checkTone2
while len(tone) > 0:
# retrieve the first tone
next_tone = tone[0:2]
tone = tone[2:]
# find its position
cons = next_tone[0]
vow = next_tone[1]
num1 = consonants.find(cons)
num2 = vowels.find(vow)
# reconstruct this part of the number -
# multiply (was divided) and add back
# the remainder from the encryption division.
phone = (num1 * 5) + num2
# recreate the number
# by treating it as a string
phone = str(phone)
# if single digit, not leading digit, add 0
if len(phone) == 1 and phone_num != '':
phone = '0' + phone
phone_num = phone_num + phone
# but return in original format
phone_num = int(phone_num)
else:
print('Tone is not in correct format.')
phone_num = -1
return phone_num
这是我编写的测试函数的(部分完成的)代码:
def test_decode(f):
testCases = (
('lo', 43),
('hi', 27),
('bomelela', 3464140),
('bomeluco', 3464408),
('', -1),
('abcd', -1),
('diju', 1234),
)
for i in range(len(testCases)):
if f(testCases[i][0]) == testCases[i][1] and testCases[i][1] == -1:
print('Checking '+ f.__name__ + '(' + testCases[i][0] + ')...Tone is not in correct format.')
print('Its value -1 is correct!')
return None
执行test_decode(alphapinDecode)时,我得到:
Tone is not in correct format.
Checking alphapinDecode()...Tone is not in correct format.
Its value -1 is correct!
Tone is not in correct format.
Checking alphapinDecode(abcd)...Tone is not in correct format.
Its value -1 is correct!
正如你所看到的,由于alphapinDecode中的print语句(我认为),它正在打印一个额外的“Tone格式不正确”。在我写的印刷声明之上。
我如何阻止执行此print语句,如果我在test函数中编写的print语句没有要求alphapinDecode的结果,为什么要打印?
我们不允许更改给定解决方案的代码。
我是stackOverflow的新手,很抱歉任何格式问题。谢谢!
编辑:修复了test_decode函数的标识
一个简单的解决方案是将额外的参数,例如布尔变量调试传递给函数。那会是这样的。
def func1(var1, debug):
if debug:
print("Printing from func1")
# Do additional stuff
现在你打电话的时候。您现在可以选择设置调试变量。
func1("hello", debug=True) # will print the statement
func1("hello", debug=False) # will not print statement.
如果无法修改被调用的函数。然后你可以按照这个方法。由@FakeRainBrigand here解释。
import sys, os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
print 'This will print'
blockPrint()
print "This won't"
enablePrint()
print "This will too"