README.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. .. image:: https://img.shields.io/pypi/v/pytest-localserver.svg?style=flat
  2. :alt: PyPI Version
  3. :target: https://pypi.python.org/pypi/pytest-localserver
  4. .. image:: https://img.shields.io/pypi/pyversions/pytest-localserver.svg
  5. :alt: Supported Python versions
  6. :target: https://pypi.python.org/pypi/pytest-localserver
  7. .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
  8. :target: https://github.com/psf/black
  9. .. image:: https://results.pre-commit.ci/badge/github/pytest-dev/pytest-localserver/master.svg
  10. :target: https://results.pre-commit.ci/latest/github/pytest-dev/pytest-localserver/master
  11. :alt: pre-commit.ci status
  12. ==================
  13. pytest-localserver
  14. ==================
  15. pytest-localserver is a plugin for the `pytest`_ testing framework which enables
  16. you to test server connections locally.
  17. Sometimes `monkeypatching`_ ``urllib2.urlopen()`` just does not cut it, for
  18. instance if you work with ``urllib2.Request``, define your own openers/handlers
  19. or work with ``httplib``. In these cases it may come in handy to have an HTTP
  20. server running locally which behaves just like the real thing [1]_. Well, look
  21. no further!
  22. Quickstart
  23. ==========
  24. Let's say you have a function to scrape HTML which only required to be pointed
  25. at a URL ::
  26. import requests
  27. def scrape(url):
  28. html = requests.get(url).text
  29. # some parsing happens here
  30. # ...
  31. return result
  32. You want to test this function in its entirety without having to rely on a
  33. remote server whose content you cannot control, neither do you want to waste
  34. time setting up a complex mechanism to mock or patch the underlying Python
  35. modules dealing with the actual HTTP request (of which there are more than one
  36. BTW). So what do you do?
  37. You simply use pytest's `funcargs feature`_ and simulate an entire server
  38. locally! ::
  39. def test_retrieve_some_content(httpserver):
  40. httpserver.serve_content(open('cached-content.html').read())
  41. assert scrape(httpserver.url) == 'Found it!'
  42. What happened here is that for the duration of your tests an HTTP server is
  43. started on a random port on localhost which will serve the content you tell it
  44. to and behaves just like the real thing.
  45. The added bonus is that you can test whether your code behaves gracefully if
  46. there is a network problem::
  47. def test_content_retrieval_fails_graciously(httpserver):
  48. httpserver.serve_content('File not found!', 404)
  49. pytest.raises(ContentNotFoundException, scrape, httpserver.url)
  50. The same thing works for SMTP servers, too::
  51. def test_sending_some_message(smtpserver):
  52. mailer = MyMailer(host=smtpserver.addr[0], port=smtpserver.addr[1])
  53. mailer.send(to='bob@example.com', from_='alice@example.com',
  54. subject='MyMailer v1.0', body='Check out my mailer!')
  55. assert len(smtpserver.outbox)==1
  56. Here an SMTP server is started which accepts e-mails being sent to it. The
  57. nice feature here is that you can actually check if the message was received
  58. and what was sent by looking into the smtpserver's ``outbox``.
  59. It is really that easy!
  60. Available funcargs
  61. ==================
  62. Here is a short overview of the available funcargs. For more details I suggest
  63. poking around in the code itself.
  64. ``httpserver``
  65. provides a threaded HTTP server instance running on localhost. It has the
  66. following attributes:
  67. * ``code`` - HTTP response code (int)
  68. * ``content`` - content of next response (str, bytes, or iterable of either)
  69. * ``headers`` - response headers (dict)
  70. * ``chunked`` - whether to chunk-encode the response (enumeration)
  71. Once these attributes are set, all subsequent requests will be answered with
  72. these values until they are changed or the server is stopped. A more
  73. convenient way to change these is ::
  74. httpserver.serve_content(content=None, code=200, headers=None, chunked=pytest_localserver.http.Chunked.NO)
  75. The ``chunked`` attribute or parameter can be set to
  76. * ``Chunked.YES``, telling the server to always apply chunk encoding
  77. * ``Chunked.NO``, telling the server to never apply chunk encoding
  78. * ``Chunked.AUTO``, telling the server to apply chunk encoding only if
  79. the ``Transfer-Encoding`` header includes ``chunked``
  80. If chunk encoding is applied, each str or bytes in ``content`` becomes one
  81. chunk in the response.
  82. The server address can be found in property
  83. * ``url``
  84. which is the string representation of tuple ``server_address`` (host as str,
  85. port as int).
  86. If you want to check which form fields have been POSTed, Try ::
  87. httpserver.serve_content(..., show_post_vars=True)
  88. which will display them as parsable text.
  89. If you need to inspect the requests sent to the server, a list of all
  90. received requests can be found in property
  91. * ``requests``
  92. which is a list of ``werkzeug.wrappers.Request`` objects.
  93. ``httpsserver``
  94. is the same as ``httpserver`` only with SSL encryption.
  95. ``smtpserver``
  96. provides a threaded SMTP server, with an API similar to ``smtpd.SMTPServer``,
  97. (the deprecated class from the Python standard library) running on localhost.
  98. It has the following attributes:
  99. * ``addr`` - server address as tuple (host as str, port as int)
  100. * ``outbox`` - list of ``email.message.Message`` instances received.
  101. Using your a WSGI application as test server
  102. ============================================
  103. As of version 0.3 you can now use a `WSGI application`_ to run on the test
  104. server ::
  105. from pytest_localserver.http import WSGIServer
  106. def simple_app(environ, start_response):
  107. """Simplest possible WSGI application"""
  108. status = '200 OK'
  109. response_headers = [('Content-type', 'text/plain')]
  110. start_response(status, response_headers)
  111. return ['Hello world!\n']
  112. @pytest.fixture
  113. def testserver(request):
  114. """Defines the testserver funcarg"""
  115. server = WSGIServer(application=simple_app)
  116. server.start()
  117. request.addfinalizer(server.stop)
  118. return server
  119. def test_retrieve_some_content(testserver):
  120. assert scrape(testserver.url) == 'Hello world!\n'
  121. Have a look at the following page for more information on WSGI:
  122. http://wsgi.readthedocs.org/en/latest/learn.html
  123. Download and Installation
  124. =========================
  125. You can install the plugin by running ::
  126. pip install pytest-localserver
  127. Alternatively, get the latest stable version from `PyPI`_ or the latest
  128. `bleeding-edge`_ from Github.
  129. License and Credits
  130. ===================
  131. This plugin is released under the MIT license. You can find the full text of
  132. the license in the LICENSE file.
  133. Copyright (C) 2010-2022 Sebastian Rahlf and others (see AUTHORS).
  134. Some parts of this package is based on ideas or code from other people:
  135. - I borrowed some implementation ideas for the httpserver from `linkchecker`_.
  136. - The implementation for the SMTP server is based on the `Mailsink recipe`_ by
  137. Adam Feuer, Matt Branthwaite and Troy Frever.
  138. - The HTTPS implementation is based on work by `Sebastien Martini`_.
  139. Thanks guys!
  140. Development and future plans
  141. ============================
  142. Feel free to clone the repository and add your own changes. Pull requests are
  143. always welcome!::
  144. git clone https://github.com/pytest-dev/pytest-localserver
  145. If you find any bugs, please file a `report`_.
  146. Test can be run with tox.
  147. I already have a couple of ideas for future versions:
  148. * support for FTP, SSH (maybe base all on twisted?)
  149. * making the SMTP outbox as convenient to use as ``django.core.mail.outbox``
  150. * add your own here!
  151. Preparing a release
  152. -------------------
  153. For package maintainers, here is how we release a new version:
  154. #. Ensure that the ``CHANGES`` file is up to date with the latest changes.
  155. #. Make sure that all tests pass on the version you want to release.
  156. #. Use the `new release form on Github`_ (or some other equivalent method) to
  157. create a new release, following the pattern of previous releases.
  158. * Each release has to be based on a tag. You can either create the tag first
  159. (e.g. using ``git tag``) and then make a release from that tag, or you can
  160. have Github create the tag as part of the process of making a release;
  161. either way works.
  162. * The tag name **must** be the `PEP 440`_-compliant version number prefixed
  163. by ``v``, making sure to include at least three version number components
  164. (e.g. ``v0.6.0``).
  165. * The "Auto-generate release notes" button will be useful in summarizing
  166. the changes since the last release.
  167. #. Using either the `release workflows page`_ or the link in the email you
  168. received about a "Deployment review", go to the workflow run created for
  169. the new release and click "Review deployments", then either approve or reject
  170. the two deployments, one to Test PyPI and one to real PyPI. (It should not be
  171. necessary to reject a deployment unless something really weird happens.)
  172. Once the deployment is approved, Github will automatically upload the files.
  173. ----
  174. .. [1] The idea for this project was born when I needed to check that `a piece
  175. of software`_ behaved itself when receiving HTTP error codes 404 and 500.
  176. Having unsuccessfully tried to mock a server, I stumbled across
  177. `linkchecker`_ which uses a the same idea to test its internals.
  178. .. _monkeypatching: http://pytest.org/latest/monkeypatch.html
  179. .. _pytest: http://pytest.org/
  180. .. _funcargs feature: http://pytest.org/latest/funcargs.html
  181. .. _linkchecker: http://linkchecker.sourceforge.net/
  182. .. _WSGI application: http://www.python.org/dev/peps/pep-0333/
  183. .. _PyPI: http://pypi.python.org/pypi/pytest-localserver/
  184. .. _bleeding-edge: https://github.com/pytest-dev/pytest-localserver
  185. .. _report: https://github.com/pytest-dev/pytest-localserver/issues/
  186. .. _tox: http://testrun.org/tox/
  187. .. _a piece of software: http://pypi.python.org/pypi/python-amazon-product-api/
  188. .. _Mailsink recipe: http://code.activestate.com/recipes/440690/
  189. .. _Sebastien Martini: http://code.activestate.com/recipes/442473/
  190. .. _PEP 440: https://peps.python.org/pep-0440/
  191. .. _build: https://pypa-build.readthedocs.io/en/latest/
  192. .. _twine: https://twine.readthedocs.io/en/stable/
  193. .. _new release form on Github: https://github.com/pytest-dev/pytest-localserver/releases/new
  194. .. _release workflows page: https://github.com/pytest-dev/pytest-localserver/actions/workflows/release.yml