test_server.py 9.5 KB

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