gclient_scm_test.py 63 KB

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