I have this method called str_to_hex
in 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 that I am writing is
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]), '')
So the first failures that I got say
# 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
Ideally only text (i.e. str
or unicode
) should be passed to str_to_hex
For handling empty args as input I modified my code with
def str_to_hex(self, text):
# .. some code ..
for character in text or '':
# .. some code
So it passes the second test but still fails for the third one.
If I use hasattr(text, '__iter__'), it will still fail for test #4 and #5.
I think the best way is to use an Exception
. But I am open to suggestions.
Please help me out. Thanks in advance.