为什么我的Python代码无法进行单元测试?

时间:2016-10-08 01:27:37

标签: python unit-testing

我有这个挑战:

  

创建一个名为binary_converter的函数。在函数内部,实现一个算法,将0到255之间的十进制数转换为二进制数。

     

对于任何无效输入,返回字符串无效输入

     

示例:对于数字5返回字符串101

单元测试代码在

之下
import unittest


class BinaryConverterTestCases(unittest.TestCase):
  def test_conversion_one(self):
    result = binary_converter(0)
    self.assertEqual(result, '0', msg='Invalid conversion')

  def test_conversion_two(self):
    result = binary_converter(62)
    self.assertEqual(result, '111110', msg='Invalid conversion')

  def test_no_negative_numbers(self):
    result = binary_converter(-1)
    self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')

  def test_no_numbers_above_255(self):
    result = binary_converter(300)
    self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed')

我的代码在下面

def binary_converter(n):

    if(n==0):
        return "0"

    elif(n>255):

        return "invalid input"
    elif(n < 0):
        return "invalid input"
    else:
        ans=""
        while(n>0):
            temp=n%2
            ans=str(temp)+ans
            n=n/2
        return ans

单元测试结果

Total Specs: 4 Total Failures: 2

1. test_no_negative_numbers

    `Failure in line 19, in test_no_negative_numbers self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') AssertionError: Input below 0 not allowed`

2. test_no_numbers_above_255

    `Failure in line 23, in test_no_numbers_above_255 self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') AssertionError: Input above 255 not allowed`

1 个答案:

答案 0 :(得分:2)

比较Python关注案例中的字符串。

>>> 'invalid input' == 'Invalid input'
False

您需要调整测试代码或实现代码,以便字符串文字完全匹配。

def test_no_negative_numbers(self):
    result = binary_converter(-1)
    self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')
                              ^--- (UPPERCASE)

...

elif(n < 0):
    return "invalid input"
            ^--- (lowercase)
相关问题