Add if...else... switch to doctest?

Ben Finney ben+python at benfinney.id.au
Thu Oct 18 21:29:25 EDT 2012


David <zhushenli at gmail.com> writes:

> Hello, how to add if...else... switch to doctest?
> E.g. function outputs different value when global_var change.
>
> """
> if (global_var == True):
> >>> function()
> [1,2]
> else:
> >>> function()
> [1,2,3]
> """
>
> Thank you very much.

You write the code in a doctest as it would appear at a standard Python
interactive prompt.

    >>> if global_thing:
    ...     foo()
    [1, 2]

But you need it to be deterministic, so that the output *always*
matches what your docstring declares.

So if you want the result to depend on some state, you need to ensure
that state in your test.

    >>> global_thing = True
    >>> foo()
    [1, 2]
    >>> global_thing = False
    >>> foo()
    [1, 2, 3]

Because this is gnarly, it's yet another reason not to depend so much on
globals. Instead, change the function so its state is passed in
explicitly::

    >>> foo(bar=True)
    [1, 2]
    >>> foo(bar=False)
    [1, 2, 3]

Once your functions and tests get complex, you should be using a more
sophisticated testing framework. Don't put complex tests in your
documentation. Instead, put *examples* for readers in the documentation,
and use doctest to test your documentation.

Doctest is for testing explanatory code examples. For more thorough
testing, don't use doctests. Use unit tests with ‘unittests’, feature
tests with Behave <URL:http://pypi.python.org/pypi/behave> or something
similar.

-- 
 \      “I tell you the truth: this generation will certainly not pass |
  `\           away until all these things [the end of the world] have |
_o__)   happened.” —Jesus Christ, c. 30 CE, as quoted in Matthew 24:34 |
Ben Finney




More information about the Python-list mailing list