test_release_robot.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 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. class GetRecentTagsTest(unittest.TestCase):
  59. """test get recent tags."""
  60. # Git repo for dulwich project
  61. test_repo = os.path.join(BASEDIR, "dulwich_test_repo.zip")
  62. committer = b"Mark Mikofski <mark.mikofski@sunpowercorp.com>"
  63. test_tags: ClassVar[list[bytes]] = [b"v0.1a", b"v0.1"]
  64. tag_test_data: ClassVar[
  65. dict[bytes, tuple[int, bytes, Optional[tuple[int, bytes]]]]
  66. ] = {
  67. test_tags[0]: (1484788003, b"3" * 40, None),
  68. test_tags[1]: (1484788314, b"1" * 40, (1484788401, b"2" * 40)),
  69. }
  70. @classmethod
  71. def setUpClass(cls) -> None:
  72. cls.projdir = tempfile.mkdtemp() # temporary project directory
  73. cls.repo = Repo.init(cls.projdir) # test repo
  74. obj_store = cls.repo.object_store # test repo object store
  75. # commit 1 ('2017-01-19T01:06:43')
  76. cls.c1 = make_commit(
  77. id=cls.tag_test_data[cls.test_tags[0]][1],
  78. commit_time=cls.tag_test_data[cls.test_tags[0]][0],
  79. message=b"unannotated tag",
  80. author=cls.committer,
  81. )
  82. obj_store.add_object(cls.c1)
  83. # tag 1: unannotated
  84. cls.t1 = cls.test_tags[0]
  85. cls.repo[b"refs/tags/" + cls.t1] = cls.c1.id # add unannotated tag
  86. # commit 2 ('2017-01-19T01:11:54')
  87. cls.c2 = make_commit(
  88. id=cls.tag_test_data[cls.test_tags[1]][1],
  89. commit_time=cls.tag_test_data[cls.test_tags[1]][0],
  90. message=b"annotated tag",
  91. parents=[cls.c1.id],
  92. author=cls.committer,
  93. )
  94. obj_store.add_object(cls.c2)
  95. # tag 2: annotated ('2017-01-19T01:13:21')
  96. cls.t2 = make_tag(
  97. cls.c2,
  98. id=cls.tag_test_data[cls.test_tags[1]][2][1],
  99. name=cls.test_tags[1],
  100. tag_time=cls.tag_test_data[cls.test_tags[1]][2][0],
  101. )
  102. obj_store.add_object(cls.t2)
  103. cls.repo[b"refs/heads/master"] = cls.c2.id
  104. cls.repo[b"refs/tags/" + cls.t2.name] = cls.t2.id # add annotated tag
  105. @classmethod
  106. def tearDownClass(cls) -> None:
  107. cls.repo.close()
  108. shutil.rmtree(cls.projdir)
  109. def test_get_recent_tags(self) -> None:
  110. """Test get recent tags."""
  111. tags = release_robot.get_recent_tags(self.projdir) # get test tags
  112. for tag, metadata in tags:
  113. tag = tag.encode("utf-8")
  114. test_data = self.tag_test_data[tag] # test data tag
  115. # test commit date, id and author name
  116. self.assertEqual(metadata[0], gmtime_to_datetime(test_data[0]))
  117. self.assertEqual(metadata[1].encode("utf-8"), test_data[1])
  118. self.assertEqual(metadata[2].encode("utf-8"), self.committer)
  119. # skip unannotated tags
  120. tag_obj = test_data[2]
  121. if not tag_obj:
  122. continue
  123. # tag date, id and name
  124. self.assertEqual(metadata[3][0], gmtime_to_datetime(tag_obj[0]))
  125. self.assertEqual(metadata[3][1].encode("utf-8"), tag_obj[1])
  126. self.assertEqual(metadata[3][2].encode("utf-8"), tag)
  127. class GetCurrentVersionTests(unittest.TestCase):
  128. """Test get_current_version function."""
  129. def setUp(self):
  130. """Set up a test repository for each test."""
  131. self.projdir = tempfile.mkdtemp()
  132. self.repo = Repo.init(self.projdir)
  133. self.addCleanup(self.cleanup)
  134. def cleanup(self):
  135. """Clean up after test."""
  136. self.repo.close()
  137. shutil.rmtree(self.projdir)
  138. def test_no_tags(self):
  139. """Test behavior when repo has no tags."""
  140. # Create a repo with no tags
  141. result = release_robot.get_current_version(self.projdir)
  142. self.assertIsNone(result)
  143. def test_tag_with_pattern_match(self):
  144. """Test with a tag that matches the pattern."""
  145. # Create a test commit and tag
  146. c = make_commit(message=b"Test commit")
  147. self.repo.object_store.add_object(c)
  148. self.repo[b"refs/tags/v1.2.3"] = c.id
  149. self.repo[b"HEAD"] = c.id
  150. # Test that the version is extracted correctly
  151. result = release_robot.get_current_version(self.projdir)
  152. self.assertEqual("1.2.3", result)
  153. def test_tag_no_pattern_match(self):
  154. """Test with a tag that doesn't match the pattern."""
  155. # Create a test commit and tag that won't match the default pattern
  156. c = make_commit(message=b"Test commit")
  157. self.repo.object_store.add_object(c)
  158. self.repo[b"refs/tags/no-version-tag"] = c.id
  159. self.repo[b"HEAD"] = c.id
  160. # Test that the full tag is returned when no match
  161. result = release_robot.get_current_version(self.projdir)
  162. self.assertEqual("no-version-tag", result)
  163. def test_with_logger(self):
  164. """Test with a logger when regex match fails."""
  165. # Create a test commit and tag that won't match the pattern
  166. c = make_commit(message=b"Test commit")
  167. self.repo.object_store.add_object(c)
  168. self.repo[b"refs/tags/no-version-tag"] = c.id
  169. self.repo[b"HEAD"] = c.id
  170. # Create a logger
  171. logger = logging.getLogger("test_logger")
  172. # Test with the logger
  173. result = release_robot.get_current_version(self.projdir, logger=logger)
  174. self.assertEqual("no-version-tag", result)
  175. def test_custom_pattern(self):
  176. """Test with a custom regex pattern."""
  177. # Create a test commit and tag
  178. c = make_commit(message=b"Test commit")
  179. self.repo.object_store.add_object(c)
  180. self.repo[b"refs/tags/CUSTOM-99.88.77"] = c.id
  181. self.repo[b"HEAD"] = c.id
  182. # Test with a custom pattern
  183. custom_pattern = r"CUSTOM-([\d\.]+)"
  184. result = release_robot.get_current_version(self.projdir, pattern=custom_pattern)
  185. self.assertEqual("99.88.77", result)
  186. class MainFunctionTests(unittest.TestCase):
  187. """Test the __main__ block."""
  188. def setUp(self):
  189. """Set up a test repository."""
  190. self.projdir = tempfile.mkdtemp()
  191. self.repo = Repo.init(self.projdir)
  192. # Create a test commit and tag
  193. c = make_commit(message=b"Test commit")
  194. self.repo.object_store.add_object(c)
  195. self.repo[b"refs/tags/v3.2.1"] = c.id
  196. self.repo[b"HEAD"] = c.id
  197. self.addCleanup(self.cleanup)
  198. def cleanup(self):
  199. """Clean up after test."""
  200. self.repo.close()
  201. shutil.rmtree(self.projdir)
  202. @patch.object(sys, "argv", ["release_robot.py"])
  203. @patch("builtins.print")
  204. def test_main_default_dir(self, mock_print):
  205. """Test main function with default directory."""
  206. # Run the __main__ block code with mocked environment
  207. module_globals = {
  208. "__name__": "__main__",
  209. "sys": sys,
  210. "get_current_version": lambda projdir: "3.2.1",
  211. "PROJDIR": ".",
  212. }
  213. exec(
  214. compile(
  215. "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))",
  216. "<string>",
  217. "exec",
  218. ),
  219. module_globals,
  220. )
  221. # Check that print was called with the version
  222. mock_print.assert_called_once_with("3.2.1")
  223. @patch.object(sys, "argv", ["release_robot.py", "/custom/path"])
  224. @patch("builtins.print")
  225. @patch("dulwich.contrib.release_robot.get_current_version")
  226. def test_main_custom_dir(self, mock_get_version, mock_print):
  227. """Test main function with custom directory from command line."""
  228. mock_get_version.return_value = "4.5.6"
  229. # Run the __main__ block code with mocked environment
  230. module_globals = {
  231. "__name__": "__main__",
  232. "sys": sys,
  233. "get_current_version": mock_get_version,
  234. "PROJDIR": ".",
  235. }
  236. exec(
  237. compile(
  238. "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))",
  239. "<string>",
  240. "exec",
  241. ),
  242. module_globals,
  243. )
  244. # Check that get_current_version was called with the right arg
  245. mock_get_version.assert_called_once_with(projdir="/custom/path")
  246. mock_print.assert_called_once_with("4.5.6")