One of the methods of my python code does not work for some unittests. How to improve it?

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):
    # 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 setbacks 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. 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):   
    # .. some code ..
    for character in text or '':
    # .. some code

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.

+4
1

, , (a) , , dicts .. (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.
+1

All Articles