Write the test in a python docstring

The doctest.testmod () function of the doctest module describes the test in the docstring and runs it in verbose mode to execute the test.

Where I used to write

sample.py


def twice(n):
    """A function that doubles the argument and returns
    >>> twice(8)
    16
    >>> twice(1850923)
    """
    return n * 2


'''TEST
twice(8)
 #Execution result
 #16
twice(1850923)
 #Execution result
 #3701846
'''#← Triple quotes here'TEST'By pulling up to the place where it is written, twice(8), twice(1850923)To run

If you raise the triple quote under TEST to TEST, the docstring-like multi-line comment out will be removed, and when executed, the twice function will be executed and tested. That TEST is below the function, so it looks bad. I want to put it together in a docstring if possible.

Use the doctest module

However, if you use the doctest module, you can write it in the docstring, and you can do dexterity that does not execute when executed from other modules.

doctest_sample.py


def twice(n):
    """A function that doubles the argument and returns
    >>> twice(8)
    16
    >>> twice(1850923)
    3701846
    """
    return n * 2


print('name?>>', __name__)
if __name__ == "__main__":
    doctest.testmod()

print('EOF')

Verify the execution result by the following four methods

  1. ipython
    1. %run doctest_sample -v
    2. %run doctest_use.py -v
  2. sublimetext
  3. Run doctest_sample.py on sublime text
  4. Run doctest_use.py.py on sublime text

Just import the contents of doctest_use.py.py

import doctest_sample
```

When running a python file on ipython, run it with'% run '. When using doctest.testmod (), execute it in verbose mode -v.

When executing on sublime text, build with ctrl + b. Execution of verbose mode is not included by default (whether it is false or true or not verified), so create a build system and save it in the User directory Select Python_Verbose created from Menu> Tools> Buile system and ctrl + b

Python_Verbose.sublime-build


{
    "cmd": ["python", "$file", "-v"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

About command line options -u and -v

1 Command line and environment (http://docs.python.jp/3.3/using/cmdline.html) 1.1 Command line 1.1.3 Other options

-u¶ (original)

Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console, or block-buffered if redirected to a non-interactive file.

See also PYTHONUNBUFFERED.

-v

Each time a module is initialized, it displays a message telling you where it was loaded (filename or built-in module). If specified twice (-vv), a message will be displayed for each file checked when searching for modules. It also provides information about module cleanup on exit. See also PYTHONVERBOSE.

Result 1.1 % run doctest_sample -v on ipython

1.1


In [80]: run doctest_sample.py -v
name?>> __main__
Trying:
    twice(8)
Expecting:
    16
ok
Trying:
    twice(1850923)
Expecting:
    3701846
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.twice
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
EOF

Since the name attribute is main, doctest is executed The description of doctest is Execute in python format where you wrote > >> and return the result If there are no errors, issue ʻok` and proceed to the next test.

1.1


Trying:
    twice(8)
Expecting:
    16
ok

View test summary

1.1


1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.twice
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
body...

Result 1.2 % run doctest_use -v on ipython

1.2


In [81]: run doctest_use.py

No output is displayed.

Result 2.1 Build doctest_sample.py on sublime text

2.1


name?>> __main__
Trying:
    twice(8)
Expecting:
    16
ok
Trying:
    twice(1850923)
Expecting:
    3701846
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.twice
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
EOF
[Finished in 0.5s]

Same as 1.1 result except [Finished in 0.5s] that appears in sublime text build result

Result 2.2 Build doctest_use.py on sublime text

2.2


name?>> doctest_sample
EOF
[Finished in 0.4s]

Unlike result 1.2, the print statement seems to be executed.

Summary

doc.py


import docstring

def hoge():
    '''
    hoge(args)
    '''


if __name__ == "__main__":
    doctest.testmod()

reference

Test with Python Command line and environment

Recommended Posts

Write the test in a python docstring
I want to write in Python! (2) Let's write a test
Write a log-scale histogram on the x-axis in python
Write a binary search in Python
Write a table-driven test in C
Write A * (A-star) algorithm in Python
Write selenium test code in python
Write a pie chart in Python
Write a vim plugin in Python
Write a depth-first search in Python
To write a test in Go, first design the interface
Write a short property definition in Python
Run the Python interpreter in a script
Write a Caesar cipher program in Python
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
Write Python in MySQL
Create a Vim + Python test environment in 1 minute
[Python] Get the files in a folder with Python
Get the caller of a function in Python
Make a copy of the list in Python
Set up a test SMTP server in Python.
The trick to write flatten concisely in python
Output in the form of a python array
[Python] Find the transposed matrix in a comprehension
Test & Debug Tips: Create a file of the specified size in Python
Create a Python image in Django without a dummy image file and test the image upload
Check if the string is a number in python
Take a screenshot in Python
Basic information Write the 2018 fall algorithm problem in Python
Feel free to write a test with nose (in the case of + gevent)
Create a function in Python
Create a dictionary in Python
Write a super simple molecular dynamics program in python
Download the file in Python
Find the difference in Python
Write beta distribution in Python
Algorithm in Python (primality test)
Write python in Rstudio (reticulate)
Write letters in the card illustration with OpenCV python
Make a bookmarklet in Python
[Python] How to write a docstring that conforms to PEP8
I want to write in Python! (3) Utilize the mock
Write code to Unit Test a Python web app
Draw a heart in Python
A reminder about the implementation of recommendations in Python
Set python test in jenkins
What does the last () in a function mean in Python?
How to unit test a function containing the current time using freezegun in python
Find out the apparent width of a string in python
Create a local scope in Python without polluting the namespace
How to use the __call__ method in a Python class
Change the standard output destination to a file in Python
Write a python program to find the editing distance [python] [Levenshtein distance]
Get the number of specific elements in a python list
[Note] Import of a file in the parent directory in Python
I tried programming the chi-square test in Python and Java.
How to get the last (last) value in a list in Python
Find the eigenvalues of a real symmetric matrix in Python
Maybe in a python (original title: Maybe in Python)
How to write a Python class