[Tutor] Help error 504

Danny Yoo dyoo at hashcollision.org
Wed Aug 26 06:58:12 CEST 2015


Unit tests that depend on external dependencies can be "flaky": they
might fail for reasons that you don't anticipate.  I'd recommend not
depending on an external web site like this: it puts load on someone
else, which they might not appreciate.


Making the test not depend on the network is not bad if we take
advantage of functions.  Functions let us swap in different parameters
for values.

Since the code depends on something that knows how to open urls, we
can let that url opener itself be a parameter.  The original code
looked something like this:

#######################
for line in fhand:
    req=urllib.request.urlopen('XXXXXXXX'+line)
    resp=req.read()
    ....
########################


We can wrap this whole block into a function that takes in a urlopen() function:

####################################
def process(urlopen=urllib.request.urlopen):
    for line in fhand:
        req=urlopen('XXXXXXXX'+line)
        resp=req.read()
        ....


process()
####################################

where we get the same behavior by calling "process()" at the end.  By
default, if we don't give process() an explicit urlopen, it'll use the
urllib.request.urlopen, just like before.


But now it's relatively easy to substitute with something that can
simulate errors:

##########################################
def simulateErrorOnOpen(url):
   raise ValueError("oh!")
##########################################

and now we can pass this to our process() to see how it behaves when
url opening raises that error:

###############################
process(urlopen=simulateErrorOnOpen)
###############################


More information about the Tutor mailing list