test_release_robot.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # release_robot.py
  2. #
  3. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  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. """Tests for release_robot."""
  21. import datetime
  22. import logging
  23. import os
  24. import re
  25. import shutil
  26. import sys
  27. import tempfile
  28. import time
  29. import unittest
  30. from typing import ClassVar, Optional
  31. from unittest.mock import MagicMock, patch
  32. from dulwich.contrib import release_robot
  33. from dulwich.repo import Repo
  34. from dulwich.tests.utils import make_commit, make_tag
  35. BASEDIR = os.path.abspath(os.path.dirname(__file__)) # this directory
  36. def gmtime_to_datetime(gmt):
  37. return datetime.datetime(*time.gmtime(gmt)[:6])
  38. class TagPatternTests(unittest.TestCase):
  39. """test tag patterns."""
  40. def test_tag_pattern(self) -> None:
  41. """Test tag patterns."""
  42. test_cases = {
  43. "0.3": "0.3",
  44. "v0.3": "0.3",
  45. "release0.3": "0.3",
  46. "Release-0.3": "0.3",
  47. "v0.3rc1": "0.3rc1",
  48. "v0.3-rc1": "0.3-rc1",
  49. "v0.3-rc.1": "0.3-rc.1",
  50. "version 0.3": "0.3",
  51. "version_0.3_rc_1": "0.3_rc_1",
  52. "v1": "1",
  53. "0.3rc1": "0.3rc1",
  54. }
  55. for testcase, version in test_cases.items():
  56. matches = re.match(release_robot.PATTERN, testcase)
  57. self.assertEqual(matches.group(1), version)
  58. def test_pattern_no_match(self) -> None:
  59. """Test tags that don't match the pattern."""
  60. test_cases = [
  61. "master",
  62. "HEAD",
  63. "feature-branch",
  64. "no-numbers",
  65. "_",
  66. ]
  67. for testcase in test_cases:
  68. matches = re.match(release_robot.PATTERN, testcase)
  69. self.assertIsNone(matches)
  70. class GetRecentTagsTest(unittest.TestCase):
  71. """test get recent tags."""
  72. # Git repo for dulwich project
  73. test_repo = os.path.join(BASEDIR, "dulwich_test_repo.zip")
  74. committer = b"Mark Mikofski <mark.mikofski@sunpowercorp.com>"
  75. test_tags: ClassVar[list[bytes]] = [b"v0.1a", b"v0.1"]
  76. tag_test_data: ClassVar[
  77. dict[bytes, tuple[int, bytes, Optional[tuple[int, bytes]]]]
  78. ] = {
  79. test_tags[0]: (1484788003, b"3" * 40, None),
  80. test_tags[1]: (1484788314, b"1" * 40, (1484788401, b"2" * 40)),
  81. }
  82. @classmethod
  83. def setUpClass(cls) -> None:
  84. cls.projdir = tempfile.mkdtemp() # temporary project directory
  85. cls.repo = Repo.init(cls.projdir) # test repo
  86. obj_store = cls.repo.object_store # test repo object store
  87. # commit 1 ('2017-01-19T01:06:43')
  88. cls.c1 = make_commit(
  89. id=cls.tag_test_data[cls.test_tags[0]][1],
  90. commit_time=cls.tag_test_data[cls.test_tags[0]][0],
  91. message=b"unannotated tag",
  92. author=cls.committer,
  93. )
  94. obj_store.add_object(cls.c1)
  95. # tag 1: unannotated
  96. cls.t1 = cls.test_tags[0]
  97. cls.repo[b"refs/tags/" + cls.t1] = cls.c1.id # add unannotated tag
  98. # commit 2 ('2017-01-19T01:11:54')
  99. cls.c2 = make_commit(
  100. id=cls.tag_test_data[cls.test_tags[1]][1],
  101. commit_time=cls.tag_test_data[cls.test_tags[1]][0],
  102. message=b"annotated tag",
  103. parents=[cls.c1.id],
  104. author=cls.committer,
  105. )
  106. obj_store.add_object(cls.c2)
  107. # tag 2: annotated ('2017-01-19T01:13:21')
  108. cls.t2 = make_tag(
  109. cls.c2,
  110. id=cls.tag_test_data[cls.test_tags[1]][2][1],
  111. name=cls.test_tags[1],
  112. tag_time=cls.tag_test_data[cls.test_tags[1]][2][0],
  113. )
  114. obj_store.add_object(cls.t2)
  115. cls.repo[b"refs/heads/master"] = cls.c2.id
  116. cls.repo[b"refs/tags/" + cls.t2.name] = cls.t2.id # add annotated tag
  117. @classmethod
  118. def tearDownClass(cls) -> None:
  119. cls.repo.close()
  120. shutil.rmtree(cls.projdir)
  121. def test_get_recent_tags(self) -> None:
  122. """Test get recent tags."""
  123. tags = release_robot.get_recent_tags(self.projdir) # get test tags
  124. for tag, metadata in tags:
  125. tag = tag.encode("utf-8")
  126. test_data = self.tag_test_data[tag] # test data tag
  127. # test commit date, id and author name
  128. self.assertEqual(metadata[0], gmtime_to_datetime(test_data[0]))
  129. self.assertEqual(metadata[1].encode("utf-8"), test_data[1])
  130. self.assertEqual(metadata[2].encode("utf-8"), self.committer)
  131. # skip unannotated tags
  132. tag_obj = test_data[2]
  133. if not tag_obj:
  134. continue
  135. # tag date, id and name
  136. self.assertEqual(metadata[3][0], gmtime_to_datetime(tag_obj[0]))
  137. self.assertEqual(metadata[3][1].encode("utf-8"), tag_obj[1])
  138. self.assertEqual(metadata[3][2].encode("utf-8"), tag)
  139. def test_get_recent_tags_sorting(self) -> None:
  140. """Test that tags are sorted by commit time from newest to oldest."""
  141. tags = release_robot.get_recent_tags(self.projdir)
  142. # v0.1 should be first as it's newer
  143. self.assertEqual(tags[0][0], "v0.1")
  144. # v0.1a should be second as it's older
  145. self.assertEqual(tags[1][0], "v0.1a")
  146. def test_get_recent_tags_non_tag_refs(self) -> None:
  147. """Test that non-tag refs are ignored."""
  148. # Create a commit on a branch to test that it's not included
  149. branch_commit = make_commit(
  150. message=b"branch commit",
  151. author=self.committer,
  152. commit_time=int(time.time()),
  153. )
  154. self.repo.object_store.add_object(branch_commit)
  155. self.repo[b"refs/heads/test-branch"] = branch_commit.id
  156. # Get tags and ensure only the actual tags are returned
  157. tags = release_robot.get_recent_tags(self.projdir)
  158. self.assertEqual(len(tags), 2) # Still only 2 tags
  159. tag_names = [tag[0] for tag in tags]
  160. self.assertIn("v0.1", tag_names)
  161. self.assertIn("v0.1a", tag_names)
  162. self.assertNotIn("test-branch", tag_names)
  163. class GetCurrentVersionTests(unittest.TestCase):
  164. """Test get_current_version function."""
  165. def setUp(self):
  166. """Set up a test repository for each test."""
  167. self.projdir = tempfile.mkdtemp()
  168. self.repo = Repo.init(self.projdir)
  169. self.addCleanup(self.cleanup)
  170. def cleanup(self):
  171. """Clean up after test."""
  172. self.repo.close()
  173. shutil.rmtree(self.projdir)
  174. def test_no_tags(self):
  175. """Test behavior when repo has no tags."""
  176. # Create a repo with no tags
  177. result = release_robot.get_current_version(self.projdir)
  178. self.assertIsNone(result)
  179. def test_tag_with_pattern_match(self):
  180. """Test with a tag that matches the pattern."""
  181. # Create a test commit and tag
  182. c = make_commit(message=b"Test commit")
  183. self.repo.object_store.add_object(c)
  184. self.repo[b"refs/tags/v1.2.3"] = c.id
  185. self.repo[b"HEAD"] = c.id
  186. # Test that the version is extracted correctly
  187. result = release_robot.get_current_version(self.projdir)
  188. self.assertEqual("1.2.3", result)
  189. def test_tag_no_pattern_match(self):
  190. """Test with a tag that doesn't match the pattern."""
  191. # Create a test commit and tag that won't match the default pattern
  192. c = make_commit(message=b"Test commit")
  193. self.repo.object_store.add_object(c)
  194. self.repo[b"refs/tags/no-version-tag"] = c.id
  195. self.repo[b"HEAD"] = c.id
  196. # Test that the full tag is returned when no match
  197. result = release_robot.get_current_version(self.projdir)
  198. self.assertEqual("no-version-tag", result)
  199. def test_with_logger(self):
  200. """Test with a logger when regex match fails."""
  201. # Create a test commit and tag that won't match the pattern
  202. c = make_commit(message=b"Test commit")
  203. self.repo.object_store.add_object(c)
  204. self.repo[b"refs/tags/no-version-tag"] = c.id
  205. self.repo[b"HEAD"] = c.id
  206. # Create a logger
  207. logger = logging.getLogger("test_logger")
  208. # Test with the logger
  209. result = release_robot.get_current_version(self.projdir, logger=logger)
  210. self.assertEqual("no-version-tag", result)
  211. def test_custom_pattern(self):
  212. """Test with a custom regex pattern."""
  213. # Create a test commit and tag
  214. c = make_commit(message=b"Test commit")
  215. self.repo.object_store.add_object(c)
  216. self.repo[b"refs/tags/CUSTOM-99.88.77"] = c.id
  217. self.repo[b"HEAD"] = c.id
  218. # Test with a custom pattern
  219. custom_pattern = r"CUSTOM-([\d\.]+)"
  220. result = release_robot.get_current_version(self.projdir, pattern=custom_pattern)
  221. self.assertEqual("99.88.77", result)
  222. def test_with_logger_debug_call(self):
  223. """Test that the logger.debug method is actually called."""
  224. # Create a test commit and tag that won't match the pattern
  225. c = make_commit(message=b"Test commit")
  226. self.repo.object_store.add_object(c)
  227. self.repo[b"refs/tags/no-version-tag"] = c.id
  228. self.repo[b"HEAD"] = c.id
  229. # Create a mock logger
  230. mock_logger = MagicMock()
  231. # Test with the mock logger
  232. result = release_robot.get_current_version(self.projdir, logger=mock_logger)
  233. # Verify logger.debug was called
  234. mock_logger.debug.assert_called_once()
  235. # Check the tag name is in the debug message
  236. self.assertIn("no-version-tag", mock_logger.debug.call_args[0][2])
  237. # The result should still be the full tag
  238. self.assertEqual("no-version-tag", result)
  239. def test_multiple_tags(self):
  240. """Test behavior with multiple tags to ensure we get the most recent."""
  241. # Create multiple commits and tags with different timestamps
  242. c1 = make_commit(message=b"First commit", commit_time=1000)
  243. c2 = make_commit(message=b"Second commit", commit_time=2000, parents=[c1.id])
  244. self.repo.object_store.add_object(c1)
  245. self.repo.object_store.add_object(c2)
  246. # Add tags with older commit first
  247. self.repo[b"refs/tags/v0.9.0"] = c1.id
  248. self.repo[b"refs/tags/v1.0.0"] = c2.id
  249. self.repo[b"HEAD"] = c2.id
  250. # Get the current version - should be from the most recent commit
  251. result = release_robot.get_current_version(self.projdir)
  252. self.assertEqual("1.0.0", result)
  253. class MainFunctionTests(unittest.TestCase):
  254. """Test the __main__ block."""
  255. def setUp(self):
  256. """Set up a test repository."""
  257. self.projdir = tempfile.mkdtemp()
  258. self.repo = Repo.init(self.projdir)
  259. # Create a test commit and tag
  260. c = make_commit(message=b"Test commit")
  261. self.repo.object_store.add_object(c)
  262. self.repo[b"refs/tags/v3.2.1"] = c.id
  263. self.repo[b"HEAD"] = c.id
  264. self.addCleanup(self.cleanup)
  265. def cleanup(self):
  266. """Clean up after test."""
  267. self.repo.close()
  268. shutil.rmtree(self.projdir)
  269. @patch.object(sys, "argv", ["release_robot.py"])
  270. @patch("builtins.print")
  271. def test_main_default_dir(self, mock_print):
  272. """Test main function with default directory."""
  273. # Run the __main__ block code with mocked environment
  274. module_globals = {
  275. "__name__": "__main__",
  276. "sys": sys,
  277. "get_current_version": lambda projdir: "3.2.1",
  278. "PROJDIR": ".",
  279. }
  280. exec(
  281. compile(
  282. "if __name__ == '__main__':\n if len(sys.argv) > 1:\n _PROJDIR = sys.argv[1]\n else:\n _PROJDIR = PROJDIR\n print(get_current_version(projdir=_PROJDIR))",
  283. "<string>",
  284. "exec",
  285. ),
  286. module_globals,
  287. )
  288. # Check that print was called with the version
  289. mock_print.assert_called_once_with("3.2.1")
  290. @patch.object(sys, "argv", ["release_robot.py", "/custom/path"])
  291. @patch("builtins.print")
  292. @patch("dulwich.contrib.release_robot.get_current_version")
  293. def test_main_custom_dir(self, mock_get_version, mock_print):
  294. """Test main function with custom directory from command line."""
  295. mock_get_version.return_value = "4.5.6"
  296. # Run the __main__ block code with mocked environment
  297. module_globals = {
  298. "__name__": "__main__",
  299. "sys": sys,
  300. "get_current_version": mock_get_version,
  301. "PROJDIR": ".",
  302. }
  303. exec(
  304. compile(
  305. "if __name__ == '__main__':\n if len(sys.argv) > 1:\n _PROJDIR = sys.argv[1]\n else:\n _PROJDIR = PROJDIR\n print(get_current_version(projdir=_PROJDIR))",
  306. "<string>",
  307. "exec",
  308. ),
  309. module_globals,
  310. )
  311. # Check that get_current_version was called with the right arg
  312. mock_get_version.assert_called_once_with(projdir="/custom/path")
  313. mock_print.assert_called_once_with("4.5.6")