当前位置: 动力学知识库 > 问答 > 编程问答 >

Why does my Python code fail unit testing?

问题描述:

I have this challenge:

Create a function called binary_converter. Inside the function, implement an algorithm to convert decimal numbers between 0 and 255 to their binary equivalents.

For any invalid input, return string Invalid input

Example: For number 5 return string 101

Unit test code is below

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')

my code goes below

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

Unit test results

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`

网友答案:

Comparing strings in Python cares cases.

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

You need to adjust test code or implementation code so that string literals matches exactly.

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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: