test_server.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 subprocess
  24. import sys
  25. import tempfile
  26. import threading
  27. import time
  28. from configparser import ConfigParser
  29. from urllib import request
  30. from urllib.error import HTTPError, URLError
  31. from radicale import config, server
  32. from .helpers import get_file_path
  33. import pytest # isort:skip
  34. try:
  35. import gunicorn
  36. except ImportError:
  37. gunicorn = None
  38. class DisabledRedirectHandler(request.HTTPRedirectHandler):
  39. def http_error_302(self, req, fp, code, msg, headers):
  40. raise HTTPError(req.full_url, code, msg, headers, fp)
  41. http_error_301 = http_error_303 = http_error_307 = http_error_302
  42. class TestBaseServerRequests:
  43. """Test the internal server."""
  44. def setup(self):
  45. self.configuration = config.load()
  46. self.colpath = tempfile.mkdtemp()
  47. self.configuration["storage"]["filesystem_folder"] = self.colpath
  48. # Enable debugging for new processes
  49. self.configuration["logging"]["level"] = "debug"
  50. # Disable syncing to disk for better performance
  51. self.configuration["internal"]["filesystem_fsync"] = "False"
  52. self.shutdown_socket, shutdown_socket_out = socket.socketpair()
  53. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  54. # Find available port
  55. sock.bind(("127.0.0.1", 0))
  56. self.sockname = sock.getsockname()
  57. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  58. self.thread = threading.Thread(target=server.serve, args=(
  59. self.configuration, shutdown_socket_out))
  60. ssl_context = ssl.create_default_context()
  61. ssl_context.check_hostname = False
  62. ssl_context.verify_mode = ssl.CERT_NONE
  63. self.opener = request.build_opener(
  64. request.HTTPSHandler(context=ssl_context),
  65. DisabledRedirectHandler)
  66. def teardown(self):
  67. self.shutdown_socket.sendall(b" ")
  68. try:
  69. self.thread.join()
  70. except RuntimeError: # Thread never started
  71. pass
  72. shutil.rmtree(self.colpath)
  73. def request(self, method, path, data=None, is_alive_fn=None, **headers):
  74. """Send a request."""
  75. if is_alive_fn is None:
  76. is_alive_fn = self.thread.is_alive
  77. scheme = ("https" if self.configuration.getboolean("server", "ssl")
  78. else "http")
  79. req = request.Request(
  80. "%s://[%s]:%d%s" % (scheme, *self.sockname, path),
  81. data=data, headers=headers, method=method)
  82. while True:
  83. assert is_alive_fn()
  84. try:
  85. with self.opener.open(req) as f:
  86. return f.getcode(), f.info(), f.read().decode()
  87. except HTTPError as e:
  88. return e.code, e.headers, e.read().decode()
  89. except URLError as e:
  90. if not isinstance(e.reason, ConnectionRefusedError):
  91. raise
  92. time.sleep(0.1)
  93. def test_root(self):
  94. self.thread.start()
  95. status, _, _ = self.request("GET", "/")
  96. assert status == 302
  97. def test_ssl(self):
  98. self.configuration["server"]["ssl"] = "True"
  99. self.configuration["server"]["certificate"] = get_file_path("cert.pem")
  100. self.configuration["server"]["key"] = get_file_path("key.pem")
  101. self.thread.start()
  102. status, _, _ = self.request("GET", "/")
  103. assert status == 302
  104. @pytest.mark.skipif(not server.HAS_IPV6, reason="IPv6 not supported")
  105. def test_ipv6(self):
  106. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
  107. sock.setsockopt(server.IPPROTO_IPV6, server.IPV6_V6ONLY, 1)
  108. try:
  109. # Find available port
  110. sock.bind(("::1", 0))
  111. except OSError:
  112. pytest.skip("IPv6 not supported")
  113. self.sockname = sock.getsockname()[:2]
  114. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  115. savedEaiAddrfamily = server.EAI_ADDRFAMILY
  116. if os.name == "nt" and server.EAI_ADDRFAMILY is None:
  117. # HACK: incomplete errno conversion in WINE
  118. server.EAI_ADDRFAMILY = -9
  119. try:
  120. self.thread.start()
  121. status, _, _ = self.request("GET", "/")
  122. finally:
  123. server.EAI_ADDRFAMILY = savedEaiAddrfamily
  124. assert status == 302
  125. def test_command_line_interface(self):
  126. config_args = []
  127. for section, values in config.INITIAL_CONFIG.items():
  128. for option, data in values.items():
  129. long_name = "--{0}-{1}".format(
  130. section, option.replace("_", "-"))
  131. if data["type"] == bool:
  132. if not self.configuration.getboolean(section, option):
  133. long_name = "--no{0}".format(long_name[1:])
  134. config_args.append(long_name)
  135. else:
  136. config_args.append(long_name)
  137. config_args.append(self.configuration.get(section, option))
  138. env = os.environ.copy()
  139. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  140. p = subprocess.Popen(
  141. [sys.executable, "-m", "radicale"] + config_args, env=env)
  142. try:
  143. status, _, _ = self.request(
  144. "GET", "/", is_alive_fn=lambda: p.poll() is None)
  145. assert status == 302
  146. finally:
  147. p.terminate()
  148. p.wait()
  149. if os.name == "posix":
  150. assert p.returncode == 0
  151. @pytest.mark.skipif(not gunicorn, reason="gunicorn module not found")
  152. def test_wsgi_server(self):
  153. config = ConfigParser()
  154. config.read_dict(self.configuration)
  155. assert config.remove_section("internal")
  156. config_path = os.path.join(self.colpath, "config")
  157. with open(config_path, "w") as f:
  158. config.write(f)
  159. env = os.environ.copy()
  160. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  161. p = subprocess.Popen([
  162. sys.executable,
  163. "-c", "from gunicorn.app.wsgiapp import run; run()",
  164. "--bind", self.configuration["server"]["hosts"],
  165. "--env", "RADICALE_CONFIG=%s" % config_path, "radicale"], env=env)
  166. try:
  167. status, _, _ = self.request(
  168. "GET", "/", is_alive_fn=lambda: p.poll() is None)
  169. assert status == 302
  170. finally:
  171. p.terminate()
  172. p.wait()
  173. assert p.returncode == 0