stiga
stiga

Reputation: 7

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`

Upvotes: 1

Views: 226

Answers (1)

falsetru
falsetru

Reputation: 369064

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)

Upvotes: 2

Related Questions