test_dumb.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # test_dumb.py -- Compatibility tests for dumb HTTP git repositories
  2. # Copyright (C) 2025 Dulwich contributors
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as published by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Compatibility tests for dumb HTTP git repositories."""
  22. import io
  23. import os
  24. import sys
  25. import tempfile
  26. import threading
  27. from http.server import HTTPServer, SimpleHTTPRequestHandler
  28. from unittest import skipUnless
  29. from dulwich.client import HttpGitClient
  30. from dulwich.porcelain import clone
  31. from dulwich.repo import Repo
  32. from tests.compat.utils import (
  33. CompatTestCase,
  34. rmtree_ro,
  35. run_git_or_fail,
  36. )
  37. def no_op_progress(msg):
  38. """Progress callback that does nothing."""
  39. class DumbHTTPRequestHandler(SimpleHTTPRequestHandler):
  40. """HTTP request handler for dumb git protocol."""
  41. def __init__(self, *args, directory=None, **kwargs):
  42. self.directory = directory
  43. super().__init__(*args, directory=directory, **kwargs)
  44. def log_message(self, format, *args):
  45. # Suppress logging during tests
  46. pass
  47. class DumbHTTPGitServer:
  48. """Simple HTTP server for serving git repositories."""
  49. def __init__(self, root_path, port=0):
  50. self.root_path = root_path
  51. def handler(*args, **kwargs):
  52. return DumbHTTPRequestHandler(*args, directory=root_path, **kwargs)
  53. self.server = HTTPServer(("127.0.0.1", port), handler)
  54. self.server.allow_reuse_address = True
  55. self.port = self.server.server_port
  56. self.thread = None
  57. def start(self):
  58. """Start the HTTP server in a background thread."""
  59. self.thread = threading.Thread(target=self.server.serve_forever)
  60. self.thread.daemon = True
  61. self.thread.start()
  62. # Give the server a moment to start and verify it's listening
  63. import socket
  64. import time
  65. for i in range(50): # Try for up to 5 seconds
  66. try:
  67. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  68. sock.settimeout(0.1)
  69. result = sock.connect_ex(("127.0.0.1", self.port))
  70. sock.close()
  71. if result == 0:
  72. return # Server is ready
  73. except OSError:
  74. pass
  75. time.sleep(0.1)
  76. # If we get here, server failed to start
  77. raise RuntimeError(f"HTTP server failed to start on port {self.port}")
  78. def stop(self):
  79. """Stop the HTTP server."""
  80. self.server.shutdown()
  81. if self.thread:
  82. self.thread.join()
  83. @property
  84. def url(self):
  85. """Get the base URL for this server."""
  86. return f"http://127.0.0.1:{self.port}"
  87. class DumbHTTPClientNoPackTests(CompatTestCase):
  88. """Tests for dumb HTTP client against real git repositories."""
  89. with_pack = False
  90. def setUp(self):
  91. super().setUp()
  92. # Create a temporary directory for test repos
  93. self.temp_dir = tempfile.mkdtemp()
  94. self.addCleanup(rmtree_ro, self.temp_dir)
  95. # Create origin repository
  96. self.origin_path = os.path.join(self.temp_dir, "origin.git")
  97. os.mkdir(self.origin_path)
  98. run_git_or_fail(["init", "--bare"], cwd=self.origin_path)
  99. # Create a working repository to push from
  100. self.work_path = os.path.join(self.temp_dir, "work")
  101. os.mkdir(self.work_path)
  102. run_git_or_fail(["init"], cwd=self.work_path)
  103. run_git_or_fail(
  104. ["config", "user.email", "test@example.com"], cwd=self.work_path
  105. )
  106. run_git_or_fail(["config", "user.name", "Test User"], cwd=self.work_path)
  107. nb_files = 10
  108. if self.with_pack:
  109. # adding more files will create a pack file in the repository
  110. nb_files = 50
  111. for i in range(nb_files):
  112. test_file = os.path.join(self.work_path, f"test{i}.txt")
  113. with open(test_file, "w") as f:
  114. f.write(f"Hello, world {i}!\n")
  115. run_git_or_fail(["add", f"test{i}.txt"], cwd=self.work_path)
  116. run_git_or_fail(["commit", "-m", f"Commit {i}"], cwd=self.work_path)
  117. # Push to origin
  118. run_git_or_fail(
  119. ["remote", "add", "origin", self.origin_path], cwd=self.work_path
  120. )
  121. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  122. # Update server info for dumb HTTP
  123. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  124. # Start HTTP server
  125. self.server = DumbHTTPGitServer(self.origin_path)
  126. self.server.start()
  127. self.addCleanup(self.server.stop)
  128. pack_dir = os.path.join(self.origin_path, "objects", "pack")
  129. if self.with_pack:
  130. assert os.listdir(pack_dir)
  131. else:
  132. assert not os.listdir(pack_dir)
  133. @skipUnless(
  134. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  135. )
  136. def test_clone_dumb(self):
  137. dest_path = os.path.join(self.temp_dir, "cloned")
  138. # Use a dummy errstream to suppress progress output
  139. repo = clone(self.server.url, dest_path, errstream=io.BytesIO())
  140. assert b"HEAD" in repo
  141. def test_clone_from_dumb_http(self):
  142. """Test cloning from a dumb HTTP server."""
  143. dest_path = os.path.join(self.temp_dir, "cloned")
  144. # Use dulwich to clone via dumb HTTP
  145. client = HttpGitClient(self.server.url)
  146. # Create destination repo
  147. dest_repo = Repo.init(dest_path, mkdir=True)
  148. try:
  149. # Fetch from dumb HTTP
  150. def determine_wants(refs, depth=None):
  151. return [
  152. sha for ref, sha in refs.items() if ref.startswith(b"refs/heads/")
  153. ]
  154. result = client.fetch(
  155. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  156. )
  157. # Update refs
  158. for ref, sha in result.refs.items():
  159. if ref.startswith(b"refs/heads/"):
  160. dest_repo.refs[ref] = sha
  161. # Checkout files
  162. dest_repo.get_worktree().reset_index()
  163. # Verify the clone
  164. test_file = os.path.join(dest_path, "test0.txt")
  165. self.assertTrue(os.path.exists(test_file))
  166. with open(test_file) as f:
  167. self.assertEqual("Hello, world 0!\n", f.read())
  168. finally:
  169. # Ensure repo is closed before cleanup
  170. dest_repo.close()
  171. @skipUnless(
  172. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  173. )
  174. def test_fetch_new_commit_from_dumb_http(self):
  175. """Test fetching new commits from a dumb HTTP server."""
  176. # First clone the repository
  177. dest_path = os.path.join(self.temp_dir, "cloned")
  178. run_git_or_fail(["clone", self.server.url, dest_path])
  179. # Make a new commit in the origin
  180. test_file2 = os.path.join(self.work_path, "test2.txt")
  181. with open(test_file2, "w") as f:
  182. f.write("Second file\n")
  183. run_git_or_fail(["add", "test2.txt"], cwd=self.work_path)
  184. run_git_or_fail(["commit", "-m", "Second commit"], cwd=self.work_path)
  185. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  186. # Update server info again
  187. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  188. # Fetch with dulwich client
  189. client = HttpGitClient(self.server.url)
  190. dest_repo = Repo(dest_path)
  191. try:
  192. old_refs = dest_repo.get_refs()
  193. def determine_wants(refs, depth=None):
  194. wants = []
  195. for ref, sha in refs.items():
  196. if ref.startswith(b"refs/heads/") and sha != old_refs.get(ref):
  197. wants.append(sha)
  198. return wants
  199. result = client.fetch(
  200. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  201. )
  202. # Update refs
  203. for ref, sha in result.refs.items():
  204. if ref.startswith(b"refs/heads/"):
  205. dest_repo.refs[ref] = sha
  206. # Reset to new commit
  207. dest_repo.get_worktree().reset_index()
  208. # Verify the new file exists
  209. test_file2_dest = os.path.join(dest_path, "test2.txt")
  210. self.assertTrue(os.path.exists(test_file2_dest))
  211. with open(test_file2_dest) as f:
  212. self.assertEqual("Second file\n", f.read())
  213. finally:
  214. # Ensure repo is closed before cleanup
  215. dest_repo.close()
  216. @skipUnless(
  217. os.name == "posix", "Skipping on non-POSIX systems due to permission handling"
  218. )
  219. def test_fetch_from_dumb_http_with_tags(self):
  220. """Test fetching tags from a dumb HTTP server."""
  221. # Create a tag in origin
  222. run_git_or_fail(["tag", "-a", "v1.0", "-m", "Version 1.0"], cwd=self.work_path)
  223. run_git_or_fail(["push", "origin", "v1.0"], cwd=self.work_path)
  224. # Update server info
  225. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  226. # Clone with dulwich
  227. dest_path = os.path.join(self.temp_dir, "cloned_with_tags")
  228. dest_repo = Repo.init(dest_path, mkdir=True)
  229. try:
  230. client = HttpGitClient(self.server.url)
  231. def determine_wants(refs, depth=None):
  232. return [
  233. sha
  234. for ref, sha in refs.items()
  235. if ref.startswith((b"refs/heads/", b"refs/tags/"))
  236. ]
  237. result = client.fetch(
  238. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  239. )
  240. # Update refs
  241. for ref, sha in result.refs.items():
  242. dest_repo.refs[ref] = sha
  243. # Check that the tag exists
  244. self.assertIn(b"refs/tags/v1.0", dest_repo.refs)
  245. # Verify tag points to the right commit
  246. tag_sha = dest_repo.refs[b"refs/tags/v1.0"]
  247. tag_obj = dest_repo[tag_sha]
  248. self.assertEqual(b"tag", tag_obj.type_name)
  249. finally:
  250. # Ensure repo is closed before cleanup
  251. dest_repo.close()
  252. class DumbHTTPClientWithPackTests(DumbHTTPClientNoPackTests):
  253. with_pack = True