473,748 Members | 4,065 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

doctest with variable return value

Hi all,

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(sym bol) connects to yahoo finance to return the rate of
symbol.
>>>get_rate('AU DEUR')
"""

url=
"http://finance.yahoo.c om/d/quotes.csv?s=%s =X&f=sl1d1t1c1o hgv&e=.csv" %
\
symbol
f=urllib.urlope n(url)
return float(f.readlin e().split(',')[1])

As you can guess I am very new to unittest and doctest in general ...

Thanks for your help,

EuGeNe

Jul 25 '06 #1
4 1882
On Tuesday 25 July 2006 09:53, 3KWA wrote:
Hi all,

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(sym bol) connects to yahoo finance to return the rate of
symbol.
>>>get_rate('AU DEUR')

"""

url=
"http://finance.yahoo.c om/d/quotes.csv?s=%s =X&f=sl1d1t1c1o hgv&e=.csv" %
\
symbol
f=urllib.urlope n(url)
return float(f.readlin e().split(',')[1])

As you can guess I am very new to unittest and doctest in general ...

Thanks for your help,

EuGeNe
Hi EuGeNe,
Pass it through a variable before returning a value.
Here's how I would do it:

import urllib2
def get_rate(symbol ):

URL='http://finance.yahoo.c om/d/quotes.csv?s=AU DEUR=X&f=sl1d1t 1c1ohgv&e=.csv'
request_headers = { 'User-Agent': 'Linuxinclar/0.1' }
request = urllib2.Request (URL, None, request_headers )
response = urllib2.urlopen (request)
STR = response.read()
return STR.split(',')[1].strip()

SYMB='AUDEUR'
print SYMB,'=',get_ra te(SYMB)

Python rocks.
That's be nice to indicate hour though (4th array element)...

Best Regards,
Rob Sinclar
Jul 25 '06 #2
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(sym bol) connects to yahoo finance to return the rate of
symbol.
>>>get_rate('AU DEUR')

"""

url=
"http://finance.yahoo.c om/d/quotes.csv?s=%s =X&f=sl1d1t1c1o hgv&e=.csv" %
\
symbol
f=urllib.urlope n(url)
return float(f.readlin e().split(',')[1])
You cannot test for an unknown value, but you can do some sanity checks:
>>rate = get_rate('AUDEU R')
rate 0
True
>>isinstance(ra te, 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(ur l):
... from cStringIO import StringIO
... return StringIO("yadda ,0.1234")
...
>>urllib.urlope n = mock_urlopen
get_rate("AUD EUR")
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
Jul 25 '06 #3

Peter Otten wrote:
You cannot test for an unknown value, but you can do some sanity checks:
>>rate = get_rate('AUDEU R')
>>rate 0
True
>>isinstance(ra te, float)
True

This will at least make sure that get_rate() does not throw an exception.
Thanks a lot ... sanity checks ... it makes a lot of sense to me!

At EuroPython I attended a talk where someone said that untested code
is nothing ... so I am trying to write something instead of nothing ...
on the other hand can code ever be over tested?

EuGeNe

Jul 26 '06 #4
3KWA wrote:
>
Peter Otten wrote:
>You cannot test for an unknown value, but you can do some sanity
checks:
> >>rate = get_rate('AUDEU R')
>>rate 0
True
> >>isinstance(ra te, float)
True

This will at least make sure that get_rate() does not throw an
exception.

Thanks a lot ... sanity checks ... it makes a lot of sense to me!

At EuroPython I attended a talk where someone said that untested code
is nothing ... so I am trying to write something instead of nothing
... on the other hand can code ever be over tested?
Yes, code can be over tested: tests require maintenance just like any other
code, so you should avoid having tests which just duplicate other tests and
don't add any value. e.g. If you know the rate code works for a few
currencies it probably also works for most others, so you don't need to
exhaustively test all possible currency pairs.

For your unknown value, I would choose a range which you might expect to
hold true for a reasonable period of time and check the value is inside
that range. If the currencies shift massively you might need to update the
test, but with luck that won't happen:
>>0.4 <= get_rate('AUDEU R') <= 0.8
That way if your code starts accidentally returning EURAUD you should catch
it in the test, but minor shifts shouldn't matter.
Jul 26 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2638
by: Pierre Rouleau | last post by:
I have a problem writing self-testable modules using doctest when these modules have internationalized strings using gettext _('...'). - The main module of an application (say app.py) calls gettext.install() to install the special _ function inside Python builtin. Other modules, taken from a general purpose collection of Python modules, also support internationalisation and doctest testing. For example:
2
1415
by: Alan G Isaac | last post by:
> python doctest.py -v Running doctest.__doc__ Trying: .remove(42) Expecting: Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: list.remove(x): x not in list ok Trying: x = 12 Expecting: nothing
0
1026
by: bearophile | last post by:
doctest module is quite useful; and I've also tried the simpler docex: http://aima.cs.berkeley.edu/python/docex.html http://aima.cs.berkeley.edu/python/docex.py (docex isn't perfect, there are problems with functions without a return, and with functions with prints inside, but it can be useful, easy to use, and it produces very short docs.) Looking at docex I think doctest usage can be simplified a little, and the doctest output can...
1
1923
by: David MacKay | last post by:
Hello, I'm a python-list newbie. I've got a question about doctest; perhaps a bug report. I really like doctest, but sometimes doctest gives a failure when the output looks absolutely fine to me -- indeed, even after I have gone to considerable effort to make my documentation match the output perfectly. http://www.aims.ac.za/~mackay/python/compression/huffman/Huffman3.py The above file is an example.
0
1257
by: Steven Bethard | last post by:
I have an optparse-like module and though I have a full unittest-style suite of tests for it, I'd also like to be able to run doctest on the documentation to make sure my examples all work. However, I see that doctest (1) doesn't capture anything from sys.stderr, and (2) unlike the normal interpreter, generates a traceback for SystemExit. Here's what some of my tests look like and the doctest output I get:: ========== in my...
12
2119
by: thomas.guest | last post by:
I'm not making progress with the following and would appreciate any help. Here's an interpreted Python session. .... Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'f' is not defined
0
245
by: Edward Loper | last post by:
Anyone testing on xemacs? I tried it, and C-c C-c sent xemacs into an It works fine for me in XEmacs 21.4 (patch 17) (i386-debian-linux, Mule). If you could answer a few questions, it might help me track down the problem: - What version of xemacs are you running? - What version of doctest-mode are you running (0.4 or 0.5)? - Are you using doctest-mode by itself, or in combination with another mode (via mmm-mode)?
6
2487
by: Bzyczek | last post by:
Hello, I have problems with running doctests if I use czech national characters in UTF-8 encoding. I have Python script, which begin with encoding definition: # -*- coding: utf-8 -*- I have this function with doctest:
0
1656
by: dj | last post by:
Hello, I have just started working with minimock in doctest. I want to create a mock pyodbc object which returns a string value when the method execute is called. Here is my doctest: .... ServerName = 'test_server'
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8239
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.