Problem with doctest

Peter Otten __peter__ at web.de
Mon May 4 11:33:46 EDT 2020


Unknown wrote:

> Hello
> 
> doctest of the sample function funct() doesn't works
> because flag used by funct() is the one defined in
> first line "flag = True" and not the one in the
> doctest code ">>> flag = False".
> 
> Any work around known ?

You can import the module where funct() is defined:

def funct()
    """
    >>> import module
    >>> module.flag = False
    >>> funct()
    'No'
    """
    ...

> flag = True              # <- funct() always use this one
> 
> def funct():
>      """
>      Code for doctest:
> 
>      >>> flag = True
>      >>> funct()
>      'Yes'
>      >>> flag = False     #  <- Ignored unfortunalely
>      >>> funct()
>      'No'
>      """
> 
>      if flag:
>          return "Yes"
>      else:
>          return "No"
> 
> if __name__ == "__main__":
>      import doctest
>      doctest.testmod()
> 
> 
> 
> Failed example:
>      funct()
> Expected:
>      'No'
> Got:
>      'Yes'
> **********************************************************************
> 1 items had failures:
>     1 of   4 in __main__.funct
> ***Test Failed*** 1 failures.




More information about the Python-list mailing list