我有一种执行以下操作的方法。问题是如何对该方法进行单元测试。我对这个Python单元测试模块非常陌生。
问题和解决方案如下:
Given a string containing of ‘0’, ‘1’ and ‘?’ wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by ‘0’ or ‘1’.
Example :
Input str = "1??0?101"
Output:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
解决方案:
def _print(string, index):
if index == len(string):
print(''.join(string))
return
if string[index] == "?":
# replace '?' by '0' and recurse
string[index] = '0'
_print(string, index + 1)
# replace '?' by '1' and recurse
string[index] = '1'
_print(string, index + 1)
# NOTE: Need to backtrack as string
# is passed by reference to the
# function
string[index] = '?'
else:
_print(string, index + 1)
# Driver code
if __name__ == "__main__":
string = "1??0?101"
string = list(string) #don’t forget to convert to string
_print(string, 0)
输出:
10000101
10001101
10100101
10101101
11000101
11001101
11100101
11101101
问题:
1。另外,有没有一种方法可以返回列表而不是将其打印出来?
2。在这种情况下,哪些断言测试用例合适?
3。在这种情况下,涵盖的最佳端到端测试用例是什么?
我尝试了这似乎不起作用:
import unittest
from wildcard import _print
class TestWildCard(unittest.TestCase):
def test_0_print(self):
print("Start wildCard _print test: \n")
result = 111
self.assertEquals(_print("1?1",0),result,"Results match")
答案:
1:确定,不要打印任何内容,而是将结果附加到列表result.append('some value')
上,不要忘记在代码result = []
的开头初始化列表,并在函数完成后返回它return result
-并且可能不会调用函数_print
,但是会调用bit_strings
。
ad 1:由于您的函数是递归的,所以现在您还需要捕获返回值,并在递归调用该函数时将其添加到结果中,因此result += _print(string, index + 1)
2:您通常应该考虑边缘情况并单独测试它们,或者将那些确实测试功能单个方面的情况组合在一起。没有一种方法可以说明测试的外观-如果有,测试框架只会为您生成它。
3:与2相同的答案。
您的代码将成为:
def bit_strings(s, index):
result = []
if index == len(s):
result.append(''.join(s))
return result
if s[index] == "?":
# replace '?' by '0' and recurse
s[index] = '0'
result += bit_strings(s, index + 1)
# replace '?' by '1' and recurse
s[index] = '1'
result += bit_strings(s, index + 1)
# NOTE: Need to backtrack as string
# is passed by reference to the
# function
s[index] = '?'
else:
result += bit_strings(s, index + 1)
return result
# Driver code
if __name__ == "__main__":
x = "1??0?101"
xl = list(x) #don’t forget to convert to string
print(bit_strings(xl, 0))
有更有效的方法,但是我只是根据问题和答案修改了您的代码。
我将string
重命名为s
,因为string
有点令人困惑,让其他人想起了这种类型,或者遮盖了(内置)模块。
关于单元测试:
import unittest
from wildcard import bit_strings
class TestWildCard(unittest.TestCase):
def test_0_print(self):
print("Start wildCard _print test: \n")
# you only had one case here and it's a list now
result = ['101', '111']
# user assertEqual, not Equals
# you were passing in a string, but your code assumed a list, so list() added
self.assertEqual(bit_strings(list("1?1"), 0), result, "Results match")
[在使用PyCharm之类的环境时,它有助于调用文件test<something>.py
(即,名称中具有test
,以便帮助您更轻松地运行单元测试。