test_repository.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # test_repo.py -- Git repo compatibility tests
  2. # Copyright (C) 2010 Google, Inc.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Compatibility tests for dulwich repositories."""
  21. from io import BytesIO
  22. from itertools import chain
  23. import os
  24. import tempfile
  25. from dulwich.objects import (
  26. hex_to_sha,
  27. )
  28. from dulwich.repo import (
  29. check_ref_format,
  30. Repo,
  31. )
  32. from dulwich.tests.compat.utils import (
  33. require_git_version,
  34. rmtree_ro,
  35. run_git_or_fail,
  36. CompatTestCase,
  37. )
  38. class ObjectStoreTestCase(CompatTestCase):
  39. """Tests for git repository compatibility."""
  40. def setUp(self):
  41. super().setUp()
  42. self._repo = self.import_repo("server_new.export")
  43. def _run_git(self, args):
  44. return run_git_or_fail(args, cwd=self._repo.path)
  45. def _parse_refs(self, output):
  46. refs = {}
  47. for line in BytesIO(output):
  48. fields = line.rstrip(b"\n").split(b" ")
  49. self.assertEqual(3, len(fields))
  50. refname, type_name, sha = fields
  51. check_ref_format(refname[5:])
  52. hex_to_sha(sha)
  53. refs[refname] = (type_name, sha)
  54. return refs
  55. def _parse_objects(self, output):
  56. return {s.rstrip(b"\n").split(b" ")[0] for s in BytesIO(output)}
  57. def test_bare(self):
  58. self.assertTrue(self._repo.bare)
  59. self.assertFalse(os.path.exists(os.path.join(self._repo.path, ".git")))
  60. def test_head(self):
  61. output = self._run_git(["rev-parse", "HEAD"])
  62. head_sha = output.rstrip(b"\n")
  63. hex_to_sha(head_sha)
  64. self.assertEqual(head_sha, self._repo.refs[b"HEAD"])
  65. def test_refs(self):
  66. output = self._run_git(
  67. ["for-each-ref", "--format=%(refname) %(objecttype) %(objectname)"]
  68. )
  69. expected_refs = self._parse_refs(output)
  70. actual_refs = {}
  71. for refname, sha in self._repo.refs.as_dict().items():
  72. if refname == b"HEAD":
  73. continue # handled in test_head
  74. obj = self._repo[sha]
  75. self.assertEqual(sha, obj.id)
  76. actual_refs[refname] = (obj.type_name, obj.id)
  77. self.assertEqual(expected_refs, actual_refs)
  78. # TODO(dborowitz): peeled ref tests
  79. def _get_loose_shas(self):
  80. output = self._run_git(["rev-list", "--all", "--objects", "--unpacked"])
  81. return self._parse_objects(output)
  82. def _get_all_shas(self):
  83. output = self._run_git(["rev-list", "--all", "--objects"])
  84. return self._parse_objects(output)
  85. def assertShasMatch(self, expected_shas, actual_shas_iter):
  86. actual_shas = set()
  87. for sha in actual_shas_iter:
  88. obj = self._repo[sha]
  89. self.assertEqual(sha, obj.id)
  90. actual_shas.add(sha)
  91. self.assertEqual(expected_shas, actual_shas)
  92. def test_loose_objects(self):
  93. # TODO(dborowitz): This is currently not very useful since
  94. # fast-imported repos only contained packed objects.
  95. expected_shas = self._get_loose_shas()
  96. self.assertShasMatch(
  97. expected_shas, self._repo.object_store._iter_loose_objects()
  98. )
  99. def test_packed_objects(self):
  100. expected_shas = self._get_all_shas() - self._get_loose_shas()
  101. self.assertShasMatch(
  102. expected_shas, chain.from_iterable(self._repo.object_store.packs)
  103. )
  104. def test_all_objects(self):
  105. expected_shas = self._get_all_shas()
  106. self.assertShasMatch(expected_shas, iter(self._repo.object_store))
  107. class WorkingTreeTestCase(ObjectStoreTestCase):
  108. """Test for compatibility with git-worktree."""
  109. min_git_version = (2, 5, 0)
  110. def create_new_worktree(self, repo_dir, branch):
  111. """Create a new worktree using git-worktree.
  112. Args:
  113. repo_dir: The directory of the main working tree.
  114. branch: The branch or commit to checkout in the new worktree.
  115. Returns: The path to the new working tree.
  116. """
  117. temp_dir = tempfile.mkdtemp()
  118. run_git_or_fail(["worktree", "add", temp_dir, branch], cwd=repo_dir)
  119. self.addCleanup(rmtree_ro, temp_dir)
  120. return temp_dir
  121. def setUp(self):
  122. super().setUp()
  123. self._worktree_path = self.create_new_worktree(self._repo.path, "branch")
  124. self._worktree_repo = Repo(self._worktree_path)
  125. self.addCleanup(self._worktree_repo.close)
  126. self._mainworktree_repo = self._repo
  127. self._number_of_working_tree = 2
  128. self._repo = self._worktree_repo
  129. def test_refs(self):
  130. super().test_refs()
  131. self.assertEqual(
  132. self._mainworktree_repo.refs.allkeys(), self._repo.refs.allkeys()
  133. )
  134. def test_head_equality(self):
  135. self.assertNotEqual(
  136. self._repo.refs[b"HEAD"], self._mainworktree_repo.refs[b"HEAD"]
  137. )
  138. def test_bare(self):
  139. self.assertFalse(self._repo.bare)
  140. self.assertTrue(os.path.isfile(os.path.join(self._repo.path, ".git")))
  141. def _parse_worktree_list(self, output):
  142. worktrees = []
  143. for line in BytesIO(output):
  144. fields = line.rstrip(b"\n").split()
  145. worktrees.append(tuple(f.decode() for f in fields))
  146. return worktrees
  147. def test_git_worktree_list(self):
  148. # 'git worktree list' was introduced in 2.7.0
  149. require_git_version((2, 7, 0))
  150. output = run_git_or_fail(["worktree", "list"], cwd=self._repo.path)
  151. worktrees = self._parse_worktree_list(output)
  152. self.assertEqual(len(worktrees), self._number_of_working_tree)
  153. self.assertEqual(worktrees[0][1], "(bare)")
  154. self.assertTrue(os.path.samefile(worktrees[0][0], self._mainworktree_repo.path))
  155. output = run_git_or_fail(["worktree", "list"], cwd=self._mainworktree_repo.path)
  156. worktrees = self._parse_worktree_list(output)
  157. self.assertEqual(len(worktrees), self._number_of_working_tree)
  158. self.assertEqual(worktrees[0][1], "(bare)")
  159. self.assertTrue(os.path.samefile(worktrees[0][0], self._mainworktree_repo.path))
  160. def test_git_worktree_config(self):
  161. """Test that git worktree config parsing matches the git CLI's behavior."""
  162. # Set some config value in the main repo using the git CLI
  163. require_git_version((2, 7, 0))
  164. test_name = "Jelmer"
  165. test_email = "jelmer@apache.org"
  166. run_git_or_fail(["config", "user.name", test_name], cwd=self._repo.path)
  167. run_git_or_fail(["config", "user.email", test_email], cwd=self._repo.path)
  168. worktree_cfg = self._worktree_repo.get_config()
  169. main_cfg = self._repo.get_config()
  170. # Assert that both the worktree repo and main repo have the same view of the config,
  171. # and that the config matches what we set with the git cli
  172. self.assertEqual(worktree_cfg, main_cfg)
  173. for c in [worktree_cfg, main_cfg]:
  174. self.assertEqual(test_name.encode(), c.get((b"user",), b"name"))
  175. self.assertEqual(test_email.encode(), c.get((b"user",), b"email"))
  176. # Read the config values in the worktree with the git cli and assert they match
  177. # the dulwich-parsed configs
  178. output_name = run_git_or_fail(["config", "user.name"], cwd=self._mainworktree_repo.path).decode().rstrip("\n")
  179. output_email = run_git_or_fail(["config", "user.email"], cwd=self._mainworktree_repo.path).decode().rstrip("\n")
  180. self.assertEqual(test_name, output_name)
  181. self.assertEqual(test_email, output_email)
  182. class InitNewWorkingDirectoryTestCase(WorkingTreeTestCase):
  183. """Test compatibility of Repo.init_new_working_directory."""
  184. min_git_version = (2, 5, 0)
  185. def setUp(self):
  186. super().setUp()
  187. self._other_worktree = self._repo
  188. worktree_repo_path = tempfile.mkdtemp()
  189. self.addCleanup(rmtree_ro, worktree_repo_path)
  190. self._repo = Repo._init_new_working_directory(
  191. worktree_repo_path, self._mainworktree_repo
  192. )
  193. self.addCleanup(self._repo.close)
  194. self._number_of_working_tree = 3
  195. def test_head_equality(self):
  196. self.assertEqual(
  197. self._repo.refs[b"HEAD"], self._mainworktree_repo.refs[b"HEAD"]
  198. )
  199. def test_bare(self):
  200. self.assertFalse(self._repo.bare)
  201. self.assertTrue(os.path.isfile(os.path.join(self._repo.path, ".git")))