NEWBIE: doctest question

engsolnom at ipns.com engsolnom at ipns.com
Mon Jan 5 22:47:09 CET 2004


I'm trying to learn a bit about the doctest module,
with the goal of incorporating unit test in my
'real' code.

I created a test class, and it works fine, until
I force an error. The results are:

C:\Python23>python myfiles\tst_doctest.py 
*****************************************************************
Failure in example: print obj.s2hex('abcdef')
from line #4 of __main__.Unittest
Expected:
*** Source string too long
None
Got:

*** Source string too long

None
*****************************************************************
1 items had failures:
   1 of   3 in __main__.Unittest
***Test Failed*** 1 failures.

If I remove the prints before and after
print '*** Source string too long'
in s2hex, it works fine, or if I just use:
return '*** Source string too long'
that works OK too. But if I try to compensate
for the pre and post 'print' in the class
doc string for the blank lines, it complains
about that.

The 'None' snows me... it would seem that
on error, the return should be honored,
and the 'return hex_string' should not be.

Is the lesson here to handle exceptions better?

All comments welcome.
Norm

TEST CODE:

class Unittest:

    """
    This class converts an ASCII string to the hex equiv blah blah

    >>> obj = Unittest()
    >>> print obj.s2hex('abcd')
    61626364
    >>> print obj.s2hex('abcdef')
    *** Source string too long
    None
    """

    def __init__(self):
        pass

    def s2hex(self,source):
        hex_string = ''
        if len(source) > 5:
            print
            print '*** Source string too long'
            print
            return
        else:
            for char in source:
                hex_string += '%.2x' % ord(char)
            return hex_string

if __name__ == '__main__':
    import doctest, sys
    doctest.testmod(sys.modules[__name__])





More information about the Python-list mailing list