Can I use doctest with hy (hylang.org)?
Yes, you can, with some limitations.
hy already supports docstrings, and simple-quoted strings can have newlines in them. Write the doctest using formatting of a Python REPL (not hy):
(defn test-fizzbuzz-with-doctest []
"
>>> fizzbuzz_of(1)
'1'
>>> fizzbuzz_of(9)
'fizz'
>>> fizzbuzz_of(25)
'buzz'
>>> fizzbuzz_of(30)
'fizzbuzz'
>>>
"
())
You will run into some limitations when writing a doctest:
- hy does not have
"""
so a literal"
will terminate the docstring. - unicode literals? Wrap tests in
str(...)
or use conditionals when writing code compatible with both Python 2 and Python 3.
Testing with doctest usually starts with a call inside the module:
if __name__ == '__main__':
import doctest
doctest.testmod()
... or a call from the command line:
python -m doctest -v FILE
Neither approach works with hy, because (a) the module is not loaded (i.e. in
sys.modules
) inside a defmain
block and (b) python -m doctest
has not yet imported hy so will not recognize any .hy files.
The most intuitive solution would have Python import hy
when running python -m doctest
, but this is hard in Python. It could potentially
be done with a sitecustomize.py
written on hy install, or a python-with-hy
executable installed as an entry point. These are left as exercises to the
reader.
An alternative would be to contribute a hy wrapper, porting or otherwise
wrapping the doctest command-line interface, so that something like
python -m hy.contrib.doctest FILE
or hy -m hy.contrib.doctest FILE
would work. (doctester2.py accomplishes this; rename it accordingly)
The enclosed doctest wrapper doctester.py
will work:
$ python doctester.py fizzbuzz
Trying:
fizzbuzz_of(1)
Expecting:
'1'
ok
Trying:
fizzbuzz_of(9)
Expecting:
'fizz'
ok
Trying:
fizzbuzz_of(25)
Expecting:
'buzz'
ok
Trying:
fizzbuzz_of(30)
Expecting:
'fizzbuzz'
ok
5 items had no tests:
fizzbuzz
fizzbuzz.fizzbuzz
fizzbuzz.fizzbuzz_of
fizzbuzz.main
fizzbuzz.test_fizzbuzz_of
1 items passed all tests:
4 tests in fizzbuzz.test_fizzbuzz_with_doctest
4 tests in 6 items.
4 passed and 0 failed.
Test passed.
Investigation used hy master 14c412c (after 0.11.1) on Python 2.7 and 3.5.
pip install git+https://git@github.com/hylang/hy.git@14c412c#egg=hy
We could put this
doctester2.py
module athy/contrib/doctest.py
, so thatpython -m hy.contrib.doctest
works. (Note that gist comments do not notify in the same way that GitHub issues do, so ping me on IRC or by email to discuss.)