Package: pytest-localserver
pytest-localserverpytest-localserver is a plugin for thepytesttesting framework which enables
you to test server connections locally.Sometimesmonkeypatchingurllib2.urlopen()just does not cut it, for
instance if you work withurllib2.Request, define your own openers/handlers
or work withhttplib. 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!QuickstartLet’s say you have a function to scrape HTML which only required to be pointed
at a URLimport requests
def scrape(url):
    html = requests.get(url).text
    # some parsing happens here
    # ...
    return resultYou 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?You simply use pytest’sfuncargs featureand simulate an entire server
locally!def test_retrieve_some_content(httpserver):
    httpserver.serve_content(open('cached-content.html').read())
    assert scrape(httpserver.url) == 'Found it!'What happened here is that for the duration of your tests an HTTP server is
started on a random port on localhost which will serve the content you tell it
to and behaves just like the real thing.The added bonus is that you can test whether your code behaves gracefully if
there is a network problem:def test_content_retrieval_fails_graciously(httpserver):
    httpserver.serve_content('File not found!', 404)
    pytest.raises(ContentNotFoundException, scrape, httpserver.url)The same thing works for SMTP servers, too:def test_sending_some_message(smtpserver):
    mailer = MyMailer(host=smtpserver.addr[0], port=smtpserver.addr[1])
    mailer.send(to='bob@example.com', from_='alice@example.com',
        subject='MyMailer v1.0', body='Check out my mailer!')
    assert len(smtpserver.outbox)==1Here 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’soutbox.It is really that easy!Available funcargsHere is a short overview of the available funcargs. For more details I suggest
poking around in the code itself.httpserverprovides a threaded HTTP server instance running on localhost. It has the
following attributes:code- HTTP response code (int)content- content of next response (str, bytes, or iterable of either)headers- response headers (dict)chunked- whether to chunk-encode the response (enumeration)Once these attributes 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 ishttpserver.serve_content(content=None, code=200, headers=None, chunked=pytest_localserver.http.Chunked.NO)Thechunkedattribute or parameter can be set toChunked.YES, telling the server to always apply chunk encodingChunked.NO, telling the server to never apply chunk encodingChunked.AUTO, telling the server to apply chunk encoding only if
theTransfer-Encodingheader includeschunkedIf chunk encoding is applied, each str or bytes incontentbecomes one
chunk in the response.The server address can be found in propertyurlwhich is the string representation of tupleserver_address(host as str,
port as int).If you want to check which form fields have been POSTed, Tryhttpserver.serve_content(..., show_post_vars=True)which will display them as parsable text.If you need to inspect the requests sent to the server, a list of all
received requests can be found in propertyrequestswhich is a list ofwerkzeug.wrappers.Requestobjects.httpsserveris the same ashttpserveronly with SSL encryption.smtpserverprovides a threaded SMTP server, with an API similar tosmtpd.SMTPServer,
(the deprecated class from the Python standard library) running on localhost.
It has the following attributes:addr- server address as tuple (host as str, port as int)outbox- list ofemail.message.Messageinstances received.Using your a WSGI application as test serverAs of version 0.3 you can now use aWSGI applicationto run on the test
serverfrom pytest_localserver.http import WSGIServer

def simple_app(environ, start_response):
    """Simplest possible WSGI application"""
    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']

@pytest.fixture
def testserver(request):
    """Defines the testserver funcarg"""
    server = WSGIServer(application=simple_app)
    server.start()
    request.addfinalizer(server.stop)
    return server

def test_retrieve_some_content(testserver):
    assert scrape(testserver.url) == 'Hello world!\n'Have a look at the following page for more information on WSGI:http://wsgi.readthedocs.org/en/latest/learn.htmlDownload and InstallationYou can install the plugin by runningpip install pytest-localserverAlternatively, get the latest stable version fromPyPIor the latestbleeding-edgefrom Github.License and CreditsThis plugin is released under the MIT license. You can find the full text of
the license in the LICENSE file.Copyright (C) 2010-2022 Sebastian Rahlf and others (see AUTHORS).Some parts of this package is based on ideas or code from other people:I borrowed some implementation ideas for the httpserver fromlinkchecker.The implementation for the SMTP server is based on theMailsink recipeby
Adam Feuer, Matt Branthwaite and Troy Frever.The HTTPS implementation is based on work bySebastien Martini.Thanks guys!Development and future plansFeel free to clone the repository and add your own changes. Pull requests are
always welcome!:git clone https://github.com/pytest-dev/pytest-localserverIf you find any bugs, please file areport.Test can be run with tox.I already have a couple of ideas for future versions:support for FTP, SSH (maybe base all on twisted?)making the SMTP outbox as convenient to use asdjango.core.mail.outboxadd your own here!Preparing a releaseFor package maintainers, here is how we release a new version:Ensure that theCHANGESfile is up to date with the latest changes.Make sure that all tests pass on the version you want to release.Use thenew release form on Github(or some other equivalent method) to
create a new release, following the pattern of previous releases.Each release has to be based on a tag. You can either create the tag first
(e.g. usinggit tag) and then make a release from that tag, or you can
have Github create the tag as part of the process of making a release;
either way works.The tag namemustbe thePEP 440-compliant version number prefixed
byv, making sure to include at least three version number components
(e.g.v0.6.0).The “Auto-generate release notes” button will be useful in summarizing
the changes since the last release.Using either therelease workflows pageor the link in the email you
received about a “Deployment review”, go to the workflow run created for
the new release and click “Review deployments”, then either approve or reject
the two deployments, one to Test PyPI and one to real PyPI. (It should not be
necessary to reject a deployment unless something really weird happens.)
Once the deployment is approved, Github will automatically upload the files.[1]The idea for this project was born when I needed to check thata piece
of softwarebehaved itself when receiving HTTP error codes 404 and 500.
Having unsuccessfully tried to mock a server, I stumbled acrosslinkcheckerwhich uses a the same idea to test its internals.