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

2024-04-26 00:01:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的中有一个名为str_to_hex的方法普通.py

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(文本,''uu iter''),测试4和5仍然会失败。你知道吗

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

请帮帮我。提前谢谢。你知道吗


Tags: to方法texttestselfforstringfailure
1条回答
网友
1楼 · 发布于 2024-04-26 00:01:23

首先,您需要决定是(a)为无效的输入(如列表、dict等)静默地返回空字符串,还是(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.

相关问题 更多 >

    热门问题