我的python代码中的一个方法对于某些单元测试失败了.我该如何改
发布时间:2020-12-20 13:48:15 所属栏目:Python 来源:网络整理
导读:我的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 = %
我的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 理想情况下,只应将文本(即str或unicode)传递给str_to_hex 为了处理空args作为输入我修改了我的代码 def str_to_hex(self,text): # .. some code .. for character in text or '': # .. some code 所以它通过了第二次测试,但仍然没有通过第三次测试. 如果我使用hasattr(text,’__ item__’),测试#4和#5仍然会失败. 我认为最好的方法是使用Exception.但我愿意接受建议. 请帮帮我.提前致谢. 解决方法
首先,您需要决定是否要(a)静默返回空字符串以获取无效输入,例如列表,字符串等.或者(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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |