2
\$\begingroup\$

The doctest module seemed easy to implement so I decided to write a simpler version of it.

my_doctest.py

def _doublets(lst):
    for index, item in enumerate(lst[:-1]):
        yield item, lst[index+1]

def _test(tests):
    for prev, curr in _doublets(tests.splitlines()):
        if prev.strip().startswith('>>>'):
            code = prev.replace('>>>','').strip()
            if not eval(code) == eval(curr):
                raise AssertionError("{} should be {} but got {}".format(
                    code, eval(curr.strip()), eval(code)))

def doctest(func):
    _test(func.__doc__)

def testmod(module_name=None):
    with open(module_name or __file__) as f:
        _test(f.read())

add.py

import my_doctest as doctest

def add(a, b):
    """
    >>> add(1,3)
    4
    >>> add(2,5) # I should study more Math ...
    8
    """
    return a + b

doctest.testmod()
\$\endgroup\$
2
\$\begingroup\$

I don't think your parser is careful and general enough.

Where in testmod() does it say that it should consider only docstrings?

Also, what happens if the expected output is empty or more than one line? You also aren't handling code that spans multiple lines, with ... leaders.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.