gclient_scm_test.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581
  1. #!/usr/bin/env vpython3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Unit tests for gclient_scm.py."""
  6. # pylint: disable=E1103
  7. from io import StringIO
  8. import json
  9. import logging
  10. import os
  11. import re
  12. from subprocess import Popen, PIPE, STDOUT
  13. import sys
  14. import tempfile
  15. import unittest
  16. from unittest import mock
  17. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  18. import gclient_scm
  19. import gclient_utils
  20. import git_cache
  21. import subprocess2
  22. from testing_support import fake_repos
  23. from testing_support import test_case_utils
  24. # TODO: Should fix these warnings.
  25. # pylint: disable=line-too-long
  26. GIT = 'git' if sys.platform != 'win32' else 'git.bat'
  27. # Disable global git cache
  28. git_cache.Mirror.SetCachePath(None)
  29. # Shortcut since this function is used often
  30. join = gclient_scm.os.path.join
  31. TIMESTAMP_RE = re.compile(r'\[[0-9]{1,2}:[0-9]{2}:[0-9]{2}\] (.*)', re.DOTALL)
  32. def strip_timestamps(value):
  33. lines = value.splitlines(True)
  34. for i in range(len(lines)):
  35. m = TIMESTAMP_RE.match(lines[i])
  36. if m:
  37. lines[i] = m.group(1)
  38. return ''.join(lines)
  39. class BasicTests(unittest.TestCase):
  40. @mock.patch('gclient_scm.scm.GIT.Capture')
  41. def testGetFirstRemoteUrl(self, mockCapture):
  42. REMOTE_STRINGS = [
  43. ('remote.origin.url E:\\foo\\bar', 'E:\\foo\\bar'),
  44. ('remote.origin.url /b/foo/bar', '/b/foo/bar'),
  45. ('remote.origin.url https://foo/bar', 'https://foo/bar'),
  46. ('remote.origin.url E:\\Fo Bar\\bax', 'E:\\Fo Bar\\bax'),
  47. ('remote.origin.url git://what/"do', 'git://what/"do')
  48. ]
  49. FAKE_PATH = '/fake/path'
  50. mockCapture.side_effect = [question for question, _ in REMOTE_STRINGS]
  51. for _, answer in REMOTE_STRINGS:
  52. self.assertEqual(
  53. gclient_scm.SCMWrapper._get_first_remote_url(FAKE_PATH), answer)
  54. expected_calls = [
  55. mock.call(['config', '--local', '--get-regexp', r'remote.*.url'],
  56. cwd=FAKE_PATH) for _ in REMOTE_STRINGS
  57. ]
  58. self.assertEqual(mockCapture.mock_calls, expected_calls)
  59. class BaseGitWrapperTestCase(unittest.TestCase, test_case_utils.TestCaseUtils):
  60. """This class doesn't use pymox."""
  61. class OptionsObject(object):
  62. def __init__(self, verbose=False, revision=None):
  63. self.auto_rebase = False
  64. self.verbose = verbose
  65. self.revision = revision
  66. self.deps_os = None
  67. self.force = False
  68. self.reset = False
  69. self.nohooks = False
  70. self.no_history = False
  71. self.upstream = False
  72. self.cache_dir = None
  73. self.merge = False
  74. self.jobs = 1
  75. self.break_repo_locks = False
  76. self.delete_unversioned_trees = False
  77. self.patch_ref = None
  78. self.patch_repo = None
  79. self.rebase_patch_ref = True
  80. self.reset_patch_ref = True
  81. sample_git_import = """blob
  82. mark :1
  83. data 6
  84. Hello
  85. blob
  86. mark :2
  87. data 4
  88. Bye
  89. reset refs/heads/main
  90. commit refs/heads/main
  91. mark :3
  92. author Bob <bob@example.com> 1253744361 -0700
  93. committer Bob <bob@example.com> 1253744361 -0700
  94. data 8
  95. A and B
  96. M 100644 :1 a
  97. M 100644 :2 b
  98. blob
  99. mark :4
  100. data 10
  101. Hello
  102. You
  103. blob
  104. mark :5
  105. data 8
  106. Bye
  107. You
  108. commit refs/heads/origin
  109. mark :6
  110. author Alice <alice@example.com> 1253744424 -0700
  111. committer Alice <alice@example.com> 1253744424 -0700
  112. data 13
  113. Personalized
  114. from :3
  115. M 100644 :4 a
  116. M 100644 :5 b
  117. blob
  118. mark :7
  119. data 5
  120. Mooh
  121. commit refs/heads/feature
  122. mark :8
  123. author Bob <bob@example.com> 1390311986 -0000
  124. committer Bob <bob@example.com> 1390311986 -0000
  125. data 6
  126. Add C
  127. from :3
  128. M 100644 :7 c
  129. reset refs/heads/main
  130. from :3
  131. """
  132. def Options(self, *args, **kwargs):
  133. return self.OptionsObject(*args, **kwargs)
  134. def checkstdout(self, expected):
  135. # pylint: disable=no-member
  136. value = sys.stdout.getvalue()
  137. sys.stdout.close()
  138. # Check that the expected output appears.
  139. self.assertIn(expected, strip_timestamps(value))
  140. @staticmethod
  141. def CreateGitRepo(git_import, path):
  142. """Do it for real."""
  143. try:
  144. Popen([GIT, 'init', '-q'], stdout=PIPE, stderr=STDOUT,
  145. cwd=path).communicate()
  146. except OSError:
  147. # git is not available, skip this test.
  148. return False
  149. Popen([GIT, 'fast-import', '--quiet'],
  150. stdin=PIPE,
  151. stdout=PIPE,
  152. stderr=STDOUT,
  153. cwd=path).communicate(input=git_import.encode())
  154. Popen([GIT, 'checkout', '-q'], stdout=PIPE, stderr=STDOUT,
  155. cwd=path).communicate()
  156. Popen([GIT, 'remote', 'add', '-f', 'origin', '.'],
  157. stdout=PIPE,
  158. stderr=STDOUT,
  159. cwd=path).communicate()
  160. Popen([GIT, 'checkout', '-b', 'new', 'origin/main', '-q'],
  161. stdout=PIPE,
  162. stderr=STDOUT,
  163. cwd=path).communicate()
  164. Popen([GIT, 'push', 'origin', 'origin/origin:origin/main', '-q'],
  165. stdout=PIPE,
  166. stderr=STDOUT,
  167. cwd=path).communicate()
  168. Popen([GIT, 'config', '--unset', 'remote.origin.fetch'],
  169. stdout=PIPE,
  170. stderr=STDOUT,
  171. cwd=path).communicate()
  172. Popen([GIT, 'config', 'user.email', 'someuser@chromium.org'],
  173. stdout=PIPE,
  174. stderr=STDOUT,
  175. cwd=path).communicate()
  176. Popen([GIT, 'config', 'user.name', 'Some User'],
  177. stdout=PIPE,
  178. stderr=STDOUT,
  179. cwd=path).communicate()
  180. # Set HEAD back to main
  181. Popen([GIT, 'checkout', 'main', '-q'],
  182. stdout=PIPE,
  183. stderr=STDOUT,
  184. cwd=path).communicate()
  185. return True
  186. def _GetAskForDataCallback(self, expected_prompt, return_value):
  187. def AskForData(prompt, options):
  188. self.assertEqual(prompt, expected_prompt)
  189. return return_value
  190. return AskForData
  191. def setUp(self):
  192. unittest.TestCase.setUp(self)
  193. test_case_utils.TestCaseUtils.setUp(self)
  194. self.url = 'git://foo'
  195. # The .git suffix allows gclient_scm to recognize the dir as a git repo
  196. # when cloning it locally
  197. self.root_dir = tempfile.mkdtemp('.git')
  198. self.relpath = '.'
  199. self.base_path = join(self.root_dir, self.relpath)
  200. self.enabled = self.CreateGitRepo(self.sample_git_import,
  201. self.base_path)
  202. mock.patch('sys.stdout', StringIO()).start()
  203. self.addCleanup(mock.patch.stopall)
  204. self.addCleanup(gclient_utils.rmtree, self.root_dir)
  205. class ManagedGitWrapperTestCase(BaseGitWrapperTestCase):
  206. def testRevertMissing(self):
  207. if not self.enabled:
  208. return
  209. options = self.Options()
  210. file_path = join(self.base_path, 'a')
  211. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  212. file_list = []
  213. scm.update(options, None, file_list)
  214. gclient_scm.os.remove(file_path)
  215. file_list = []
  216. scm.revert(options, self.args, file_list)
  217. self.assertEqual(file_list, [file_path])
  218. file_list = []
  219. scm.diff(options, self.args, file_list)
  220. self.assertEqual(file_list, [])
  221. sys.stdout.close()
  222. def testRevertNone(self):
  223. if not self.enabled:
  224. return
  225. options = self.Options()
  226. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  227. file_list = []
  228. scm.update(options, None, file_list)
  229. file_list = []
  230. scm.revert(options, self.args, file_list)
  231. self.assertEqual(file_list, [])
  232. self.assertEqual(scm.revinfo(options, self.args, None),
  233. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  234. sys.stdout.close()
  235. def testRevertModified(self):
  236. if not self.enabled:
  237. return
  238. options = self.Options()
  239. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  240. file_list = []
  241. scm.update(options, None, file_list)
  242. file_path = join(self.base_path, 'a')
  243. with open(file_path, 'a') as f:
  244. f.writelines('touched\n')
  245. file_list = []
  246. scm.revert(options, self.args, file_list)
  247. self.assertEqual(file_list, [file_path])
  248. file_list = []
  249. scm.diff(options, self.args, file_list)
  250. self.assertEqual(file_list, [])
  251. self.assertEqual(scm.revinfo(options, self.args, None),
  252. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  253. sys.stdout.close()
  254. def testRevertNew(self):
  255. if not self.enabled:
  256. return
  257. options = self.Options()
  258. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  259. file_list = []
  260. scm.update(options, None, file_list)
  261. file_path = join(self.base_path, 'c')
  262. with open(file_path, 'w') as f:
  263. f.writelines('new\n')
  264. Popen([GIT, 'add', 'c'], stdout=PIPE, stderr=STDOUT,
  265. cwd=self.base_path).communicate()
  266. file_list = []
  267. scm.revert(options, self.args, file_list)
  268. self.assertEqual(file_list, [file_path])
  269. file_list = []
  270. scm.diff(options, self.args, file_list)
  271. self.assertEqual(file_list, [])
  272. self.assertEqual(scm.revinfo(options, self.args, None),
  273. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  274. sys.stdout.close()
  275. def testStatusRef(self):
  276. if not self.enabled:
  277. return
  278. options = self.Options()
  279. file_paths = [join(self.base_path, 'a')]
  280. with open(file_paths[0], 'a') as f:
  281. f.writelines('touched\n')
  282. scm = gclient_scm.GitWrapper(self.url + '@refs/heads/feature',
  283. self.root_dir, self.relpath)
  284. file_paths.append(join(self.base_path, 'c')) # feature branch touches c
  285. file_list = []
  286. scm.status(options, self.args, file_list)
  287. self.assertEqual(file_list, file_paths)
  288. self.checkstdout((
  289. '\n________ running \'git -c core.quotePath=false diff --name-status '
  290. 'refs/remotes/origin/feature\' in \'%s\'\n\nM\ta\n') %
  291. join(self.root_dir, '.'))
  292. def testStatusNew(self):
  293. if not self.enabled:
  294. return
  295. options = self.Options()
  296. file_path = join(self.base_path, 'a')
  297. with open(file_path, 'a') as f:
  298. f.writelines('touched\n')
  299. scm = gclient_scm.GitWrapper(
  300. self.url + '@069c602044c5388d2d15c3f875b057c852003458',
  301. self.root_dir, self.relpath)
  302. file_list = []
  303. scm.status(options, self.args, file_list)
  304. self.assertEqual(file_list, [file_path])
  305. self.checkstdout((
  306. '\n________ running \'git -c core.quotePath=false diff --name-status '
  307. '069c602044c5388d2d15c3f875b057c852003458\' in \'%s\'\n\nM\ta\n') %
  308. join(self.root_dir, '.'))
  309. def testStatusNewNoBaseRev(self):
  310. if not self.enabled:
  311. return
  312. options = self.Options()
  313. file_path = join(self.base_path, 'a')
  314. with open(file_path, 'a') as f:
  315. f.writelines('touched\n')
  316. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  317. file_list = []
  318. scm.status(options, self.args, file_list)
  319. self.assertEqual(file_list, [file_path])
  320. self.checkstdout((
  321. '\n________ running \'git -c core.quotePath=false diff --name-status'
  322. '\' in \'%s\'\n\nM\ta\n') % join(self.root_dir, '.'))
  323. def testStatus2New(self):
  324. if not self.enabled:
  325. return
  326. options = self.Options()
  327. expected_file_list = []
  328. for f in ['a', 'b']:
  329. file_path = join(self.base_path, f)
  330. with open(file_path, 'a') as f:
  331. f.writelines('touched\n')
  332. expected_file_list.extend([file_path])
  333. scm = gclient_scm.GitWrapper(
  334. self.url + '@069c602044c5388d2d15c3f875b057c852003458',
  335. self.root_dir, self.relpath)
  336. file_list = []
  337. scm.status(options, self.args, file_list)
  338. expected_file_list = [join(self.base_path, x) for x in ['a', 'b']]
  339. self.assertEqual(sorted(file_list), expected_file_list)
  340. self.checkstdout((
  341. '\n________ running \'git -c core.quotePath=false diff --name-status '
  342. '069c602044c5388d2d15c3f875b057c852003458\' in \'%s\'\n\nM\ta\nM\tb\n'
  343. ) % join(self.root_dir, '.'))
  344. def testUpdateUpdate(self):
  345. if not self.enabled:
  346. return
  347. options = self.Options()
  348. expected_file_list = [join(self.base_path, x) for x in ['a', 'b']]
  349. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  350. file_list = []
  351. scm.update(options, (), file_list)
  352. self.assertEqual(file_list, expected_file_list)
  353. self.assertEqual(scm.revinfo(options, (), None),
  354. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  355. self.assertEqual(
  356. scm._Capture(['config', '--get', 'diff.ignoreSubmodules']), 'dirty')
  357. self.assertEqual(
  358. scm._Capture(['config', '--get', 'fetch.recurseSubmodules']), 'off')
  359. self.assertEqual(
  360. scm._Capture(['config', '--get', 'push.recurseSubmodules']), 'off')
  361. sys.stdout.close()
  362. def testUpdateMerge(self):
  363. if not self.enabled:
  364. return
  365. options = self.Options()
  366. options.merge = True
  367. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  368. scm._Run(['checkout', '-q', 'feature'], options)
  369. rev = scm.revinfo(options, (), None)
  370. file_list = []
  371. scm.update(options, (), file_list)
  372. self.assertEqual(file_list,
  373. [join(self.base_path, x) for x in ['a', 'b', 'c']])
  374. # The actual commit that is created is unstable, so we verify its tree
  375. # and parents instead.
  376. self.assertEqual(scm._Capture(['rev-parse', 'HEAD:']),
  377. 'd2e35c10ac24d6c621e14a1fcadceb533155627d')
  378. parent = 'HEAD^' if sys.platform != 'win32' else 'HEAD^^'
  379. self.assertEqual(scm._Capture(['rev-parse', parent + '1']), rev)
  380. self.assertEqual(scm._Capture(['rev-parse', parent + '2']),
  381. scm._Capture(['rev-parse', 'origin/main']))
  382. sys.stdout.close()
  383. def testUpdateRebase(self):
  384. if not self.enabled:
  385. return
  386. options = self.Options()
  387. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  388. scm._Run(['checkout', '-q', 'feature'], options)
  389. file_list = []
  390. # Fake a 'y' key press.
  391. scm._AskForData = self._GetAskForDataCallback(
  392. 'Cannot fast-forward merge, attempt to rebase? '
  393. '(y)es / (q)uit / (s)kip : ', 'y')
  394. scm.update(options, (), file_list)
  395. self.assertEqual(file_list,
  396. [join(self.base_path, x) for x in ['a', 'b', 'c']])
  397. # The actual commit that is created is unstable, so we verify its tree
  398. # and parent instead.
  399. self.assertEqual(scm._Capture(['rev-parse', 'HEAD:']),
  400. 'd2e35c10ac24d6c621e14a1fcadceb533155627d')
  401. parent = 'HEAD^' if sys.platform != 'win32' else 'HEAD^^'
  402. self.assertEqual(scm._Capture(['rev-parse', parent + '1']),
  403. scm._Capture(['rev-parse', 'origin/main']))
  404. sys.stdout.close()
  405. def testUpdateReset(self):
  406. if not self.enabled:
  407. return
  408. options = self.Options()
  409. options.reset = True
  410. dir_path = join(self.base_path, 'c')
  411. os.mkdir(dir_path)
  412. with open(join(dir_path, 'nested'), 'w') as f:
  413. f.writelines('new\n')
  414. file_path = join(self.base_path, 'file')
  415. with open(file_path, 'w') as f:
  416. f.writelines('new\n')
  417. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  418. file_list = []
  419. scm.update(options, (), file_list)
  420. self.assert_(gclient_scm.os.path.isdir(dir_path))
  421. self.assert_(gclient_scm.os.path.isfile(file_path))
  422. sys.stdout.close()
  423. def testUpdateResetUnsetsFetchConfig(self):
  424. if not self.enabled:
  425. return
  426. options = self.Options()
  427. options.reset = True
  428. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  429. scm._Run([
  430. 'config', 'remote.origin.fetch',
  431. '+refs/heads/bad/ref:refs/remotes/origin/bad/ref'
  432. ], options)
  433. file_list = []
  434. scm.update(options, (), file_list)
  435. self.assertEqual(scm.revinfo(options, (), None),
  436. '069c602044c5388d2d15c3f875b057c852003458')
  437. sys.stdout.close()
  438. def testUpdateResetDeleteUnversionedTrees(self):
  439. if not self.enabled:
  440. return
  441. options = self.Options()
  442. options.reset = True
  443. options.delete_unversioned_trees = True
  444. dir_path = join(self.base_path, 'dir')
  445. os.mkdir(dir_path)
  446. with open(join(dir_path, 'nested'), 'w') as f:
  447. f.writelines('new\n')
  448. file_path = join(self.base_path, 'file')
  449. with open(file_path, 'w') as f:
  450. f.writelines('new\n')
  451. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  452. file_list = []
  453. scm.update(options, (), file_list)
  454. self.assert_(not gclient_scm.os.path.isdir(dir_path))
  455. self.assert_(gclient_scm.os.path.isfile(file_path))
  456. sys.stdout.close()
  457. def testUpdateUnstagedConflict(self):
  458. if not self.enabled:
  459. return
  460. options = self.Options()
  461. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  462. file_path = join(self.base_path, 'b')
  463. with open(file_path, 'w') as f:
  464. f.writelines('conflict\n')
  465. try:
  466. scm.update(options, (), [])
  467. self.fail()
  468. except (gclient_scm.gclient_utils.Error,
  469. subprocess2.CalledProcessError):
  470. # The exact exception text varies across git versions so it's not
  471. # worth verifying it. It's fine as long as it throws.
  472. pass
  473. # Manually flush stdout since we can't verify it's content accurately
  474. # across git versions.
  475. sys.stdout.getvalue()
  476. sys.stdout.close()
  477. @unittest.skip('Skipping until crbug.com/670884 is resolved.')
  478. def testUpdateLocked(self):
  479. if not self.enabled:
  480. return
  481. options = self.Options()
  482. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  483. file_path = join(self.base_path, '.git', 'index.lock')
  484. with open(file_path, 'w'):
  485. pass
  486. with self.assertRaises(subprocess2.CalledProcessError):
  487. scm.update(options, (), [])
  488. sys.stdout.close()
  489. def testUpdateLockedBreak(self):
  490. if not self.enabled:
  491. return
  492. options = self.Options()
  493. options.break_repo_locks = True
  494. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  495. file_path = join(self.base_path, '.git', 'index.lock')
  496. with open(file_path, 'w'):
  497. pass
  498. scm.update(options, (), [])
  499. self.assertRegexpMatches(sys.stdout.getvalue(),
  500. r'breaking lock.*\.git[/|\\]index\.lock')
  501. self.assertFalse(os.path.exists(file_path))
  502. sys.stdout.close()
  503. def testUpdateConflict(self):
  504. if not self.enabled:
  505. return
  506. options = self.Options()
  507. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  508. file_path = join(self.base_path, 'b')
  509. with open(file_path, 'w') as f:
  510. f.writelines('conflict\n')
  511. scm._Run(['commit', '-am', 'test'], options)
  512. scm._AskForData = self._GetAskForDataCallback(
  513. 'Cannot fast-forward merge, attempt to rebase? '
  514. '(y)es / (q)uit / (s)kip : ', 'y')
  515. with self.assertRaises(gclient_scm.gclient_utils.Error) as e:
  516. scm.update(options, (), [])
  517. self.assertEqual(
  518. e.exception.args[0], 'Conflict while rebasing this branch.\n'
  519. 'Fix the conflict and run gclient again.\n'
  520. 'See \'man git-rebase\' for details.\n')
  521. with self.assertRaises(gclient_scm.gclient_utils.Error) as e:
  522. scm.update(options, (), [])
  523. self.assertEqual(
  524. e.exception.args[0], '\n____ . at refs/remotes/origin/main\n'
  525. '\tYou have uncommitted changes.\n'
  526. '\tcd into ., run git status to see changes,\n'
  527. '\tand commit, stash, or reset.\n')
  528. sys.stdout.close()
  529. def testRevinfo(self):
  530. if not self.enabled:
  531. return
  532. options = self.Options()
  533. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  534. rev_info = scm.revinfo(options, (), None)
  535. self.assertEqual(rev_info, '069c602044c5388d2d15c3f875b057c852003458')
  536. class ManagedGitWrapperTestCaseMock(unittest.TestCase):
  537. class OptionsObject(object):
  538. def __init__(self, verbose=False, revision=None, force=False):
  539. self.verbose = verbose
  540. self.revision = revision
  541. self.deps_os = None
  542. self.force = force
  543. self.reset = False
  544. self.nohooks = False
  545. self.break_repo_locks = False
  546. # TODO(maruel): Test --jobs > 1.
  547. self.jobs = 1
  548. self.patch_ref = None
  549. self.patch_repo = None
  550. self.rebase_patch_ref = True
  551. def Options(self, *args, **kwargs):
  552. return self.OptionsObject(*args, **kwargs)
  553. def checkstdout(self, expected):
  554. # pylint: disable=no-member
  555. value = sys.stdout.getvalue()
  556. sys.stdout.close()
  557. # Check that the expected output appears.
  558. self.assertIn(expected, strip_timestamps(value))
  559. def setUp(self):
  560. self.fake_hash_1 = 't0ta11yf4k3'
  561. self.fake_hash_2 = '3v3nf4k3r'
  562. self.url = 'git://foo'
  563. self.root_dir = '/tmp' if sys.platform != 'win32' else 't:\\tmp'
  564. self.relpath = 'fake'
  565. self.base_path = os.path.join(self.root_dir, self.relpath)
  566. self.backup_base_path = os.path.join(self.root_dir,
  567. 'old_%s.git' % self.relpath)
  568. mock.patch('gclient_scm.scm.GIT.ApplyEnvVars').start()
  569. mock.patch('gclient_scm.GitWrapper._Fetch').start()
  570. mock.patch('gclient_scm.GitWrapper._DeleteOrMove').start()
  571. mock.patch('sys.stdout', StringIO()).start()
  572. self.addCleanup(mock.patch.stopall)
  573. @mock.patch('scm.GIT.IsValidRevision')
  574. @mock.patch('os.path.isdir', lambda _: True)
  575. def testGetUsableRevGit(self, mockIsValidRevision):
  576. # pylint: disable=no-member
  577. options = self.Options(verbose=True)
  578. mockIsValidRevision.side_effect = lambda cwd, rev: rev != '1'
  579. git_scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  580. # A [fake] git sha1 with a git repo should work (this is in the case
  581. # that the LKGR gets flipped to git sha1's some day).
  582. self.assertEqual(git_scm.GetUsableRev(self.fake_hash_1, options),
  583. self.fake_hash_1)
  584. # An SVN rev with an existing purely git repo should raise an exception.
  585. self.assertRaises(gclient_scm.gclient_utils.Error, git_scm.GetUsableRev,
  586. '1', options)
  587. @mock.patch('gclient_scm.GitWrapper._Clone')
  588. @mock.patch('os.path.isdir')
  589. @mock.patch('os.path.exists')
  590. @mock.patch('subprocess2.check_output')
  591. def testUpdateNoDotGit(self, mockCheckOutput, mockExists, mockIsdir,
  592. mockClone):
  593. mockIsdir.side_effect = lambda path: path == self.base_path
  594. mockExists.side_effect = lambda path: path == self.base_path
  595. mockCheckOutput.side_effect = [b'refs/remotes/origin/main', b'', b'']
  596. options = self.Options()
  597. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  598. scm.update(options, None, [])
  599. env = gclient_scm.scm.GIT.ApplyEnvVars({})
  600. self.assertEqual(mockCheckOutput.mock_calls, [
  601. mock.call(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD'],
  602. cwd=self.base_path,
  603. env=env,
  604. stderr=-1),
  605. mock.call(['git', '-c', 'core.quotePath=false', 'ls-files'],
  606. cwd=self.base_path,
  607. env=env,
  608. stderr=-1),
  609. mock.call(['git', 'rev-parse', '--verify', 'HEAD'],
  610. cwd=self.base_path,
  611. env=env,
  612. stderr=-1),
  613. ])
  614. mockClone.assert_called_with('refs/remotes/origin/main', self.url,
  615. options)
  616. self.checkstdout('\n')
  617. @mock.patch('gclient_scm.GitWrapper._Clone')
  618. @mock.patch('os.path.isdir')
  619. @mock.patch('os.path.exists')
  620. @mock.patch('subprocess2.check_output')
  621. def testUpdateConflict(self, mockCheckOutput, mockExists, mockIsdir,
  622. mockClone):
  623. mockIsdir.side_effect = lambda path: path == self.base_path
  624. mockExists.side_effect = lambda path: path == self.base_path
  625. mockCheckOutput.side_effect = [b'refs/remotes/origin/main', b'', b'']
  626. mockClone.side_effect = [
  627. gclient_scm.subprocess2.CalledProcessError(None, None, None, None,
  628. None),
  629. None,
  630. ]
  631. options = self.Options()
  632. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  633. scm.update(options, None, [])
  634. env = gclient_scm.scm.GIT.ApplyEnvVars({})
  635. self.assertEqual(mockCheckOutput.mock_calls, [
  636. mock.call(['git', 'symbolic-ref', 'refs/remotes/origin/HEAD'],
  637. cwd=self.base_path,
  638. env=env,
  639. stderr=-1),
  640. mock.call(['git', '-c', 'core.quotePath=false', 'ls-files'],
  641. cwd=self.base_path,
  642. env=env,
  643. stderr=-1),
  644. mock.call(['git', 'rev-parse', '--verify', 'HEAD'],
  645. cwd=self.base_path,
  646. env=env,
  647. stderr=-1),
  648. ])
  649. mockClone.assert_called_with('refs/remotes/origin/main', self.url,
  650. options)
  651. self.checkstdout('\n')
  652. class UnmanagedGitWrapperTestCase(BaseGitWrapperTestCase):
  653. def checkInStdout(self, expected):
  654. # pylint: disable=no-member
  655. value = sys.stdout.getvalue()
  656. sys.stdout.close()
  657. self.assertIn(expected, value)
  658. def checkNotInStdout(self, expected):
  659. # pylint: disable=no-member
  660. value = sys.stdout.getvalue()
  661. sys.stdout.close()
  662. self.assertNotIn(expected, value)
  663. def getCurrentBranch(self):
  664. # Returns name of current branch or HEAD for detached HEAD
  665. branch = gclient_scm.scm.GIT.Capture(
  666. ['rev-parse', '--abbrev-ref', 'HEAD'], cwd=self.base_path)
  667. if branch == 'HEAD':
  668. return None
  669. return branch
  670. def testUpdateClone(self):
  671. if not self.enabled:
  672. return
  673. options = self.Options()
  674. origin_root_dir = self.root_dir
  675. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  676. self.root_dir = tempfile.mkdtemp()
  677. self.relpath = '.'
  678. self.base_path = join(self.root_dir, self.relpath)
  679. scm = gclient_scm.GitWrapper(origin_root_dir, self.root_dir,
  680. self.relpath)
  681. expected_file_list = [
  682. join(self.base_path, "a"),
  683. join(self.base_path, "b")
  684. ]
  685. file_list = []
  686. options.revision = 'unmanaged'
  687. scm.update(options, (), file_list)
  688. self.assertEqual(file_list, expected_file_list)
  689. self.assertEqual(scm.revinfo(options, (), None),
  690. '069c602044c5388d2d15c3f875b057c852003458')
  691. # indicates detached HEAD
  692. self.assertEqual(self.getCurrentBranch(), None)
  693. self.checkInStdout(
  694. 'Checked out refs/remotes/origin/main to a detached HEAD')
  695. def testUpdateCloneOnCommit(self):
  696. if not self.enabled:
  697. return
  698. options = self.Options()
  699. origin_root_dir = self.root_dir
  700. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  701. self.root_dir = tempfile.mkdtemp()
  702. self.relpath = '.'
  703. self.base_path = join(self.root_dir, self.relpath)
  704. url_with_commit_ref = origin_root_dir +\
  705. '@a7142dc9f0009350b96a11f372b6ea658592aa95'
  706. scm = gclient_scm.GitWrapper(url_with_commit_ref, self.root_dir,
  707. self.relpath)
  708. expected_file_list = [
  709. join(self.base_path, "a"),
  710. join(self.base_path, "b")
  711. ]
  712. file_list = []
  713. options.revision = 'unmanaged'
  714. scm.update(options, (), file_list)
  715. self.assertEqual(file_list, expected_file_list)
  716. self.assertEqual(scm.revinfo(options, (), None),
  717. 'a7142dc9f0009350b96a11f372b6ea658592aa95')
  718. # indicates detached HEAD
  719. self.assertEqual(self.getCurrentBranch(), None)
  720. self.checkInStdout(
  721. 'Checked out a7142dc9f0009350b96a11f372b6ea658592aa95 to a detached HEAD'
  722. )
  723. def testUpdateCloneOnBranch(self):
  724. if not self.enabled:
  725. return
  726. options = self.Options()
  727. origin_root_dir = self.root_dir
  728. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  729. self.root_dir = tempfile.mkdtemp()
  730. self.relpath = '.'
  731. self.base_path = join(self.root_dir, self.relpath)
  732. url_with_branch_ref = origin_root_dir + '@feature'
  733. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  734. self.relpath)
  735. expected_file_list = [
  736. join(self.base_path, "a"),
  737. join(self.base_path, "b"),
  738. join(self.base_path, "c")
  739. ]
  740. file_list = []
  741. options.revision = 'unmanaged'
  742. scm.update(options, (), file_list)
  743. self.assertEqual(file_list, expected_file_list)
  744. self.assertEqual(scm.revinfo(options, (), None),
  745. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  746. # indicates detached HEAD
  747. self.assertEqual(self.getCurrentBranch(), None)
  748. self.checkInStdout(
  749. 'Checked out 9a51244740b25fa2ded5252ca00a3178d3f665a9 '
  750. 'to a detached HEAD')
  751. def testUpdateCloneOnFetchedRemoteBranch(self):
  752. if not self.enabled:
  753. return
  754. options = self.Options()
  755. origin_root_dir = self.root_dir
  756. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  757. self.root_dir = tempfile.mkdtemp()
  758. self.relpath = '.'
  759. self.base_path = join(self.root_dir, self.relpath)
  760. url_with_branch_ref = origin_root_dir + '@refs/remotes/origin/feature'
  761. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  762. self.relpath)
  763. expected_file_list = [
  764. join(self.base_path, "a"),
  765. join(self.base_path, "b"),
  766. join(self.base_path, "c")
  767. ]
  768. file_list = []
  769. options.revision = 'unmanaged'
  770. scm.update(options, (), file_list)
  771. self.assertEqual(file_list, expected_file_list)
  772. self.assertEqual(scm.revinfo(options, (), None),
  773. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  774. # indicates detached HEAD
  775. self.assertEqual(self.getCurrentBranch(), None)
  776. self.checkInStdout(
  777. 'Checked out refs/remotes/origin/feature to a detached HEAD')
  778. def testUpdateCloneOnTrueRemoteBranch(self):
  779. if not self.enabled:
  780. return
  781. options = self.Options()
  782. origin_root_dir = self.root_dir
  783. self.addCleanup(gclient_utils.rmtree, origin_root_dir)
  784. self.root_dir = tempfile.mkdtemp()
  785. self.relpath = '.'
  786. self.base_path = join(self.root_dir, self.relpath)
  787. url_with_branch_ref = origin_root_dir + '@refs/heads/feature'
  788. scm = gclient_scm.GitWrapper(url_with_branch_ref, self.root_dir,
  789. self.relpath)
  790. expected_file_list = [
  791. join(self.base_path, "a"),
  792. join(self.base_path, "b"),
  793. join(self.base_path, "c")
  794. ]
  795. file_list = []
  796. options.revision = 'unmanaged'
  797. scm.update(options, (), file_list)
  798. self.assertEqual(file_list, expected_file_list)
  799. self.assertEqual(scm.revinfo(options, (), None),
  800. '9a51244740b25fa2ded5252ca00a3178d3f665a9')
  801. # @refs/heads/feature is AKA @refs/remotes/origin/feature in the clone,
  802. # so should be treated as such by gclient. TODO(mmoss): Though really,
  803. # we should only allow DEPS to specify branches as they are known in the
  804. # upstream repo, since the mapping into the local repo can be modified
  805. # by users (or we might even want to change the gclient defaults at some
  806. # point). But that will take more work to stop using refs/remotes/
  807. # everywhere that we do (and to stop assuming a DEPS ref will always
  808. # resolve locally, like when passing them to show-ref or rev-list).
  809. self.assertEqual(self.getCurrentBranch(), None)
  810. self.checkInStdout(
  811. 'Checked out refs/remotes/origin/feature to a detached HEAD')
  812. def testUpdateUpdate(self):
  813. if not self.enabled:
  814. return
  815. options = self.Options()
  816. expected_file_list = []
  817. scm = gclient_scm.GitWrapper(self.url, self.root_dir, self.relpath)
  818. file_list = []
  819. options.revision = 'unmanaged'
  820. scm.update(options, (), file_list)
  821. self.assertEqual(file_list, expected_file_list)
  822. self.assertEqual(scm.revinfo(options, (), None),
  823. '069c602044c5388d2d15c3f875b057c852003458')
  824. self.checkstdout('________ unmanaged solution; skipping .\n')
  825. class CipdWrapperTestCase(unittest.TestCase):
  826. def setUp(self):
  827. # Create this before setting up mocks.
  828. self._cipd_root_dir = tempfile.mkdtemp()
  829. self._workdir = tempfile.mkdtemp()
  830. self._cipd_instance_url = 'https://chrome-infra-packages.appspot.com'
  831. self._cipd_root = gclient_scm.CipdRoot(self._cipd_root_dir,
  832. self._cipd_instance_url)
  833. self._cipd_packages = [
  834. self._cipd_root.add_package('f', 'foo_package', 'foo_version'),
  835. self._cipd_root.add_package('b', 'bar_package', 'bar_version'),
  836. self._cipd_root.add_package('b', 'baz_package', 'baz_version'),
  837. ]
  838. mock.patch('tempfile.mkdtemp', lambda: self._workdir).start()
  839. mock.patch('gclient_scm.CipdRoot.add_package').start()
  840. mock.patch('gclient_scm.CipdRoot.clobber').start()
  841. mock.patch('gclient_scm.CipdRoot.ensure_file_resolve').start()
  842. mock.patch('gclient_scm.CipdRoot.ensure').start()
  843. self.addCleanup(mock.patch.stopall)
  844. self.addCleanup(gclient_utils.rmtree, self._cipd_root_dir)
  845. self.addCleanup(gclient_utils.rmtree, self._workdir)
  846. def createScmWithPackageThatSatisfies(self, condition):
  847. return gclient_scm.CipdWrapper(
  848. url=self._cipd_instance_url,
  849. root_dir=self._cipd_root_dir,
  850. relpath='fake_relpath',
  851. root=self._cipd_root,
  852. package=self.getPackageThatSatisfies(condition))
  853. def getPackageThatSatisfies(self, condition):
  854. for p in self._cipd_packages:
  855. if condition(p):
  856. return p
  857. self.fail('Unable to find a satisfactory package.')
  858. def testRevert(self):
  859. """Checks that revert does nothing."""
  860. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  861. scm.revert(None, (), [])
  862. @mock.patch('gclient_scm.gclient_utils.CheckCallAndFilter')
  863. @mock.patch('gclient_scm.gclient_utils.rmtree')
  864. def testRevinfo(self, mockRmtree, mockCheckCallAndFilter):
  865. """Checks that revinfo uses the JSON from cipd describe."""
  866. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  867. expected_revinfo = '0123456789abcdef0123456789abcdef01234567'
  868. json_contents = {
  869. 'result': {
  870. 'pin': {
  871. 'instance_id': expected_revinfo,
  872. }
  873. }
  874. }
  875. describe_json_path = join(self._workdir, 'describe.json')
  876. with open(describe_json_path, 'w') as describe_json:
  877. json.dump(json_contents, describe_json)
  878. revinfo = scm.revinfo(None, (), [])
  879. self.assertEqual(revinfo, expected_revinfo)
  880. mockRmtree.assert_called_with(self._workdir)
  881. mockCheckCallAndFilter.assert_called_with([
  882. 'cipd',
  883. 'describe',
  884. 'foo_package',
  885. '-log-level',
  886. 'error',
  887. '-version',
  888. 'foo_version',
  889. '-json-output',
  890. describe_json_path,
  891. ])
  892. def testUpdate(self):
  893. """Checks that update does nothing."""
  894. scm = self.createScmWithPackageThatSatisfies(lambda _: True)
  895. scm.update(None, (), [])
  896. class BranchHeadsFakeRepo(fake_repos.FakeReposBase):
  897. def populateGit(self):
  898. # Creates a tree that looks like this:
  899. #
  900. # 5 refs/branch-heads/5
  901. # |
  902. # 4
  903. # |
  904. # 1--2--3 refs/heads/main
  905. self._commit_git('repo_1', {'commit 1': 'touched'})
  906. self._commit_git('repo_1', {'commit 2': 'touched'})
  907. self._commit_git('repo_1', {'commit 3': 'touched'})
  908. self._create_ref('repo_1', 'refs/heads/main', 3)
  909. self._commit_git('repo_1', {'commit 4': 'touched'}, base=2)
  910. self._commit_git('repo_1', {'commit 5': 'touched'}, base=2)
  911. self._create_ref('repo_1', 'refs/branch-heads/5', 5)
  912. class BranchHeadsTest(fake_repos.FakeReposTestBase):
  913. FAKE_REPOS_CLASS = BranchHeadsFakeRepo
  914. def setUp(self):
  915. super(BranchHeadsTest, self).setUp()
  916. self.enabled = self.FAKE_REPOS.set_up_git()
  917. self.options = BaseGitWrapperTestCase.OptionsObject()
  918. self.url = self.git_base + 'repo_1'
  919. self.mirror = None
  920. mock.patch('sys.stdout', StringIO()).start()
  921. self.addCleanup(mock.patch.stopall)
  922. def setUpMirror(self):
  923. self.mirror = tempfile.mkdtemp('mirror')
  924. git_cache.Mirror.SetCachePath(self.mirror)
  925. self.addCleanup(gclient_utils.rmtree, self.mirror)
  926. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  927. def testCheckoutBranchHeads(self):
  928. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  929. file_list = []
  930. self.options.revision = 'refs/branch-heads/5'
  931. scm.update(self.options, None, file_list)
  932. self.assertEqual(self.githash('repo_1', 5),
  933. self.gitrevparse(self.root_dir))
  934. def testCheckoutUpdatedBranchHeads(self):
  935. # Travel back in time, and set refs/branch-heads/5 to its parent.
  936. subprocess2.check_call([
  937. 'git', 'update-ref', 'refs/branch-heads/5',
  938. self.githash('repo_1', 4)
  939. ],
  940. cwd=self.url)
  941. # Sync to refs/branch-heads/5
  942. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  943. self.options.revision = 'refs/branch-heads/5'
  944. scm.update(self.options, None, [])
  945. # Set refs/branch-heads/5 back to its original value.
  946. subprocess2.check_call([
  947. 'git', 'update-ref', 'refs/branch-heads/5',
  948. self.githash('repo_1', 5)
  949. ],
  950. cwd=self.url)
  951. # Attempt to sync to refs/branch-heads/5 again.
  952. self.testCheckoutBranchHeads()
  953. def testCheckoutBranchHeadsMirror(self):
  954. self.setUpMirror()
  955. self.testCheckoutBranchHeads()
  956. def testCheckoutUpdatedBranchHeadsMirror(self):
  957. self.setUpMirror()
  958. self.testCheckoutUpdatedBranchHeads()
  959. class GerritChangesFakeRepo(fake_repos.FakeReposBase):
  960. def populateGit(self):
  961. # Creates a tree that looks like this:
  962. #
  963. # 6 refs/changes/35/1235/1
  964. # |
  965. # 5 refs/changes/34/1234/1
  966. # |
  967. # 1--2--3--4 refs/heads/main
  968. # | |
  969. # | 11(5)--12 refs/heads/main-with-5
  970. # |
  971. # 7--8--9 refs/heads/feature
  972. # |
  973. # 10 refs/changes/36/1236/1
  974. #
  975. self._commit_git('repo_1', {'commit 1': 'touched'})
  976. self._commit_git('repo_1', {'commit 2': 'touched'})
  977. self._commit_git('repo_1', {'commit 3': 'touched'})
  978. self._commit_git('repo_1', {'commit 4': 'touched'})
  979. self._create_ref('repo_1', 'refs/heads/main', 4)
  980. # Create a change on top of commit 3 that consists of two commits.
  981. self._commit_git('repo_1', {
  982. 'commit 5': 'touched',
  983. 'change': '1234'
  984. },
  985. base=3)
  986. self._create_ref('repo_1', 'refs/changes/34/1234/1', 5)
  987. self._commit_git('repo_1', {'commit 6': 'touched', 'change': '1235'})
  988. self._create_ref('repo_1', 'refs/changes/35/1235/1', 6)
  989. # Create a refs/heads/feature branch on top of commit 2, consisting of
  990. # three commits.
  991. self._commit_git('repo_1', {'commit 7': 'touched'}, base=2)
  992. self._commit_git('repo_1', {'commit 8': 'touched'})
  993. self._commit_git('repo_1', {'commit 9': 'touched'})
  994. self._create_ref('repo_1', 'refs/heads/feature', 9)
  995. # Create a change of top of commit 8.
  996. self._commit_git('repo_1', {
  997. 'commit 10': 'touched',
  998. 'change': '1236'
  999. },
  1000. base=8)
  1001. self._create_ref('repo_1', 'refs/changes/36/1236/1', 10)
  1002. # Create a refs/heads/main-with-5 on top of commit 3 which is a branch
  1003. # where refs/changes/34/1234/1 (commit 5) has already landed as commit
  1004. # 11.
  1005. self._commit_git(
  1006. 'repo_1',
  1007. # This is really commit 11, but has the changes of commit 5
  1008. {
  1009. 'commit 5': 'touched',
  1010. 'change': '1234'
  1011. },
  1012. base=3)
  1013. self._commit_git('repo_1', {'commit 12': 'touched'})
  1014. self._create_ref('repo_1', 'refs/heads/main-with-5', 12)
  1015. class GerritChangesTest(fake_repos.FakeReposTestBase):
  1016. FAKE_REPOS_CLASS = GerritChangesFakeRepo
  1017. def setUp(self):
  1018. super(GerritChangesTest, self).setUp()
  1019. self.enabled = self.FAKE_REPOS.set_up_git()
  1020. self.options = BaseGitWrapperTestCase.OptionsObject()
  1021. self.url = self.git_base + 'repo_1'
  1022. self.mirror = None
  1023. mock.patch('sys.stdout', StringIO()).start()
  1024. self.addCleanup(mock.patch.stopall)
  1025. def setUpMirror(self):
  1026. self.mirror = tempfile.mkdtemp()
  1027. git_cache.Mirror.SetCachePath(self.mirror)
  1028. self.addCleanup(gclient_utils.rmtree, self.mirror)
  1029. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  1030. def assertCommits(self, commits):
  1031. """Check that all, and only |commits| are present in the current checkout.
  1032. """
  1033. for i in commits:
  1034. name = os.path.join(self.root_dir, 'commit ' + str(i))
  1035. self.assertTrue(os.path.exists(name), 'Commit not found: %s' % name)
  1036. all_commits = set(range(1, len(self.FAKE_REPOS.git_hashes['repo_1'])))
  1037. for i in all_commits - set(commits):
  1038. name = os.path.join(self.root_dir, 'commit ' + str(i))
  1039. self.assertFalse(os.path.exists(name),
  1040. 'Unexpected commit: %s' % name)
  1041. def testCanCloneGerritChange(self):
  1042. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1043. file_list = []
  1044. self.options.revision = 'refs/changes/35/1235/1'
  1045. scm.update(self.options, None, file_list)
  1046. self.assertEqual(self.githash('repo_1', 6),
  1047. self.gitrevparse(self.root_dir))
  1048. def testCanSyncToGerritChange(self):
  1049. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1050. file_list = []
  1051. self.options.revision = self.githash('repo_1', 1)
  1052. scm.update(self.options, None, file_list)
  1053. self.assertEqual(self.githash('repo_1', 1),
  1054. self.gitrevparse(self.root_dir))
  1055. self.options.revision = 'refs/changes/35/1235/1'
  1056. scm.update(self.options, None, file_list)
  1057. self.assertEqual(self.githash('repo_1', 6),
  1058. self.gitrevparse(self.root_dir))
  1059. def testCanCloneGerritChangeMirror(self):
  1060. self.setUpMirror()
  1061. self.testCanCloneGerritChange()
  1062. def testCanSyncToGerritChangeMirror(self):
  1063. self.setUpMirror()
  1064. self.testCanSyncToGerritChange()
  1065. def testMirrorPushUrl(self):
  1066. self.setUpMirror()
  1067. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1068. file_list = []
  1069. self.assertIsNotNone(scm._GetMirror(self.url, self.options))
  1070. scm.update(self.options, None, file_list)
  1071. fetch_url = scm._Capture(['remote', 'get-url', 'origin'])
  1072. self.assertTrue(
  1073. fetch_url.startswith(self.mirror),
  1074. msg='\n'.join([
  1075. 'Repository fetch url should be in the git cache mirror directory.',
  1076. ' fetch_url: %s' % fetch_url,
  1077. ' mirror: %s' % self.mirror
  1078. ]))
  1079. push_url = scm._Capture(['remote', 'get-url', '--push', 'origin'])
  1080. self.assertEqual(push_url, self.url)
  1081. def testAppliesPatchOnTopOfMasterByDefault(self):
  1082. """Test the default case, where we apply a patch on top of main."""
  1083. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1084. file_list = []
  1085. # Make sure we don't specify a revision.
  1086. self.options.revision = None
  1087. scm.update(self.options, None, file_list)
  1088. self.assertEqual(self.githash('repo_1', 4),
  1089. self.gitrevparse(self.root_dir))
  1090. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1091. 'refs/heads/main', self.options, file_list)
  1092. self.assertCommits([1, 2, 3, 4, 5, 6])
  1093. self.assertEqual(self.githash('repo_1', 4),
  1094. self.gitrevparse(self.root_dir))
  1095. def testCheckoutOlderThanPatchBase(self):
  1096. """Test applying a patch on an old checkout.
  1097. We first checkout commit 1, and try to patch refs/changes/35/1235/1, which
  1098. contains commits 5 and 6, and is based on top of commit 3.
  1099. The final result should contain commits 1, 5 and 6, but not commits 2 or 3.
  1100. """
  1101. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1102. file_list = []
  1103. # Sync to commit 1
  1104. self.options.revision = self.githash('repo_1', 1)
  1105. scm.update(self.options, None, file_list)
  1106. self.assertEqual(self.githash('repo_1', 1),
  1107. self.gitrevparse(self.root_dir))
  1108. # Apply the change on top of that.
  1109. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1110. 'refs/heads/main', self.options, file_list)
  1111. self.assertCommits([1, 5, 6])
  1112. self.assertEqual(self.githash('repo_1', 1),
  1113. self.gitrevparse(self.root_dir))
  1114. def testCheckoutOriginFeature(self):
  1115. """Tests that we can apply a patch on a branch other than main."""
  1116. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1117. file_list = []
  1118. # Sync to remote's refs/heads/feature
  1119. self.options.revision = 'refs/heads/feature'
  1120. scm.update(self.options, None, file_list)
  1121. self.assertEqual(self.githash('repo_1', 9),
  1122. self.gitrevparse(self.root_dir))
  1123. # Apply the change on top of that.
  1124. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1125. 'refs/heads/feature', self.options, file_list)
  1126. self.assertCommits([1, 2, 7, 8, 9, 10])
  1127. self.assertEqual(self.githash('repo_1', 9),
  1128. self.gitrevparse(self.root_dir))
  1129. def testCheckoutOriginFeatureOnOldRevision(self):
  1130. """Tests that we can apply a patch on an old checkout, on a branch other
  1131. than main."""
  1132. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1133. file_list = []
  1134. # Sync to remote's refs/heads/feature on an old revision
  1135. self.options.revision = self.githash('repo_1', 7)
  1136. scm.update(self.options, None, file_list)
  1137. self.assertEqual(self.githash('repo_1', 7),
  1138. self.gitrevparse(self.root_dir))
  1139. # Apply the change on top of that.
  1140. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1141. 'refs/heads/feature', self.options, file_list)
  1142. # We shouldn't have rebased on top of 2 (which is the merge base between
  1143. # remote's main branch and the change) but on top of 7 (which is the
  1144. # merge base between remote's feature branch and the change).
  1145. self.assertCommits([1, 2, 7, 10])
  1146. self.assertEqual(self.githash('repo_1', 7),
  1147. self.gitrevparse(self.root_dir))
  1148. def testCheckoutOriginFeaturePatchBranch(self):
  1149. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1150. file_list = []
  1151. # Sync to the hash instead of remote's refs/heads/feature.
  1152. self.options.revision = self.githash('repo_1', 9)
  1153. scm.update(self.options, None, file_list)
  1154. self.assertEqual(self.githash('repo_1', 9),
  1155. self.gitrevparse(self.root_dir))
  1156. # Apply refs/changes/34/1234/1, created for remote's main branch on top
  1157. # of remote's feature branch.
  1158. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1159. 'refs/heads/main', self.options, file_list)
  1160. # Commits 5 and 6 are part of the patch, and commits 1, 2, 7, 8 and 9
  1161. # are part of remote's feature branch.
  1162. self.assertCommits([1, 2, 5, 6, 7, 8, 9])
  1163. self.assertEqual(self.githash('repo_1', 9),
  1164. self.gitrevparse(self.root_dir))
  1165. def testDoesntRebasePatchMaster(self):
  1166. """Tests that we can apply a patch without rebasing it."""
  1167. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1168. file_list = []
  1169. self.options.rebase_patch_ref = False
  1170. scm.update(self.options, None, file_list)
  1171. self.assertEqual(self.githash('repo_1', 4),
  1172. self.gitrevparse(self.root_dir))
  1173. # Apply the change on top of that.
  1174. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1175. 'refs/heads/main', self.options, file_list)
  1176. self.assertCommits([1, 2, 3, 5, 6])
  1177. self.assertEqual(self.githash('repo_1', 5),
  1178. self.gitrevparse(self.root_dir))
  1179. def testDoesntRebasePatchOldCheckout(self):
  1180. """Tests that we can apply a patch without rebasing it on an old checkout.
  1181. """
  1182. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1183. file_list = []
  1184. # Sync to commit 1
  1185. self.options.revision = self.githash('repo_1', 1)
  1186. self.options.rebase_patch_ref = False
  1187. scm.update(self.options, None, file_list)
  1188. self.assertEqual(self.githash('repo_1', 1),
  1189. self.gitrevparse(self.root_dir))
  1190. # Apply the change on top of that.
  1191. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1192. 'refs/heads/main', self.options, file_list)
  1193. self.assertCommits([1, 2, 3, 5, 6])
  1194. self.assertEqual(self.githash('repo_1', 5),
  1195. self.gitrevparse(self.root_dir))
  1196. def testDoesntSoftResetIfNotAskedTo(self):
  1197. """Test that we can apply a patch without doing a soft reset."""
  1198. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1199. file_list = []
  1200. self.options.reset_patch_ref = False
  1201. scm.update(self.options, None, file_list)
  1202. self.assertEqual(self.githash('repo_1', 4),
  1203. self.gitrevparse(self.root_dir))
  1204. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1205. 'refs/heads/main', self.options, file_list)
  1206. self.assertCommits([1, 2, 3, 4, 5, 6])
  1207. # The commit hash after cherry-picking is not known, but it must be
  1208. # different from what the repo was synced at before patching.
  1209. self.assertNotEqual(self.githash('repo_1', 4),
  1210. self.gitrevparse(self.root_dir))
  1211. @mock.patch('gerrit_util.GetChange', return_value={'topic': 'test_topic'})
  1212. @mock.patch('gerrit_util.QueryChanges',
  1213. return_value=[{
  1214. '_number': 1234
  1215. }, {
  1216. '_number': 1235,
  1217. 'current_revision': 'abc',
  1218. 'revisions': {
  1219. 'abc': {
  1220. 'ref': 'refs/changes/35/1235/1'
  1221. }
  1222. }
  1223. }])
  1224. def testDownloadTopics(self, query_changes_mock, get_change_mock):
  1225. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1226. file_list = []
  1227. self.options.revision = 'refs/changes/34/1234/1'
  1228. scm.update(self.options, None, file_list)
  1229. self.assertEqual(self.githash('repo_1', 5),
  1230. self.gitrevparse(self.root_dir))
  1231. # pylint: disable=attribute-defined-outside-init
  1232. self.options.download_topics = True
  1233. scm.url = 'https://test-repo.googlesource.com/repo_1.git'
  1234. scm.apply_patch_ref(self.url, 'refs/changes/34/1234/1',
  1235. 'refs/heads/main', self.options, file_list)
  1236. get_change_mock.assert_called_once_with(mock.ANY, '1234')
  1237. query_changes_mock.assert_called_once_with(mock.ANY,
  1238. [('topic', 'test_topic'),
  1239. ('status', 'open'),
  1240. ('repo', 'repo_1')],
  1241. o_params=['ALL_REVISIONS'])
  1242. self.assertCommits([1, 2, 3, 5, 6])
  1243. # The commit hash after the two cherry-picks is not known, but it must
  1244. # be different from what the repo was synced at before patching.
  1245. self.assertNotEqual(self.githash('repo_1', 4),
  1246. self.gitrevparse(self.root_dir))
  1247. def testRecoversAfterPatchFailure(self):
  1248. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1249. file_list = []
  1250. self.options.revision = 'refs/changes/34/1234/1'
  1251. scm.update(self.options, None, file_list)
  1252. self.assertEqual(self.githash('repo_1', 5),
  1253. self.gitrevparse(self.root_dir))
  1254. # Checkout 'refs/changes/34/1234/1' modifies the 'change' file, so
  1255. # trying to patch 'refs/changes/36/1236/1' creates a patch failure.
  1256. with self.assertRaises(subprocess2.CalledProcessError) as cm:
  1257. scm.apply_patch_ref(self.url, 'refs/changes/36/1236/1',
  1258. 'refs/heads/main', self.options, file_list)
  1259. self.assertEqual(cm.exception.cmd[:2], ['git', 'cherry-pick'])
  1260. self.assertIn(b'error: could not apply', cm.exception.stderr)
  1261. # Try to apply 'refs/changes/35/1235/1', which doesn't have a merge
  1262. # conflict.
  1263. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1264. 'refs/heads/main', self.options, file_list)
  1265. self.assertCommits([1, 2, 3, 5, 6])
  1266. self.assertEqual(self.githash('repo_1', 5),
  1267. self.gitrevparse(self.root_dir))
  1268. def testIgnoresAlreadyMergedCommits(self):
  1269. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1270. file_list = []
  1271. self.options.revision = 'refs/heads/main-with-5'
  1272. scm.update(self.options, None, file_list)
  1273. self.assertEqual(self.githash('repo_1', 12),
  1274. self.gitrevparse(self.root_dir))
  1275. # When we try 'refs/changes/35/1235/1' on top of 'refs/heads/feature',
  1276. # 'refs/changes/34/1234/1' will be an empty commit, since the changes
  1277. # were already present in the tree as commit 11. Make sure we deal with
  1278. # this gracefully.
  1279. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1280. 'refs/heads/feature', self.options, file_list)
  1281. self.assertCommits([1, 2, 3, 5, 6, 12])
  1282. self.assertEqual(self.githash('repo_1', 12),
  1283. self.gitrevparse(self.root_dir))
  1284. def testRecoversFromExistingCherryPick(self):
  1285. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1286. file_list = []
  1287. self.options.revision = 'refs/changes/34/1234/1'
  1288. scm.update(self.options, None, file_list)
  1289. self.assertEqual(self.githash('repo_1', 5),
  1290. self.gitrevparse(self.root_dir))
  1291. # Checkout 'refs/changes/34/1234/1' modifies the 'change' file, so
  1292. # trying to cherry-pick 'refs/changes/36/1236/1' raises an error.
  1293. scm._Run(['fetch', 'origin', 'refs/changes/36/1236/1'], self.options)
  1294. with self.assertRaises(subprocess2.CalledProcessError) as cm:
  1295. scm._Run(['cherry-pick', 'FETCH_HEAD'], self.options)
  1296. self.assertEqual(cm.exception.cmd[:2], ['git', 'cherry-pick'])
  1297. # Try to apply 'refs/changes/35/1235/1', which doesn't have a merge
  1298. # conflict.
  1299. scm.apply_patch_ref(self.url, 'refs/changes/35/1235/1',
  1300. 'refs/heads/main', self.options, file_list)
  1301. self.assertCommits([1, 2, 3, 5, 6])
  1302. self.assertEqual(self.githash('repo_1', 5),
  1303. self.gitrevparse(self.root_dir))
  1304. class DepsChangesFakeRepo(fake_repos.FakeReposBase):
  1305. def populateGit(self):
  1306. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'B'})
  1307. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'C'})
  1308. self._commit_git('repo_1', {'DEPS': 'versionB'})
  1309. self._commit_git('repo_1', {'DEPS': 'versionA', 'doesnotmatter': 'C'})
  1310. self._create_ref('repo_1', 'refs/heads/main', 4)
  1311. class CheckDiffTest(fake_repos.FakeReposTestBase):
  1312. FAKE_REPOS_CLASS = DepsChangesFakeRepo
  1313. def setUp(self):
  1314. super(CheckDiffTest, self).setUp()
  1315. self.enabled = self.FAKE_REPOS.set_up_git()
  1316. self.options = BaseGitWrapperTestCase.OptionsObject()
  1317. self.url = self.git_base + 'repo_1'
  1318. self.mirror = None
  1319. mock.patch('sys.stdout', StringIO()).start()
  1320. self.addCleanup(mock.patch.stopall)
  1321. def setUpMirror(self):
  1322. self.mirror = tempfile.mkdtemp()
  1323. git_cache.Mirror.SetCachePath(self.mirror)
  1324. self.addCleanup(gclient_utils.rmtree, self.mirror)
  1325. self.addCleanup(git_cache.Mirror.SetCachePath, None)
  1326. def testCheckDiff(self):
  1327. """Correctly check for diffs."""
  1328. scm = gclient_scm.GitWrapper(self.url, self.root_dir, '.')
  1329. file_list = []
  1330. # Make sure we don't specify a revision.
  1331. self.options.revision = None
  1332. scm.update(self.options, None, file_list)
  1333. self.assertEqual(self.githash('repo_1', 4),
  1334. self.gitrevparse(self.root_dir))
  1335. self.assertFalse(
  1336. scm.check_diff(self.githash('repo_1', 1), files=['DEPS']))
  1337. self.assertTrue(scm.check_diff(self.githash('repo_1', 1)))
  1338. self.assertTrue(
  1339. scm.check_diff(self.githash('repo_1', 3), files=['DEPS']))
  1340. self.assertFalse(
  1341. scm.check_diff(self.githash('repo_1', 2),
  1342. files=['DEPS', 'doesnotmatter']))
  1343. self.assertFalse(scm.check_diff(self.githash('repo_1', 2)))
  1344. if 'unittest.util' in __import__('sys').modules:
  1345. # Show full diff in self.assertEqual.
  1346. __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999
  1347. if __name__ == '__main__':
  1348. level = logging.DEBUG if '-v' in sys.argv else logging.FATAL
  1349. logging.basicConfig(level=level,
  1350. format='%(asctime).19s %(levelname)s %(filename)s:'
  1351. '%(lineno)s %(message)s')
  1352. unittest.main()
  1353. # vim: ts=2:sw=2:tw=80:et: