For integration tests it can be helpful to have a fake HTTP server whose behaviour the tests can control. All necessary building blocks are even included in Python standard library. However, the BaseHTTPServer is surprisingly hard to shut down properly, so that it gives up the socket and everything.

While working on gocept.selenium, we came up with some code that does the trick (together with Jan-Wijbrand Kolman and Jan-Jaap Driessen).

class HTTPServer(BaseHTTPServer.HTTPServer):
_continue = True
def serve_until_shutdown(self):
while self._continue:
self.handle_request()
def shutdown(self):
self._continue = False
# We fire a last request at the server in order to take it out of the
# while loop in `self.serve_until_shutdown`.
try:
urllib2.urlopen(
'http://%s:%s/' % (self.server_name, self.server_port))
except urllib2.URLError:
# If the server is already shut down, we receive a socket error,
# which we ignore.
pass
self.server_close()

zc.sourcefactory is very handy to easily create a source (zope.schema.interfaces.IIterableSource to be precise) with corresponding titles and tokens for its contents. Every now and then a source requires an explicit interface. For zc.sourcefactory the following code snippet helps:

Of course it is also possible to declare the source_class separately from the source factory and reference it. But since its sole purpose is to hold an implements declaration, I’m fine with defining it inline.