test_dumb.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 public 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 os
  23. import sys
  24. import tempfile
  25. import threading
  26. from http.server import HTTPServer, SimpleHTTPRequestHandler
  27. from unittest import skipUnless
  28. from dulwich.client import HttpGitClient
  29. from dulwich.porcelain import clone
  30. from dulwich.repo import Repo
  31. from tests.compat.utils import (
  32. CompatTestCase,
  33. rmtree_ro,
  34. run_git_or_fail,
  35. )
  36. class DumbHTTPRequestHandler(SimpleHTTPRequestHandler):
  37. """HTTP request handler for dumb git protocol."""
  38. def __init__(self, *args, directory=None, **kwargs):
  39. self.directory = directory
  40. super().__init__(*args, directory=directory, **kwargs)
  41. def log_message(self, format, *args):
  42. # Suppress logging during tests
  43. pass
  44. class DumbHTTPGitServer:
  45. """Simple HTTP server for serving git repositories."""
  46. def __init__(self, root_path, port=0):
  47. self.root_path = root_path
  48. def handler(*args, **kwargs):
  49. return DumbHTTPRequestHandler(*args, directory=root_path, **kwargs)
  50. self.server = HTTPServer(("127.0.0.1", port), handler)
  51. self.server.allow_reuse_address = True
  52. self.port = self.server.server_port
  53. self.thread = None
  54. def start(self):
  55. """Start the HTTP server in a background thread."""
  56. self.thread = threading.Thread(target=self.server.serve_forever)
  57. self.thread.daemon = True
  58. self.thread.start()
  59. # Give the server a moment to start and verify it's listening
  60. import socket
  61. import time
  62. for i in range(50): # Try for up to 5 seconds
  63. try:
  64. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  65. sock.settimeout(0.1)
  66. result = sock.connect_ex(("127.0.0.1", self.port))
  67. sock.close()
  68. if result == 0:
  69. return # Server is ready
  70. except OSError:
  71. pass
  72. time.sleep(0.1)
  73. # If we get here, server failed to start
  74. raise RuntimeError(f"HTTP server failed to start on port {self.port}")
  75. def stop(self):
  76. """Stop the HTTP server."""
  77. self.server.shutdown()
  78. if self.thread:
  79. self.thread.join()
  80. @property
  81. def url(self):
  82. """Get the base URL for this server."""
  83. return f"http://127.0.0.1:{self.port}"
  84. class DumbHTTPClientNoPackTests(CompatTestCase):
  85. """Tests for dumb HTTP client against real git repositories."""
  86. with_pack = False
  87. def setUp(self):
  88. super().setUp()
  89. # Create a temporary directory for test repos
  90. self.temp_dir = tempfile.mkdtemp()
  91. self.addCleanup(rmtree_ro, self.temp_dir)
  92. # Create origin repository
  93. self.origin_path = os.path.join(self.temp_dir, "origin.git")
  94. os.mkdir(self.origin_path)
  95. run_git_or_fail(["init", "--bare"], cwd=self.origin_path)
  96. # Create a working repository to push from
  97. self.work_path = os.path.join(self.temp_dir, "work")
  98. os.mkdir(self.work_path)
  99. run_git_or_fail(["init"], cwd=self.work_path)
  100. run_git_or_fail(
  101. ["config", "user.email", "test@example.com"], cwd=self.work_path
  102. )
  103. run_git_or_fail(["config", "user.name", "Test User"], cwd=self.work_path)
  104. nb_files = 10
  105. if self.with_pack:
  106. # adding more files will create a pack file in the repository
  107. nb_files = 50
  108. for i in range(nb_files):
  109. test_file = os.path.join(self.work_path, f"test{i}.txt")
  110. with open(test_file, "w") as f:
  111. f.write(f"Hello, world {i}!\n")
  112. run_git_or_fail(["add", f"test{i}.txt"], cwd=self.work_path)
  113. run_git_or_fail(["commit", "-m", f"Commit {i}"], cwd=self.work_path)
  114. # Push to origin
  115. run_git_or_fail(
  116. ["remote", "add", "origin", self.origin_path], cwd=self.work_path
  117. )
  118. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  119. # Update server info for dumb HTTP
  120. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  121. # Start HTTP server
  122. self.server = DumbHTTPGitServer(self.origin_path)
  123. self.server.start()
  124. self.addCleanup(self.server.stop)
  125. pack_dir = os.path.join(self.origin_path, "objects", "pack")
  126. if self.with_pack:
  127. assert os.listdir(pack_dir)
  128. else:
  129. assert not os.listdir(pack_dir)
  130. @skipUnless(
  131. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  132. )
  133. def test_clone_dumb(self):
  134. dest_path = os.path.join(self.temp_dir, "cloned")
  135. repo = clone(self.server.url, dest_path)
  136. assert b"HEAD" in repo
  137. def test_clone_from_dumb_http(self):
  138. """Test cloning from a dumb HTTP server."""
  139. dest_path = os.path.join(self.temp_dir, "cloned")
  140. # Use dulwich to clone via dumb HTTP
  141. client = HttpGitClient(self.server.url)
  142. # Create destination repo
  143. dest_repo = Repo.init(dest_path, mkdir=True)
  144. try:
  145. # Fetch from dumb HTTP
  146. def determine_wants(refs):
  147. return [
  148. sha for ref, sha in refs.items() if ref.startswith(b"refs/heads/")
  149. ]
  150. result = client.fetch("/", dest_repo, determine_wants=determine_wants)
  151. # Update refs
  152. for ref, sha in result.refs.items():
  153. if ref.startswith(b"refs/heads/"):
  154. dest_repo.refs[ref] = sha
  155. # Checkout files
  156. dest_repo.reset_index()
  157. # Verify the clone
  158. test_file = os.path.join(dest_path, "test0.txt")
  159. self.assertTrue(os.path.exists(test_file))
  160. with open(test_file) as f:
  161. self.assertEqual("Hello, world 0!\n", f.read())
  162. finally:
  163. # Ensure repo is closed before cleanup
  164. dest_repo.close()
  165. @skipUnless(
  166. sys.platform != "win32", "git clone from Python HTTPServer fails on Windows"
  167. )
  168. def test_fetch_new_commit_from_dumb_http(self):
  169. """Test fetching new commits from a dumb HTTP server."""
  170. # First clone the repository
  171. dest_path = os.path.join(self.temp_dir, "cloned")
  172. run_git_or_fail(["clone", self.server.url, dest_path])
  173. # Make a new commit in the origin
  174. test_file2 = os.path.join(self.work_path, "test2.txt")
  175. with open(test_file2, "w") as f:
  176. f.write("Second file\n")
  177. run_git_or_fail(["add", "test2.txt"], cwd=self.work_path)
  178. run_git_or_fail(["commit", "-m", "Second commit"], cwd=self.work_path)
  179. run_git_or_fail(["push", "origin", "master"], cwd=self.work_path)
  180. # Update server info again
  181. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  182. # Fetch with dulwich client
  183. client = HttpGitClient(self.server.url)
  184. dest_repo = Repo(dest_path)
  185. try:
  186. old_refs = dest_repo.get_refs()
  187. def determine_wants(refs):
  188. wants = []
  189. for ref, sha in refs.items():
  190. if ref.startswith(b"refs/heads/") and sha != old_refs.get(ref):
  191. wants.append(sha)
  192. return wants
  193. result = client.fetch("/", dest_repo, determine_wants=determine_wants)
  194. # Update refs
  195. for ref, sha in result.refs.items():
  196. if ref.startswith(b"refs/heads/"):
  197. dest_repo.refs[ref] = sha
  198. # Reset to new commit
  199. dest_repo.reset_index()
  200. # Verify the new file exists
  201. test_file2_dest = os.path.join(dest_path, "test2.txt")
  202. self.assertTrue(os.path.exists(test_file2_dest))
  203. with open(test_file2_dest) as f:
  204. self.assertEqual("Second file\n", f.read())
  205. finally:
  206. # Ensure repo is closed before cleanup
  207. dest_repo.close()
  208. @skipUnless(
  209. os.name == "posix", "Skipping on non-POSIX systems due to permission handling"
  210. )
  211. def test_fetch_from_dumb_http_with_tags(self):
  212. """Test fetching tags from a dumb HTTP server."""
  213. # Create a tag in origin
  214. run_git_or_fail(["tag", "-a", "v1.0", "-m", "Version 1.0"], cwd=self.work_path)
  215. run_git_or_fail(["push", "origin", "v1.0"], cwd=self.work_path)
  216. # Update server info
  217. run_git_or_fail(["update-server-info"], cwd=self.origin_path)
  218. # Clone with dulwich
  219. dest_path = os.path.join(self.temp_dir, "cloned_with_tags")
  220. dest_repo = Repo.init(dest_path, mkdir=True)
  221. try:
  222. client = HttpGitClient(self.server.url)
  223. def determine_wants(refs):
  224. return [
  225. sha
  226. for ref, sha in refs.items()
  227. if ref.startswith((b"refs/heads/", b"refs/tags/"))
  228. ]
  229. result = client.fetch("/", dest_repo, determine_wants=determine_wants)
  230. # Update refs
  231. for ref, sha in result.refs.items():
  232. dest_repo.refs[ref] = sha
  233. # Check that the tag exists
  234. self.assertIn(b"refs/tags/v1.0", dest_repo.refs)
  235. # Verify tag points to the right commit
  236. tag_sha = dest_repo.refs[b"refs/tags/v1.0"]
  237. tag_obj = dest_repo[tag_sha]
  238. self.assertEqual(b"tag", tag_obj.type_name)
  239. finally:
  240. # Ensure repo is closed before cleanup
  241. dest_repo.close()
  242. class DumbHTTPClientWithPackTests(DumbHTTPClientNoPackTests):
  243. with_pack = True