Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(449)

Side by Side Diff: tests/presubmit_unittest.py

Issue 392006: Cleanup the unit tests by mocking more system functions. (Closed)
Patch Set: Created 11 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « tests/gclient_test.py ('k') | tests/revert_unittest.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 #!/usr/bin/python 1 #!/usr/bin/python
2 # Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. 2 # Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 """Unit tests for presubmit_support.py and presubmit_canned_checks.py.""" 6 """Unit tests for presubmit_support.py and presubmit_canned_checks.py."""
7 7
8 import exceptions
9 import os
10 import StringIO 8 import StringIO
11 import unittest
12 9
13 # Local imports 10 # Local imports
14 import presubmit_support as presubmit 11 import presubmit_support as presubmit
15 import presubmit_canned_checks 12 import presubmit_canned_checks
16 import super_mox 13 from super_mox import mox, SuperMoxTestBase
17 from super_mox import mox
18 14
19 15
20 class PresubmitTestsBase(super_mox.SuperMoxTestBase): 16 class PresubmitTestsBase(SuperMoxTestBase):
21 """Setups and tear downs the mocks but doesn't test anything as-is.""" 17 """Setups and tear downs the mocks but doesn't test anything as-is."""
22 presubmit_text = """ 18 presubmit_text = """
23 def CheckChangeOnUpload(input_api, output_api): 19 def CheckChangeOnUpload(input_api, output_api):
24 if not input_api.change.NOSUCHKEY: 20 if not input_api.change.NOSUCHKEY:
25 return [output_api.PresubmitError("!!")] 21 return [output_api.PresubmitError("!!")]
26 elif not input_api.change.REALLYNOSUCHKEY: 22 elif not input_api.change.REALLYNOSUCHKEY:
27 return [output_api.PresubmitPromptWarning("??")] 23 return [output_api.PresubmitPromptWarning("??")]
28 elif not input_api.change.REALLYABSOLUTELYNOSUCHKEY: 24 elif not input_api.change.REALLYABSOLUTELYNOSUCHKEY:
29 return [output_api.PresubmitPromptWarning("??"), 25 return [output_api.PresubmitPromptWarning("??"),
30 output_api.PresubmitError("XX!!XX")] 26 output_api.PresubmitError("XX!!XX")]
31 else: 27 else:
32 return () 28 return ()
33 """ 29 """
34 presubmit_tryslave = """ 30 presubmit_tryslave = """
35 def GetPreferredTrySlaves(): 31 def GetPreferredTrySlaves():
36 return %s 32 return %s
37 """ 33 """
38 34
39 def setUp(self): 35 def setUp(self):
40 super_mox.SuperMoxTestBase.setUp(self) 36 SuperMoxTestBase.setUp(self)
37 self.mox.StubOutWithMock(presubmit, 'random')
41 self.mox.StubOutWithMock(presubmit, 'warnings') 38 self.mox.StubOutWithMock(presubmit, 'warnings')
42 # Stub out 'os' but keep os.path.commonprefix/dirname/join/normpath/splitext
43 # and os.sep.
44 os_sep = presubmit.os.sep
45 os_path_commonprefix = presubmit.os.path.commonprefix
46 os_path_dirname = presubmit.os.path.dirname
47 os_path_join = presubmit.os.path.join
48 os_path_normpath = presubmit.os.path.normpath
49 os_path_splitext = presubmit.os.path.splitext
50 self.mox.StubOutWithMock(presubmit, 'os')
51 self.mox.StubOutWithMock(presubmit.os, 'path')
52 presubmit.os.sep = os_sep
53 presubmit.os.path.join = os_path_join
54 presubmit.os.path.dirname = os_path_dirname
55 presubmit.os.path.normpath = os_path_normpath
56 presubmit.os.path.splitext = os_path_splitext
57 self.mox.StubOutWithMock(presubmit, 'random')
58 self.mox.StubOutWithMock(presubmit, 'sys')
59 presubmit._ASKED_FOR_FEEDBACK = False 39 presubmit._ASKED_FOR_FEEDBACK = False
60 presubmit.os.path.commonprefix = os_path_commonprefix
61 self.fake_root_dir = self.RootDir() 40 self.fake_root_dir = self.RootDir()
62 # Special mocks. 41 # Special mocks.
63 def MockAbsPath(f): 42 def MockAbsPath(f):
64 return f 43 return f
65 def MockChdir(f): 44 def MockChdir(f):
66 return None 45 return None
46 # SuperMoxTestBase already mock these but simplify our life.
67 presubmit.os.path.abspath = MockAbsPath 47 presubmit.os.path.abspath = MockAbsPath
68 presubmit.os.getcwd = self.RootDir 48 presubmit.os.getcwd = self.RootDir
69 presubmit.os.chdir = MockChdir 49 presubmit.os.chdir = MockChdir
70 self.mox.StubOutWithMock(presubmit.gclient_scm, 'CaptureSVNInfo') 50 self.mox.StubOutWithMock(presubmit.gclient_scm, 'CaptureSVNInfo')
71 self.mox.StubOutWithMock(presubmit.gcl, 'GetSVNFileProperty') 51 self.mox.StubOutWithMock(presubmit.gcl, 'GetSVNFileProperty')
72 self.mox.StubOutWithMock(presubmit.gcl, 'ReadFile') 52 self.mox.StubOutWithMock(presubmit.gcl, 'ReadFile')
73 53
74 54
75 class PresubmitUnittest(PresubmitTestsBase): 55 class PresubmitUnittest(PresubmitTestsBase):
76 """General presubmit_support.py tests (excluding InputApi and OutputApi).""" 56 """General presubmit_support.py tests (excluding InputApi and OutputApi)."""
(...skipping 197 matching lines...) Expand 10 before | Expand all | Expand 10 after
274 254
275 self.failUnless(executer.ExecPresubmitScript( 255 self.failUnless(executer.ExecPresubmitScript(
276 ('def CheckChangeOnCommit(input_api, output_api):\n' 256 ('def CheckChangeOnCommit(input_api, output_api):\n'
277 ' if not input_api.change.NOSUCHKEY:\n' 257 ' if not input_api.change.NOSUCHKEY:\n'
278 ' return [output_api.PresubmitError("!!")]\n' 258 ' return [output_api.PresubmitError("!!")]\n'
279 ' else:\n' 259 ' else:\n'
280 ' return ()'), 260 ' return ()'),
281 fake_presubmit 261 fake_presubmit
282 )) 262 ))
283 263
284 self.assertRaises(exceptions.RuntimeError, 264 self.assertRaises(presubmit.exceptions.RuntimeError,
285 executer.ExecPresubmitScript, 265 executer.ExecPresubmitScript,
286 'def CheckChangeOnCommit(input_api, output_api):\n' 266 'def CheckChangeOnCommit(input_api, output_api):\n'
287 ' return "foo"', 267 ' return "foo"',
288 fake_presubmit) 268 fake_presubmit)
289 269
290 self.assertRaises(exceptions.RuntimeError, 270 self.assertRaises(presubmit.exceptions.RuntimeError,
291 executer.ExecPresubmitScript, 271 executer.ExecPresubmitScript,
292 'def CheckChangeOnCommit(input_api, output_api):\n' 272 'def CheckChangeOnCommit(input_api, output_api):\n'
293 ' return ["foo"]', 273 ' return ["foo"]',
294 fake_presubmit) 274 fake_presubmit)
295 275
296 def testDoPresubmitChecks(self): 276 def testDoPresubmitChecks(self):
297 join = presubmit.os.path.join 277 join = presubmit.os.path.join
298 description_lines = ('Hello there', 278 description_lines = ('Hello there',
299 'this is a change', 279 'this is a change',
300 'STORY=http://tracker/123') 280 'STORY=http://tracker/123')
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
417 text = ('Warning, no presubmit.py found.\n' 397 text = ('Warning, no presubmit.py found.\n'
418 'Running default presubmit script.\n' 398 'Running default presubmit script.\n'
419 '** Presubmit ERRORS **\n!!\n\n' 399 '** Presubmit ERRORS **\n!!\n\n'
420 'Was the presubmit check useful? Please send feedback & hate mail ' 400 'Was the presubmit check useful? Please send feedback & hate mail '
421 'to maruel@chromium.org!\n') 401 'to maruel@chromium.org!\n')
422 self.assertEquals(output.getvalue(), text) 402 self.assertEquals(output.getvalue(), text)
423 403
424 def testDirectoryHandling(self): 404 def testDirectoryHandling(self):
425 files = [ 405 files = [
426 ['A', 'isdir'], 406 ['A', 'isdir'],
427 ['A', os.path.join('isdir', 'blat.cc')], 407 ['A', presubmit.os.path.join('isdir', 'blat.cc')],
428 ] 408 ]
429 isdir = presubmit.os.path.join(self.fake_root_dir, 'isdir') 409 isdir = presubmit.os.path.join(self.fake_root_dir, 'isdir')
430 blat = presubmit.os.path.join(isdir, 'blat.cc') 410 blat = presubmit.os.path.join(isdir, 'blat.cc')
431 presubmit.os.path.exists(isdir).AndReturn(True) 411 presubmit.os.path.exists(isdir).AndReturn(True)
432 presubmit.os.path.isdir(isdir).AndReturn(True) 412 presubmit.os.path.isdir(isdir).AndReturn(True)
433 presubmit.os.path.exists(blat).AndReturn(True) 413 presubmit.os.path.exists(blat).AndReturn(True)
434 presubmit.os.path.isdir(blat).AndReturn(False) 414 presubmit.os.path.isdir(blat).AndReturn(False)
435 self.mox.ReplayAll() 415 self.mox.ReplayAll()
436 416
437 change = presubmit.Change('mychange', 'foo', self.fake_root_dir, files, 417 change = presubmit.Change('mychange', 'foo', self.fake_root_dir, files,
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
494 474
495 executer = presubmit.GetTrySlavesExecuter() 475 executer = presubmit.GetTrySlavesExecuter()
496 self.assertEqual([], executer.ExecPresubmitScript('')) 476 self.assertEqual([], executer.ExecPresubmitScript(''))
497 self.assertEqual([], executer.ExecPresubmitScript('def foo():\n return\n')) 477 self.assertEqual([], executer.ExecPresubmitScript('def foo():\n return\n'))
498 478
499 # bad results 479 # bad results
500 starts_with_space_result = [' starts_with_space'] 480 starts_with_space_result = [' starts_with_space']
501 not_list_result1 = "'foo'" 481 not_list_result1 = "'foo'"
502 not_list_result2 = "('a', 'tuple')" 482 not_list_result2 = "('a', 'tuple')"
503 for result in starts_with_space_result, not_list_result1, not_list_result2: 483 for result in starts_with_space_result, not_list_result1, not_list_result2:
504 self.assertRaises(exceptions.RuntimeError, 484 self.assertRaises(presubmit.exceptions.RuntimeError,
505 executer.ExecPresubmitScript, 485 executer.ExecPresubmitScript,
506 self.presubmit_tryslave % result) 486 self.presubmit_tryslave % result)
507 487
508 # good results 488 # good results
509 expected_result = ['1', '2', '3'] 489 expected_result = ['1', '2', '3']
510 empty_result = [] 490 empty_result = []
511 space_in_name_result = ['foo bar', '1\t2 3'] 491 space_in_name_result = ['foo bar', '1\t2 3']
512 for result in expected_result, empty_result, space_in_name_result: 492 for result in expected_result, empty_result, space_in_name_result:
513 self.assertEqual(result, 493 self.assertEqual(result,
514 executer.ExecPresubmitScript(self.presubmit_tryslave % 494 executer.ExecPresubmitScript(self.presubmit_tryslave %
(...skipping 22 matching lines...) Expand all
537 self.assertEqual(['win'], 517 self.assertEqual(['win'],
538 presubmit.DoGetTrySlaves([filename], self.fake_root_dir, 518 presubmit.DoGetTrySlaves([filename], self.fake_root_dir,
539 None, False, output)) 519 None, False, output))
540 output = StringIO.StringIO() 520 output = StringIO.StringIO()
541 self.assertEqual(['win', 'linux'], 521 self.assertEqual(['win', 'linux'],
542 presubmit.DoGetTrySlaves([filename, filename_linux], 522 presubmit.DoGetTrySlaves([filename, filename_linux],
543 self.fake_root_dir, None, False, 523 self.fake_root_dir, None, False,
544 output)) 524 output))
545 525
546 def testMain(self): 526 def testMain(self):
527 # OptParser calls presubmit.os.path.exists and is a pain when mocked.
528 self.UnMock(presubmit.os.path, 'exists')
547 self.mox.StubOutWithMock(presubmit, 'DoPresubmitChecks') 529 self.mox.StubOutWithMock(presubmit, 'DoPresubmitChecks')
548 self.mox.StubOutWithMock(presubmit, 'ParseFiles') 530 self.mox.StubOutWithMock(presubmit, 'ParseFiles')
549 presubmit.os.path.isdir(presubmit.os.path.join(self.fake_root_dir, '.git') 531 presubmit.os.path.isdir(presubmit.os.path.join(self.fake_root_dir, '.git')
550 ).AndReturn(False) 532 ).AndReturn(False)
551 presubmit.os.path.isdir(presubmit.os.path.join(self.fake_root_dir, '.svn') 533 presubmit.os.path.isdir(presubmit.os.path.join(self.fake_root_dir, '.svn')
552 ).AndReturn(False) 534 ).AndReturn(False)
553 #presubmit.ParseFiles([], None).AndReturn([]) 535 #presubmit.ParseFiles([], None).AndReturn([])
554 presubmit.DoPresubmitChecks(mox.IgnoreArg(), False, False, 536 presubmit.DoPresubmitChecks(mox.IgnoreArg(), False, False,
555 mox.IgnoreArg(), 537 mox.IgnoreArg(),
556 mox.IgnoreArg(), 538 mox.IgnoreArg(),
(...skipping 913 matching lines...) Expand 10 before | Expand all | Expand 10 after
1470 stdout=presubmit.subprocess.PIPE).AndReturn(process) 1452 stdout=presubmit.subprocess.PIPE).AndReturn(process)
1471 process.communicate().AndReturn(('', '')) 1453 process.communicate().AndReturn(('', ''))
1472 self.mox.ReplayAll() 1454 self.mox.ReplayAll()
1473 1455
1474 results = presubmit_canned_checks.RunPythonUnitTests( 1456 results = presubmit_canned_checks.RunPythonUnitTests(
1475 input_api, presubmit.OutputApi, ['test_module']) 1457 input_api, presubmit.OutputApi, ['test_module'])
1476 self.assertEquals(len(results), 0) 1458 self.assertEquals(len(results), 0)
1477 1459
1478 1460
1479 if __name__ == '__main__': 1461 if __name__ == '__main__':
1462 import unittest
1480 unittest.main() 1463 unittest.main()
OLDNEW
« no previous file with comments | « tests/gclient_test.py ('k') | tests/revert_unittest.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698