plugin.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (C) 2011 Sebastian Rahlf <basti at redtoad dot de>
  2. #
  3. # This program is release under the MIT license. You can find the full text of
  4. # the license in the LICENSE file.
  5. import os
  6. import pkgutil
  7. import pytest
  8. @pytest.fixture
  9. def httpserver(request):
  10. """The returned ``httpserver`` provides a threaded HTTP server instance
  11. running on a randomly assigned port on localhost. It can be taught which
  12. content (i.e. string) to serve with which response code and comes with
  13. following attributes:
  14. * ``code`` - HTTP response code (int)
  15. * ``content`` - content of next response (str)
  16. * ``headers`` - response headers (dict)
  17. Once these attribute are set, all subsequent requests will be answered with
  18. these values until they are changed or the server is stopped. A more
  19. convenient way to change these is ::
  20. httpserver.serve_content(
  21. content='My content', code=200,
  22. headers={'content-type': 'text/plain'})
  23. The server address can be found in property
  24. * ``url``
  25. which is the string representation of tuple ``server_address`` (host as
  26. str, port as int).
  27. Example::
  28. import requests
  29. def scrape(url):
  30. html = requests.get(url).text
  31. # some parsing happens here
  32. # ...
  33. return result
  34. def test_retrieve_some_content(httpserver):
  35. httpserver.serve_content(open('cached-content.html').read())
  36. assert scrape(httpserver.url) == 'Found it!'
  37. """
  38. from pytest_localserver import http
  39. server = http.ContentServer()
  40. server.start()
  41. request.addfinalizer(server.stop)
  42. return server
  43. @pytest.fixture
  44. def httpsserver(request):
  45. """The returned ``httpsserver`` (note the additional S!) provides a
  46. threaded HTTP server instance similar to funcarg ``httpserver`` but with
  47. SSL encryption.
  48. """
  49. from pytest_localserver import https
  50. try:
  51. with open(https.DEFAULT_CERTIFICATE, 'wb') as f:
  52. f.write(pkgutil.get_data('pytest_localserver', 'server.pem'))
  53. server = https.SecureContentServer()
  54. server.start()
  55. request.addfinalizer(server.stop)
  56. yield server
  57. finally:
  58. os.remove(https.DEFAULT_CERTIFICATE)
  59. @pytest.fixture
  60. def smtpserver(request):
  61. """The returned ``smtpserver`` provides a threaded instance of
  62. ``smtpd.SMTPServer`` running on localhost. It has the following
  63. attributes:
  64. * ``addr`` - server address as tuple (host as str, port as int)
  65. """
  66. from pytest_localserver import smtp
  67. server = smtp.Server()
  68. server.start()
  69. request.addfinalizer(server.stop)
  70. return server