test_server.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. # Disable syncing to disk for better performance
  49. self.configuration["internal"]["filesystem_fsync"] = "False"
  50. self.shutdown_socket, shutdown_socket_out = socket.socketpair()
  51. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
  52. # Find available port
  53. sock.bind(("127.0.0.1", 0))
  54. self.sockname = sock.getsockname()
  55. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  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):
  65. self.shutdown_socket.sendall(b" ")
  66. try:
  67. self.thread.join()
  68. except RuntimeError: # Thread never started
  69. pass
  70. shutil.rmtree(self.colpath)
  71. def request(self, method, path, data=None, is_alive_fn=None, **headers):
  72. """Send a request."""
  73. if is_alive_fn is None:
  74. is_alive_fn = self.thread.is_alive
  75. scheme = ("https" if self.configuration.getboolean("server", "ssl")
  76. else "http")
  77. req = request.Request(
  78. "%s://[%s]:%d%s" % (scheme, *self.sockname, path),
  79. data=data, headers=headers, method=method)
  80. while True:
  81. assert is_alive_fn()
  82. try:
  83. with self.opener.open(req) as f:
  84. return f.getcode(), f.info(), f.read().decode()
  85. except HTTPError as e:
  86. return e.code, e.headers, e.read().decode()
  87. except URLError as e:
  88. if not isinstance(e.reason, ConnectionRefusedError):
  89. raise
  90. time.sleep(0.1)
  91. def test_root(self):
  92. self.thread.start()
  93. status, _, _ = self.request("GET", "/")
  94. assert status == 302
  95. def test_ssl(self):
  96. self.configuration["server"]["ssl"] = "True"
  97. self.configuration["server"]["certificate"] = get_file_path("cert.pem")
  98. self.configuration["server"]["key"] = get_file_path("key.pem")
  99. self.thread.start()
  100. status, _, _ = self.request("GET", "/")
  101. assert status == 302
  102. @pytest.mark.skipif(not server.HAS_IPV6, reason="IPv6 not supported")
  103. def test_ipv6(self):
  104. with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
  105. sock.setsockopt(server.IPPROTO_IPV6, server.IPV6_V6ONLY, 1)
  106. try:
  107. # Find available port
  108. sock.bind(("::1", 0))
  109. except OSError:
  110. pytest.skip("IPv6 not supported")
  111. self.sockname = sock.getsockname()[:2]
  112. self.configuration["server"]["hosts"] = "[%s]:%d" % self.sockname
  113. savedEaiAddrfamily = server.EAI_ADDRFAMILY
  114. if os.name == "nt" and server.EAI_ADDRFAMILY is None:
  115. # HACK: incomplete errno conversion in WINE
  116. server.EAI_ADDRFAMILY = -9
  117. try:
  118. self.thread.start()
  119. status, _, _ = self.request("GET", "/")
  120. finally:
  121. server.EAI_ADDRFAMILY = savedEaiAddrfamily
  122. assert status == 302
  123. def test_command_line_interface(self):
  124. config_args = []
  125. for section, values in config.INITIAL_CONFIG.items():
  126. for option, data in values.items():
  127. long_name = "--{0}-{1}".format(
  128. section, option.replace("_", "-"))
  129. if data["type"] == bool:
  130. if not self.configuration.getboolean(section, option):
  131. long_name = "--no{0}".format(long_name[1:])
  132. config_args.append(long_name)
  133. else:
  134. config_args.append(long_name)
  135. config_args.append(self.configuration.get(section, option))
  136. env = os.environ.copy()
  137. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  138. p = subprocess.Popen(
  139. [sys.executable, "-m", "radicale"] + config_args, env=env)
  140. try:
  141. status, _, _ = self.request(
  142. "GET", "/", is_alive_fn=lambda: p.poll() is None)
  143. assert status == 302
  144. finally:
  145. p.terminate()
  146. p.wait()
  147. if os.name == "posix":
  148. assert p.returncode == 0
  149. @pytest.mark.skipif(not gunicorn, reason="gunicorn module not found")
  150. def test_wsgi_server(self):
  151. config = ConfigParser()
  152. config.read_dict(self.configuration)
  153. assert config.remove_section("internal")
  154. config_path = os.path.join(self.colpath, "config")
  155. with open(config_path, "w") as f:
  156. config.write(f)
  157. env = os.environ.copy()
  158. env["PYTHONPATH"] = os.pathsep.join(sys.path)
  159. p = subprocess.Popen([
  160. sys.executable,
  161. "-c", "from gunicorn.app.wsgiapp import run; run()",
  162. "--bind", self.configuration["server"]["hosts"],
  163. "--env", "RADICALE_CONFIG=%s" % config_path, "radicale"], env=env)
  164. try:
  165. status, _, _ = self.request(
  166. "GET", "/", is_alive_fn=lambda: p.poll() is None)
  167. assert status == 302
  168. finally:
  169. p.terminate()
  170. p.wait()
  171. assert p.returncode == 0