【问题标题】:Need help writing test case for this code需要帮助为此代码编写测试用例
【发布时间】:2019-01-21 10:10:58
【问题描述】:

如何在不使用任何外部库的情况下为这段代码编写测试用例?

Python 程序将输入的字符串反转,同时将特殊字符保持在同一位置

    #Returns true if x is an alphabetic character, false otherwise
    def isAlphabet(x):
        return x.isalpha()

    def reverse_string(input_str):
        LIST = toList(input_str)

        #Initialize left and right pointers
        r = len(LIST) - 1
        l = 0

        #Traverse LIST from both ends until 'l' and 'r'
        while l < r:


            #Ignore special characters
            if not isAlphabet(LIST[l]):
                l += 1
            elif not isAlphabet(LIST[r]):
                r -= 1

            #Both LIST[l] and LIST[r] are not special 
            else:
                LIST[l], LIST[r] = swap(LIST[l], LIST[r])
                l += 1
                r -= 1

        return toString(LIST)

    # Utility functions 
    def toList(input_str): 
        List = [] 
        for i in input_str: 
            List.append(i) 
        return List

    def toString(List): 
        return ''.join(List) 

    def swap(a, b): 
        return b, a 

    # Driver code 
    input_str = "adfc_#sin*"
    print "Input string: " + input_str
    input_str = reverse_string(input_str) 
    print "Output string: " + input_str


    input_str = "hon()lo&"
    print "Input string: " + input_str
    input_str = reverse_string(input_str) 
    print "Output string: " + input_str

【问题讨论】:

  • 到目前为止你尝试过什么?考虑一些输入字符串,手动执行算法,然后将这些输入/输出元组放入您的测试中应该不会太难
  • 我只写了程序。我是单元测试的新手。你能举个例子说明如何解决这个问题吗?
  • 欢迎来到 *!在这里,您可以① 发布您的代码(作为minimal reproducible example),② 描述您观察到的代码(使用哪个输入),以及 ③ 描述您希望观察到的内容。这导致了一个可以回答的明确问题。请拨打tour 并阅读How-To-Ask 以了解更多信息。
  • 我会引导您使用 Python 内置函数 unit testing framework。非常方便。

标签: python testing


【解决方案1】:

试试这个:

input_str = "1234#as"
wanted_output = "sa#4321"

cur_output = reverse_string(input_str)

print("Input: ", input_str, "Output OK?", cur_output==wanted_output)

或者这样:

assert cur_output==wanted_output

【讨论】:

  • 特殊字符不在同一位置
  • 对不起!我只是想展示将预期结果与实际结果进行比较的方式。
最近更新 更多