test_dumb.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. with_missing_remote_head = False
  91. def setUp(self):
  92. super().setUp()
  93. # Create a temporary directory for test repos
  94. self.temp_dir = tempfile.mkdtemp()
  95. self.addCleanup(rmtree_ro, self.temp_dir)
  96. # Create origin repository
  97. self.origin_path = os.path.join(self.temp_dir, "origin.git")
  98. os.mkdir(self.origin_path)
  99. run_git_or_fail(["init", "--bare"], cwd=self.origin_path)
  100. # Create a working repository to push from
  101. self.work_path = os.path.join(self.temp_dir, "work")
  102. os.mkdir(self.work_path)
  103. run_git_or_fail(["init"], cwd=self.work_path)
  104. run_git_or_fail(
  105. ["config", "user.email", "test@example.com"], cwd=self.work_path
  106. )
  107. run_git_or_fail(["config", "user.name", "Test User"], cwd=self.work_path)
  108. nb_files = 10
  109. if self.with_pack:
  110. # adding more files will create a pack file in the repository
  111. nb_files = 50
  112. for i in range(nb_files):
  113. test_file = os.path.join(self.work_path, f"test{i}.txt")
  114. with open(test_file, "w") as f:
  115. f.write(f"Hello, world {i}!\n")
  116. run_git_or_fail(["add", f"test{i}.txt"], cwd=self.work_path)
  117. run_git_or_fail(["commit", "-m", f"Commit {i}"], cwd=self.work_path)
  118. # Push to origin
  119. run_git_or_fail(
  120. ["remote", "add", "origin", self.origin_path], cwd=self.work_path
  121. )
  122. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  123. # Update server info for dumb HTTP
  124. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  125. if self.with_missing_remote_head:
  126. os.remove(os.path.join(self.origin_path, "HEAD"))
  127. # Start HTTP server
  128. self.server = DumbHTTPGitServer(self.origin_path)
  129. self.server.start()
  130. self.addCleanup(self.server.stop)
  131. pack_dir = os.path.join(self.origin_path, "objects", "pack")
  132. if self.with_pack:
  133. assert os.listdir(pack_dir)
  134. else:
  135. assert not os.listdir(pack_dir)
  136. @skipUnless(
  137. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  138. )
  139. def test_clone_dumb(self):
  140. dest_path = os.path.join(self.temp_dir, "cloned")
  141. # Use a dummy errstream to suppress progress output
  142. repo = clone(self.server.url, dest_path, errstream=io.BytesIO())
  143. assert b"HEAD" in repo
  144. def test_clone_from_dumb_http(self):
  145. """Test cloning from a dumb HTTP server."""
  146. dest_path = os.path.join(self.temp_dir, "cloned")
  147. # Use dulwich to clone via dumb HTTP
  148. client = HttpGitClient(self.server.url)
  149. # Create destination repo
  150. dest_repo = Repo.init(dest_path, mkdir=True)
  151. try:
  152. # Fetch from dumb HTTP
  153. def determine_wants(refs, depth=None):
  154. return [
  155. sha for ref, sha in refs.items() if ref.startswith(b"refs/heads/")
  156. ]
  157. result = client.fetch(
  158. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  159. )
  160. # Update refs
  161. for ref, sha in result.refs.items():
  162. if ref.startswith(b"refs/heads/"):
  163. dest_repo.refs[ref] = sha
  164. # Checkout files
  165. dest_repo.get_worktree().reset_index()
  166. # Verify the clone
  167. test_file = os.path.join(dest_path, "test0.txt")
  168. self.assertTrue(os.path.exists(test_file))
  169. with open(test_file) as f:
  170. self.assertEqual("Hello, world 0!\n", f.read())
  171. finally:
  172. # Ensure repo is closed before cleanup
  173. dest_repo.close()
  174. @skipUnless(
  175. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  176. )
  177. def test_fetch_new_commit_from_dumb_http(self):
  178. """Test fetching new commits from a dumb HTTP server."""
  179. # First clone the repository
  180. dest_path = os.path.join(self.temp_dir, "cloned")
  181. run_git_or_fail(["clone", self.server.url, dest_path])
  182. # Make a new commit in the origin
  183. test_file2 = os.path.join(self.work_path, "test2.txt")
  184. with open(test_file2, "w") as f:
  185. f.write("Second file\n")
  186. run_git_or_fail(["add", "test2.txt"], cwd=self.work_path)
  187. run_git_or_fail(["commit", "-m", "Second commit"], cwd=self.work_path)
  188. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  189. # Update server info again
  190. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  191. # Fetch with dulwich client
  192. client = HttpGitClient(self.server.url)
  193. dest_repo = Repo(dest_path)
  194. try:
  195. old_refs = dest_repo.get_refs()
  196. def determine_wants(refs, depth=None):
  197. wants = []
  198. for ref, sha in refs.items():
  199. if ref.startswith(b"refs/heads/") and sha != old_refs.get(ref):
  200. wants.append(sha)
  201. return wants
  202. result = client.fetch(
  203. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  204. )
  205. # Update refs
  206. for ref, sha in result.refs.items():
  207. if ref.startswith(b"refs/heads/"):
  208. dest_repo.refs[ref] = sha
  209. # Reset to new commit
  210. dest_repo.get_worktree().reset_index()
  211. # Verify the new file exists
  212. test_file2_dest = os.path.join(dest_path, "test2.txt")
  213. self.assertTrue(os.path.exists(test_file2_dest))
  214. with open(test_file2_dest) as f:
  215. self.assertEqual("Second file\n", f.read())
  216. finally:
  217. # Ensure repo is closed before cleanup
  218. dest_repo.close()
  219. @skipUnless(
  220. os.name == "posix", "Skipping on non-POSIX systems due to permission handling"
  221. )
  222. def test_fetch_from_dumb_http_with_tags(self):
  223. """Test fetching tags from a dumb HTTP server."""
  224. # Create a tag in origin
  225. run_git_or_fail(["tag", "-a", "v1.0", "-m", "Version 1.0"], cwd=self.work_path)
  226. run_git_or_fail(["push", "origin", "v1.0"], cwd=self.work_path)
  227. # Update server info
  228. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  229. # Clone with dulwich
  230. dest_path = os.path.join(self.temp_dir, "cloned_with_tags")
  231. dest_repo = Repo.init(dest_path, mkdir=True)
  232. try:
  233. client = HttpGitClient(self.server.url)
  234. def determine_wants(refs, depth=None):
  235. return [
  236. sha
  237. for ref, sha in refs.items()
  238. if ref.startswith((b"refs/heads/", b"refs/tags/"))
  239. ]
  240. result = client.fetch(
  241. "/", dest_repo, determine_wants=determine_wants, progress=no_op_progress
  242. )
  243. # Update refs
  244. for ref, sha in result.refs.items():
  245. dest_repo.refs[ref] = sha
  246. # Check that the tag exists
  247. self.assertIn(b"refs/tags/v1.0", dest_repo.refs)
  248. # Verify tag points to the right commit
  249. tag_sha = dest_repo.refs[b"refs/tags/v1.0"]
  250. tag_obj = dest_repo[tag_sha]
  251. self.assertEqual(b"tag", tag_obj.type_name)
  252. finally:
  253. # Ensure repo is closed before cleanup
  254. dest_repo.close()
  255. class DumbHTTPClientWithPackTests(DumbHTTPClientNoPackTests):
  256. with_pack = True
  257. class DumbHTTPClientWithMissingRemoteHEAD(DumbHTTPClientNoPackTests):
  258. with_missing_remote_head = True
  259. # we only want to test clone operation as removing the HEAD file
  260. # prevents any push operation used in tests below
  261. def test_fetch_from_dumb_http_with_tags(self):
  262. pass
  263. def test_fetch_new_commit_from_dumb_http(self):
  264. pass