簡體   English   中英

為什么我的Python代碼未通過單元測試?

[英]Why does my Python code fail 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`

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM