test_dumb.py 8.3 KB

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