pytest-localserver

pytest-localserver is a plugin for the pytest testing framework which enables
you to test server connections locally.

Sometimes monkeypatchingurllib2.urlopen() just does not cut it, for
instance if you work with urllib2.Request, define your own openers/handlers
or work with httplib. In these cases it may come in handy to have an HTTP
server running locally which behaves just like the real thing [1]. Well, look
no further!

Quickstart

Let's say you have a function to scrape HTML which only required to be pointed
at a URL

You want to test this function in its entirety without having to rely on a
remote server whose content you cannot control, neither do you want to waste
time setting up a complex mechanism to mock or patch the underlying Python
modules dealing with the actual HTTP request (of which there are more than one
BTW). So what do you do?

Here an SMTP server is started which accepts e-mails being sent to it. The
nice feature here is that you can actually check if the message was received
and what was sent by looking into the smtpserver's outbox.

It is really that easy!

Available funcargs

Here is a short overview of the available funcargs. For more details I suggest
poking around in the code itself.

httpserver

provides a threaded HTTP server instance running on localhost. It has the
following attributes:

code - HTTP response code (int)

content - content of next response (str)

headers - response headers (dict)

Once these attribute are set, all subsequent requests will be answered with
these values until they are changed or the server is stopped. A more
convenient way to change these is

httpserver.serve_content(content=None, code=200, headers=None)

The server address can be found in property

url

which is the string representation of tuple server_address (host as str,
port as int).

If you want to check which form fields have been POSTed, Try

httpserver.serve_content(..., show_post_vars=True)

which will display them as parsable text.

httpsserver

is the same as httpserver only with SSL encryption.

smtpserver

provides a threaded instance of smtpd.SMTPServer runnning on localhost.
It has the following attributes:

The idea for this project was born when I needed to check that a piece
of software behaved itself when receiving HTTP error codes 404 and 500.
Having unsuccessfully tried to mock a server, I stumbled across
linkchecker which uses a the same idea to test its internals.

Unlimited private and public hosted repositories. Free for small teams!