test_dumb.py 9.7 KB

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