Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python代码中的一个方法在某些单元测试中失败。我如何改进它?_Python_Python Unittest - Fatal编程技术网

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

python代码中的一个方法在某些单元测试中失败。我如何改进它?,python,python-unittest,Python,Python Unittest,我在我的common.py中有一个名为str\u to\u 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_h

我在我的common.py中有一个名为
str\u to\u 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
理想情况下,只能将文本(即
str
unicode
)传递给
str\u to\u hex

为了将空参数作为输入进行处理,我用

def str_to_hex(self, text):   
    # .. some code ..
    for character in text or '':
    # .. some code
因此,它通过了第二次测试,但第三次测试仍然失败

如果我使用(文本“iter”),它仍然会在测试4和5中失败

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


请帮帮我。提前感谢。

首先,您需要决定是(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.

此外,您是否测试其他数据类型(例如dict或list)作为方法的输入?如果是的话,如何避免把焦点从主要逻辑上移开?这是一个很好的观点。如果它只包含
char
,它将适用于
列表。e、 g.[a',b',c']。但是关于
dict
和其他列表呢?修改了问题“为什么您想要空字符串而不是异常?”?这似乎只会隐藏错误,并使您之后处理此代码的人员感到困惑。@user2357112是的,在不同的情况下,理想情况下,它应该抛出不同类型的
异常
。我已经看到一些文本具有datatype=
unicode
(例如
u'á'
)。对于这样的文本,测试会失败吗?我刚刚尝试了针对选项(a)的
self.assertEqual(self.common.str_to_hex(u'á'),'')
,但是它失败了,因为
AssertionError
basestring
将允许unicode和普通字符串通过。如果您想禁止unicode,只需将其更改为
isinstance(text,str)
。是。没错。我的测试应该是self.assertEqual(self.common.str_to_hex(u'á'),'e1')
。对不起:(我认为选项A不起作用。选项B不是一个真正的选项。它没有解释我们应该在主代码中做什么。这里
基串
起作用,但在很多地方它不会起作用。你会不会最后加入
语句,比如
isinstance(x1)或isinstance(x2)
??如果您这样做,我认为我们更多地关注测试代码而不是主逻辑,因为超过一半的代码行实际上只是捕获异常并抛出它们。这只是测试类型的代码(我将调用的无用部分),因为主测试逻辑不在其中。