doctest with variable return value
Peter Otten
__peter__ at web.de
Tue Jul 25 13:36:08 EDT 2006
3KWA wrote:
> I am wondering what is the standard doctest (test) practice for
> functions who's returned value change all the time e.g. forex rate:
>
> import urllib
>
> def get_rate(symbol):
> """get_rate(symbol) connects to yahoo finance to return the rate of
> symbol.
>
> >>>get_rate('AUDEUR')
>
> """
>
> url=
> "http://finance.yahoo.com/d/quotes.csv?s=%s=X&f=sl1d1t1c1ohgv&e=.csv" %
> \
> symbol
> f=urllib.urlopen(url)
> return float(f.readline().split(',')[1])
You cannot test for an unknown value, but you can do some sanity checks:
>>> rate = get_rate('AUDEUR')
>>> rate > 0
True
>>> isinstance(rate, float)
True
This will at least make sure that get_rate() does not throw an exception.
You can also spoonfeed it with handcrafted data...
>>> def mock_urlopen(url):
... from cStringIO import StringIO
... return StringIO("yadda,0.1234")
...
>>> urllib.urlopen = mock_urlopen
>>> get_rate("AUDEUR")
0.1234
but this has the disadvantage that the test has to know about the actual
implementation of the function about to be tested.
Peter
More information about the Python-list
mailing list