I have this method called str_to_hexin my common.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
The unittesting method I am writing is
def test_str_to_hex(self):
self.assertEqual(self.common.str_to_hex('test'), '74657374');
self.assertEqual(self.common.str_to_hex(None) , '')
self.assertEqual(self.common.str_to_hex(34234), '')
self.assertEqual(self.common.str_to_hex({'k': 'v'}), '')
self.assertEqual(self.common.str_to_hex([None, 5]), '')
So the first setbacks I got say
TypeError: 'NoneType' object is not iterable
TypeError: 'int' object is not iterable
AssertionError: '6b' != ''
TypeError: ord() expected string of length 1, but NoneType found
Ideally, only text (i.e. stror unicode) should be passed instr_to_hex
To handle empty arguments as input, I modified my code with
def str_to_hex(self, text):
for character in text or '':
So, he passes the second test, but still does not work for the third.
If I use hasattr (text, '__iter__'), it will still fail for tests # 4 and #.
I think the best way is to use Exception. But I am open to suggestions.
Please help me. Thanks in advance.