Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #31701

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

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: Add if...else... switch to doctest?
Date 2012-10-19 12:29 +1100
References <c500a76c-3e6b-4dfc-97ca-8b24f0628620@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.2487.1350610181.27098.python-list@python.org> (permalink)

Show all headers | View raw


David <zhushenli@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Add if...else...  switch to doctest? David <zhushenli@gmail.com> - 2012-10-18 17:08 -0700
  Re: Add if...else...  switch to doctest? Ben Finney <ben+python@benfinney.id.au> - 2012-10-19 12:29 +1100
  Re: Add if...else...  switch to doctest? Terry Reedy <tjreedy@udel.edu> - 2012-10-18 21:31 -0400
  Re: Add if...else...  switch to doctest? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-10-19 01:57 +0000
  Re: Add if...else...  switch to doctest? Duncan Booth <duncan.booth@invalid.invalid> - 2012-10-19 09:27 +0000

csiph-web