doctest redundant mock class instantiations

mde at micahelliott.com mde at micahelliott.com
Fri Oct 24 20:16:50 EDT 2008


I'm wondering if there is a "best practice" for *creating doctests in
methods* that reduces clutter/duplication of dummy instantiations.  In
the following code there are five (labeled 1-5) possible places to put
a
dummy mock instantiation.  I have the impression that creating the
dummies in every method is the common practice (1-3), but I'm hoping
otherwise.  I've found that creating the dummy down by the testmod
call
obviates the need to do any of the other (1-5) instantiations.

Doctests are written so concisely in *functions* (x6), but they are
tedious in *methods* due the redundant creation of dummies.  This
tedium
makes me prefer writing functions over methods, but I hate to
sacrifice on design.

It seems that __init__ is the most intuitive place to put a single
instantiation (#1), but alas, that doesn't work as it's not visible to
#2,3.  Next best would be in the module-level docstring (#5); also no
dice.  #2,3 are tedious.  The #4 approach works okay; is there any
problem with adopting this (#4) approach as a convention?  Is there a
better way, to make it more like what's possible in functions?

    """
    >>> mockSM = SillyMult()  # 5
    """

    class SillyMult(object):
        def __init__(self):
            """
            >>> mockSM = SillyMult()  # 1
            """
            pass
        def x2(self, x):
            """
            >>> mockSM = SillyMult()  # 2
            >>> mockSM.x2(2)
            4
            """
            return x*2

        def x3(self, x):
            """
            >>> mockSM = SillyMult()  # 3
            >>> mockSM.x3(2)
            6
            """
            return x*3

    def x6(x):
        """
        >>> x6(2)  # 6
        12
        """
        return x*6

    if __name__ == '__main__':
        import doctest
        #mockSM = SillyMult()  # 4
        doctest.testmod()
~

--
Micah Elliott  |  http://MicahElliott.blogspot.com  |  @MicahElliott



More information about the Python-list mailing list