test_server.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2018-2019 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 errno
  20. import os
  21. import socket
  22. import ssl
  23. import subprocess
  24. import sys
  25. import threading
  26. import time
  27. from configparser import RawConfigParser
  28. from typing import Callable, Dict, NoReturn, Optional, Tuple, cast
  29. from urllib import request
  30. from urllib.error import HTTPError, URLError
  31. import pytest
  32. from radicale import config, server
  33. from radicale.tests import BaseTest
  34. from radicale.tests.helpers import configuration_to_dict, get_file_path
  35. class DisabledRedirectHandler(request.HTTPRedirectHandler):
  36. # HACK: typeshed annotation are wrong for `fp` and `msg`
  37. # (https://github.com/python/typeshed/pull/5728)
  38. # `headers` is incompatible with `http.client.HTTPMessage`
  39. # (https://github.com/python/typeshed/issues/5729)
  40. def http_error_301(self, req: request.Request, fp, code: int,
  41. msg, headers) -> NoReturn:
  42. raise HTTPError(req.full_url, code, msg, headers, fp)
  43. def http_error_302(self, req: request.Request, fp, code: int,
  44. msg, headers) -> NoReturn:
  45. raise HTTPError(req.full_url, code, msg, headers, fp)
  46. def http_error_303(self, req: request.Request, fp, code: int,
  47. msg, headers) -> NoReturn:
  48. raise HTTPError(req.full_url, code, msg, headers, fp)
  49. def http_error_307(self, req: request.Request, fp, code: int,
  50. msg, headers) -> NoReturn:
  51. raise HTTPError(req.full_url, code, msg, headers, fp)
  52. class TestBaseServerRequests(BaseTest):
  53. """Test the internal server."""
  54. shutdown_socket: socket.socket
  55. thread: threading.Thread
  56. opener: request.OpenerDirector
  57. def setup(self) -> None:
  58. super().setup()
  59. self.shutdown_socket, shutdown_socket_out = socket.socketpair()
  60. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  61. # Find available port
  62. sock.bind(("127.0.0.1", 0))
  63. self.sockname = sock.getsockname()
  64. self.configuration.update({
  65. "server": {"hosts": "[%s]:%d" % self.sockname},
  66. # Enable debugging for new processes
  67. "logging": {"level": "debug"}},
  68. "test", privileged=True)
  69. self.thread = threading.Thread(target=server.serve, args=(
  70. self.configuration, shutdown_socket_out))
  71. ssl_context = ssl.create_default_context()
  72. ssl_context.check_hostname = False
  73. ssl_context.verify_mode = ssl.CERT_NONE
  74. self.opener = request.build_opener(
  75. request.HTTPSHandler(context=ssl_context),
  76. DisabledRedirectHandler)
  77. def teardown(self) -> None:
  78. self.shutdown_socket.close()
  79. try:
  80. self.thread.join()
  81. except RuntimeError: # Thread never started
  82. pass
  83. super().teardown()
  84. def request(self, method: str, path: str, data: Optional[str] = None,
  85. **kwargs) -> Tuple[int, Dict[str, str], str]:
  86. """Send a request."""
  87. login = kwargs.pop("login", None)
  88. if login is not None and not isinstance(login, str):
  89. raise TypeError("login argument must be %r, not %r" %
  90. (str, type(login)))
  91. if login:
  92. raise NotImplementedError
  93. is_alive_fn: Optional[Callable[[], bool]] = kwargs.pop(
  94. "is_alive_fn", None)
  95. headers: Dict[str, str] = kwargs
  96. for k, v in headers.items():
  97. if not isinstance(v, str):
  98. raise TypeError("type of %r is %r, expected %r" %
  99. (k, type(v), str))
  100. if is_alive_fn is None:
  101. is_alive_fn = self.thread.is_alive
  102. encoding: str = self.configuration.get("encoding", "request")
  103. scheme = "https" if self.configuration.get("server", "ssl") else "http"
  104. data_bytes = None
  105. if data:
  106. data_bytes = data.encode(encoding)
  107. req = request.Request(
  108. "%s://[%s]:%d%s" % (scheme, *self.sockname, path),
  109. data=data_bytes, headers=headers, method=method)
  110. while True:
  111. assert is_alive_fn()
  112. try:
  113. with self.opener.open(req) as f:
  114. return f.getcode(), dict(f.info()), f.read().decode()
  115. except HTTPError as e:
  116. return e.code, dict(e.headers), e.read().decode()
  117. except URLError as e:
  118. if not isinstance(e.reason, ConnectionRefusedError):
  119. raise
  120. time.sleep(0.1)
  121. def test_root(self) -> None:
  122. self.thread.start()
  123. self.get("/", check=302)
  124. def test_ssl(self) -> None:
  125. self.configuration.update({
  126. "server": {"ssl": "True",
  127. "certificate": get_file_path("cert.pem"),
  128. "key": get_file_path("key.pem")}}, "test")
  129. self.thread.start()
  130. self.get("/", check=302)
  131. def test_bind_fail(self) -> None:
  132. for address_family, address in [(socket.AF_INET, "::1"),
  133. (socket.AF_INET6, "127.0.0.1")]:
  134. with socket.socket(address_family, socket.SOCK_STREAM) as sock:
  135. if address_family == socket.AF_INET6:
  136. # Only allow IPv6 connections to the IPv6 socket
  137. sock.setsockopt(server.COMPAT_IPPROTO_IPV6,
  138. socket.IPV6_V6ONLY, 1)
  139. with pytest.raises(OSError) as exc_info:
  140. sock.bind((address, 0))
  141. # See ``radicale.server.serve``
  142. assert (isinstance(exc_info.value, socket.gaierror) and
  143. exc_info.value.errno in (
  144. socket.EAI_NONAME, server.COMPAT_EAI_ADDRFAMILY,
  145. server.COMPAT_EAI_NODATA) or
  146. str(exc_info.value) == "address family mismatched" or
  147. exc_info.value.errno in (
  148. errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT,
  149. errno.EPROTONOSUPPORT))
  150. def test_ipv6(self) -> None:
  151. try:
  152. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
  153. # Only allow IPv6 connections to the IPv6 socket
  154. sock.setsockopt(
  155. server.COMPAT_IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
  156. # Find available port
  157. sock.bind(("::1", 0))
  158. self.sockname = sock.getsockname()[:2]
  159. except OSError as e:
  160. if e.errno in (errno.EADDRNOTAVAIL, errno.EAFNOSUPPORT,
  161. errno.EPROTONOSUPPORT):
  162. pytest.skip("IPv6 not supported")
  163. raise
  164. self.configuration.update({
  165. "server": {"hosts": "[%s]:%d" % self.sockname}}, "test")
  166. self.thread.start()
  167. self.get("/", check=302)
  168. def test_command_line_interface(self) -> None:
  169. self.configuration.update({"headers": {"Test-Server": "test"}})
  170. config_args = []
  171. for section in self.configuration.sections():
  172. if section.startswith("_"):
  173. continue
  174. for option in self.configuration.options(section):
  175. if option.startswith("_"):
  176. continue
  177. long_name = "--%s-%s" % (section, option.replace("_", "-"))
  178. if config.DEFAULT_CONFIG_SCHEMA.get(
  179. section, {}).get(option, {}).get("type") == bool:
  180. if not cast(bool, self.configuration.get(section, option)):
  181. long_name = "--no%s" % long_name[1:]
  182. config_args.append(long_name)
  183. else:
  184. config_args.append(long_name)
  185. raw_value = self.configuration.get_raw(section, option)
  186. assert isinstance(raw_value, str)
  187. config_args.append(raw_value)
  188. config_args.append("--headers-Test-Header=test")
  189. p = subprocess.Popen(
  190. [sys.executable, "-m", "radicale"] + config_args,
  191. env={**os.environ, "PYTHONPATH": os.pathsep.join(sys.path)})
  192. try:
  193. status, headers, _ = self.request(
  194. "GET", "/", is_alive_fn=lambda: p.poll() is None)
  195. self._check_status(status, 302)
  196. for key in self.configuration.options("headers"):
  197. assert headers.get(key) == self.configuration.get(
  198. "headers", key)
  199. finally:
  200. p.terminate()
  201. p.wait()
  202. if os.name == "posix":
  203. assert p.returncode == 0
  204. def test_wsgi_server(self) -> None:
  205. config_path = os.path.join(self.colpath, "config")
  206. parser = RawConfigParser()
  207. parser.read_dict(configuration_to_dict(self.configuration))
  208. with open(config_path, "w") as f:
  209. parser.write(f)
  210. env = os.environ.copy()
  211. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  212. env["RADICALE_CONFIG"] = config_path
  213. raw_server_hosts = self.configuration.get_raw("server", "hosts")
  214. assert isinstance(raw_server_hosts, str)
  215. p = subprocess.Popen([
  216. sys.executable, "-m", "waitress", "--listen", raw_server_hosts,
  217. "radicale:application"], env=env)
  218. try:
  219. self.get("/", is_alive_fn=lambda: p.poll() is None, check=302)
  220. finally:
  221. p.terminate()
  222. p.wait()