plugin.py 2.7 KB

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