Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Python doctest with plotting

Is there a way or trick to pass doctest, when output is matplotlib object? Doctest framework I also use for examples of code (not only for testing output)

So my problem looks like this:

    plt.plot(grid, pdf); plt.title('Random Normal 1D using Kernel1D.kde function'); plt.grid(); plt.show()
Expected nothing
Got:
    [<matplotlib.lines.Line2D object at 0x00000208BDA8E2B0>]
    Text(0.5, 1.0, 'Random Normal 1D using Kernel1D.kde function')

What I would like to happen, is to pass doctest when I plot anything. Thanks.

like image 216
Alex Avatar asked Dec 05 '25 08:12

Alex


1 Answers

You can use doctest.ELLIPSIS to make a string match to anything.

Your code will still show problems in the plt.show() if you want to avoid seeing the plots and go directly to the report of the evaluation. For that you can use doctest.SKIP. Check the following example:

import matplotlib.pyplot as plt

def test():
    """
    Code example:

    >>> 1 + 1
    2
    >>> plt.plot([1, 2, 3])
    [...
    >>> plt.show() #doctest: +SKIP
    >>> plt.close()
    """
    pass

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)

This returns the following report:

Trying:
    1 + 1
Expecting:
    2
ok
Trying:
    plt.plot([1, 2, 3])
Expecting:
    [...
ok
Trying:
    plt.close()
Expecting nothing
ok
1 items had no tests:
    __main__
1 items passed all tests:
   3 tests in __main__.test
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
like image 156
armatita Avatar answered Dec 06 '25 22:12

armatita



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!