Home > Back-end >  How to automatically generate unit testing routines from special syntax in method docstring / commen
How to automatically generate unit testing routines from special syntax in method docstring / commen

Time:05-31

This is a mock-up of what I'm looking for:

def is_even(a, b):
    """Returns True if both numbers are even.
    @AutoUnitTestTag:
    - (0,2) -> True
    - (2,1) -> False
    - (3,5) -> False
    """
    return (a % 2 == 0 and b % 2 == 0)

Is there a tool that could allow one to insert compact syntax-defined unit tests within a function's docstring and then automatically generate a unittest_foobar.py unit testing routine?

I'm almost sure I've seen this a while ago, but cannot find it.

EDIT: @mkrieger1 suggested doctest in the comments below and after playing a bit with it, I'd say it's a pretty apt solution. However, I'd like to let this question linger a bit longer in order to collect more suggestions, especially about more sophisticated tools.

If someone's interested, here's how one would use doctest in my example case:

  1. Format function in file is_even.py like so:
def is_even(a,b):
    """Returns True if both numbers are even.
    >>> is_even(0,2)
    True
    >>> is_even(2,1)
    False
    >>> is_even(3,5)
    False
    """
    return (a % 2 == 0 and b % 2 == 0)
  1. Then run the command python3 -m doctest is_even.py. The output will look like so:
Trying:
    is_even(0,2)
Expecting:
    True
ok
Trying:
    is_even(2,1)
Expecting:
    False
ok
Trying:
    is_even(3,5)
Expecting:
    False
ok
1 items had no tests:
    foo2
1 items passed all tests:
   3 tests in foo2.is_even
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

CodePudding user response:

It's called doctest and it's part of the standard library. But you'll have to change your syntax a bit:

def is_even(a, b):
    """Returns True if both numbers are even.

    >>> is_even(0, 2)
    True
    >>> is_even(2, 1)
    False
    >>> is_even(3, 5)
    False
    """
    return (a % 2 == 0 and b % 2 == 0)

You can run it with:

python -m doctest is_even.py

The syntax has been designed so that you can mostly copy and paste your tests from an interactive (C)Python interpreter session, so there is good reason not to try and change it. Moreover, other Python developers will already be familiar with this syntax, and not with anything custom you might come up with.

  • Related