我的 python 代码中的一种方法在某些单元测试中失败。我该如何改进它?

One of the method from my python code fails for some unittests. How do I improve it?

我的 common.py

中有一个名为 str_to_hex 的方法
def str_to_hex(self, text):
    self.log.info('str_to_hex :: text=%s' % text)
    hex_string = ''
    for character in text:
        hex_string += ('%x' % ord(character)).ljust(2, '0') 
    self.log.info('str_to_hex; hex = %s' % hex_string)
    return hex_string

我写的单元测试方法是

def test_str_to_hex(self):
    # test 1
    self.assertEqual(self.common.str_to_hex('test'), '74657374');
    # test 2
    self.assertEqual(self.common.str_to_hex(None) , '')
    # test 3
    self.assertEqual(self.common.str_to_hex(34234), '')
    # test 4
    self.assertEqual(self.common.str_to_hex({'k': 'v'}), '')
    # test 5  
    self.assertEqual(self.common.str_to_hex([None, 5]), '')

所以我说的第一个失败

# failure 1 (for test 2)
TypeError: 'NoneType' object is not iterable
# failure 2 (for test 3)
TypeError: 'int' object is not iterable
# failure 3 (for test 4)
AssertionError: '6b' != ''
# failure 4 (for test 5)
TypeError: ord() expected string of length 1, but NoneType found

理想情况下,只应将文本(即 strunicode)传递给 str_to_hex

为了处理空参数作为输入,我修改了我的代码

def str_to_hex(self, text):   
    # .. some code ..
    for character in text or '':
    # .. some code

所以它通过了第二次测试,但第三次仍然失败。

如果我使用 hasattr(text, '__iter__'),测试 #4 和 #5 仍然会失败。

我认为最好的方法是使用 Exception。但我愿意接受建议。

请帮帮我。提前致谢。

首先,您需要决定是否要 (a) 静默 return 清空无效输入的字符串,例如列表、字典等。或者 (b) 您实际上可以提出适当的异常,只希望您的测试能够处理这些问题。

对于 (a),您可以使您的函数本身对传递的内容更具防御性:

def str_to_hex(self, text):
    if not isinstance(text, basestring):
        return ''
    # rest of code

对于选项 (b),您可以更改测试预期以匹配正在发生的情况:

with self.assertRaises(TypeError):
    self.common.str_to_hex(None)
# etc.