doctest

Using Mocks inside Doctests?

假装没事ソ 提交于 2019-12-05 09:45:15
I am using doctests. I am wondering what is the correct way to doctest a function that performs an external action (e.g. sends email, connects to a server, etc)? Using Mock seems like the answer but it will muddy up the doc string of the function. For example: class SSHConnection(BaseConnection): """Provides basic SSH functions. >>> host = '127.0.0.1' >>> port = 22 >>> username = 'user' >>> password = 'password' >>> ssh = SSHConnection(host, username, password, port) >>> ssh.execute('uname -a') """ ... 来源: https://stackoverflow.com/questions/41289247/using-mocks-inside-doctests

Python: How can I define a class in a doctest?

左心房为你撑大大i 提交于 2019-12-05 01:34:48
I would like to use a doctest comment block to demonstrate the usage of a particular base class, but either this cannot be done with doctest or I am doing something wrong. Here is my simple demo code. class MyClass(object): ''' >>> m = MyClass() >>> print m.x 1 >>> class A(MyClass): >>> def __init__(self): >>> super(A,self).__init__() >>> >>> a = A() >>> print a.x 1 ''' def __init__(self): self.x = 1 if __name__ == "__main__": import doctest doctest.testmod() The code doesn't run. Here's the first error issued: Failed example: class A(MyClass): Exception raised: Traceback (most recent call

Python doctests: test for None

牧云@^-^@ 提交于 2019-12-04 22:21:05
Using Python 2.7 I'm trying to test that the result of a particular function call is None I would expect these tests to pass (excuse the rather silly example) def six_or_none(val): """ >>> six_or_none(6) 6 >>> six_or_none(4) None """ if val == 6: return 6 return None However they yield the following result Failed example: six_or_none(4) Expected: None Got nothing What's the correct way to test for None in doctests? The Python interpreter ignores None return values, so doctests do the same. Test for is None instead: >>> six_or_none(4) is None True Other option would be a direct check for None :

Why could doctests raise a NameError when run with Sphinx's `make doctest`?

我怕爱的太早我们不能终老 提交于 2019-12-04 15:05:19
I have a simple function with a doctest , which, when run with Sphinx's make doctest , gives me the following error: File "scheemey.rst", line ?, in default Failed example: verify_balanced('asdf (foo [bar] [[baz], {}, ()]') Exception raised: Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.8/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1315, in __run compileflags, 1) in test.globs File "<doctest default[0]>", line 1, in <module> verify_balanced('asdf (foo [bar] [[baz], {}, ()]') NameError: name 'verify_balanced' is not defined What could be

use doctest and logging in python program

扶醉桌前 提交于 2019-12-04 11:08:57
#!/usr/bin/python2.4 import logging import sys import doctest def foo(x): """ >>> foo (0) 0 """ print ("%d" %(x)) _logger.debug("%d" %(x)) def _test(): doctest.testmod() _logger = logging.getLogger() _logger.setLevel(logging.DEBUG) _formatter = logging.Formatter('%(message)s') _handler = logging.StreamHandler(sys.stdout) _handler.setFormatter(_formatter) _logger.addHandler(_handler) _test() I would like to use logger module for all of my print statements. I have looked at the first 50 top google links for this, and they seem to agree that doctest uses it's own copy of the stdout. If print is

Python doctest for shell scripts that test argument parsing without polluting docstring with os.popen()

一笑奈何 提交于 2019-12-04 04:41:00
Is there a way to write a python doctest string to test a script intended to be launched from the command line (terminal) that doesn't pollute the documentation examples with os.popen calls? #!/usr/bin/env python # filename: add """ Example: >>> import os >>> os.popen('add -n 1 2').read().strip() '3' """ if __name__ == '__main__': from argparse import ArgumentParser p = ArgumentParser(description=__doc__.strip()) p.add_argument('-n',type = int, nargs = 2, default = 0,help = 'Numbers to add.') p.add_argument('--test',action = 'store_true',help = 'Test script.') a = p.parse_args() if a.test:

Doctest not recognizing __future__.division

夙愿已清 提交于 2019-12-04 03:28:28
I have the following doctest written x.doctest : This is something: >>> x = 3 + 4 foo bar something else: >>> from __future__ import division >>> y = 15 >>> z = int('24') >>> m = z / y >>> print (m) 1.6 But when I ran python -m doctest x.doctest on python 2.7.11, the doctest didn't recognize from __future__ import division : ********************************************************************** File "x.doctest", line 11, in x.doctest Failed example: print (m) Expected: 1.6 Got: 1 ********************************************************************** 1 items had failures: 1 of 6 in x.doctest **

Can I have an ellipsis at the beginning of the line in a Python doctest?

こ雲淡風輕ζ 提交于 2019-12-04 02:47:16
问题 Python doctests are cool. Let me start with a simple example: def foo(): """ >>> foo() hello world """ print "hello world" Now let's assume some part is somewhat varying, e.g., because it is a time value or a random number. In general, doctests allow me to specify a wildcard saying using the +ELLIPSIS option. This works fine when for instance "world" is a varying string: def foo(): """ >>> foo() # doctest: +ELLIPSIS hello ... """ print "hello world" In my case however, the variable string is

Doctest fails due to unicode leading u

一个人想着一个人 提交于 2019-12-03 22:04:15
问题 I am writing a doctest for a function that outputs a list of tokenized words. r''' >>> s = "This is a tokenized sentence s\u00f3" >>> tokenizer.tokenize(s0) ['This', 'is', 'a', 'tokenized', 'sentence', 'só'] ''' Using Python3.4 my test passes with no problems. Using Python2.7 I get: Expected: ['This', 'is', 'a', 'tokenized', 'sentence', 'só'] Got: [u'This', u'is', u'a', u'tokenized', u'sentence', u's\xf3'] My code has to work on both Python3.4 and Python2.7. How can I solve this problem? 回答1:

Doctests that contain string literals

吃可爱长大的小学妹 提交于 2019-12-03 21:29:24
I have a unit test that I'd like to write for a function that takes XML as a string. It's a doctest and I'd like the XML in-line with the tests. Since the XML is multi-line, I tried a string literal within the doctest, but no success. Here's simplified test code: def test(): """ >>> config = \"\"\"\ <?xml version="1.0"?> <test> <data>d1</data> <data>d2</data> </test>\"\"\" """ if __name__ == "__main__": import doctest doctest.testmod(name='test') The error I get is File "<doctest test.test[0]>", line 1 config = """ <?xml version="1.0"?> ^ SyntaxError: EOF while scanning triple-quoted string I