test_server.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2018 Unrud<unrud@outlook.com>
  3. #
  4. # This library is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This library is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. Test the internal server.
  18. """
  19. import os
  20. import shutil
  21. import socket
  22. import ssl
  23. import tempfile
  24. import threading
  25. import time
  26. import warnings
  27. from urllib import request
  28. from urllib.error import HTTPError, URLError
  29. from radicale import config, server
  30. from .helpers import get_file_path
  31. import pytest # isort:skip
  32. class DisabledRedirectHandler(request.HTTPRedirectHandler):
  33. def http_error_302(self, req, fp, code, msg, headers):
  34. raise HTTPError(req.full_url, code, msg, headers, fp)
  35. http_error_301 = http_error_303 = http_error_307 = http_error_302
  36. class TestBaseServerRequests:
  37. """Test the internal server."""
  38. def setup(self):
  39. self.configuration = config.load()
  40. self.colpath = tempfile.mkdtemp()
  41. self.configuration["storage"]["filesystem_folder"] = self.colpath
  42. # Disable syncing to disk for better performance
  43. self.configuration["internal"]["filesystem_fsync"] = "False"
  44. self.shutdown_socket, shutdown_socket_out = socket.socketpair()
  45. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  46. # Find available port
  47. sock.bind(("127.0.0.1", 0))
  48. self.sockname = sock.getsockname()
  49. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  50. self.thread = threading.Thread(target=server.serve, args=(
  51. self.configuration, shutdown_socket_out))
  52. ssl_context = ssl.create_default_context()
  53. ssl_context.check_hostname = False
  54. ssl_context.verify_mode = ssl.CERT_NONE
  55. self.opener = request.build_opener(
  56. request.HTTPSHandler(context=ssl_context),
  57. DisabledRedirectHandler)
  58. def teardown(self):
  59. self.shutdown_socket.sendall(b" ")
  60. try:
  61. self.thread.join()
  62. except RuntimeError: # Thread never started
  63. pass
  64. shutil.rmtree(self.colpath)
  65. def request(self, method, path, data=None, **headers):
  66. """Send a request."""
  67. scheme = ("https" if self.configuration.getboolean("server", "ssl")
  68. else "http")
  69. req = request.Request(
  70. "%s://[%s]:%d%s" % (scheme, *self.sockname, path),
  71. data=data, headers=headers, method=method)
  72. while True:
  73. assert self.thread.is_alive()
  74. try:
  75. with self.opener.open(req) as f:
  76. return f.getcode(), f.info(), f.read().decode()
  77. except HTTPError as e:
  78. return e.code, e.headers, e.read().decode()
  79. except URLError as e:
  80. if not isinstance(e.reason, ConnectionRefusedError):
  81. raise
  82. time.sleep(0.1)
  83. def test_root(self):
  84. self.thread.start()
  85. status, _, _ = self.request("GET", "/")
  86. assert status == 302
  87. def test_ssl(self):
  88. self.configuration["server"]["ssl"] = "True"
  89. self.configuration["server"]["certificate"] = get_file_path("cert.pem")
  90. self.configuration["server"]["key"] = get_file_path("key.pem")
  91. self.thread.start()
  92. status, _, _ = self.request("GET", "/")
  93. assert status == 302
  94. def test_ipv6(self):
  95. if not server.HAS_IPV6:
  96. pytest.skip("IPv6 not support")
  97. if os.name == "nt" and os.environ.get("WINE_PYTHON"):
  98. warnings.warn("WORKAROUND: incomplete errno conversion in WINE")
  99. server.EAI_ADDRFAMILY = -9
  100. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
  101. sock.setsockopt(server.IPPROTO_IPV6, server.IPV6_V6ONLY, 1)
  102. # Find available port
  103. sock.bind(("::1", 0))
  104. self.sockname = sock.getsockname()[:2]
  105. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  106. self.thread.start()
  107. status, _, _ = self.request("GET", "/")
  108. assert status == 302