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

Side by Side Diff: chromite/lib/cros_build_lib_unittest.py

Issue 3307022: Issue 6600: RunCommand should return an object with various attributes (Closed) Base URL: http://git.chromium.org/git/crosutils.git
Patch Set: add copyright notice Created 10 years, 3 months 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 | Annotate | Revision Log
« no previous file with comments | « chromite/lib/cros_build_lib.py ('k') | no next file » | 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 #
3 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
2 6
3 import errno 7 import errno
4 import os 8 import os
5 import unittest
6 import shutil 9 import shutil
7 import tempfile 10 import subprocess
11 import tempfile
12 import unittest
13 import cros_build_lib
14 import mox
8 15
9 import cros_build_lib 16
17 class TestRunCommand(unittest.TestCase):
18
19 def setUp(self):
20 self.mox = mox.Mox()
21 self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True)
22 self.proc_mock = self.mox.CreateMockAnything()
23 self.cmd = 'test cmd'
24 self.error = 'test error'
25 self.output = 'test output'
26
27 def tearDown(self):
28 self.mox.UnsetStubs()
29 self.mox.VerifyAll()
30
31 def _assertCrEqual(self, expected, actual):
32 """Helper method to compare two CommandResult objects.
33
34 This is needed since assertEqual does not know how to compare two
35 CommandResult objects.
36
37 Args:
38 expected: a CommandResult object, expected result.
39 actual: a CommandResult object, actual result.
40 """
41 self.assertEqual(expected.cmd, actual.cmd)
42 self.assertEqual(expected.error, actual.error)
43 self.assertEqual(expected.output, actual.output)
44 self.assertEqual(expected.returncode, actual.returncode)
45
46 def _testCmd(self, cmd, sp_kv=dict(), rc_kv=dict()):
47 """Factor out common setup logic for testing --cmd.
48
49 Args:
50 cmd: a string or an array of strings.
51 sp_kv: key-value pairs passed to subprocess.Popen().
52 rc_kv: key-value pairs passed to RunCommand().
53 """
54 expected_result = cros_build_lib.CommandResult()
55 expected_result.cmd = self.cmd
56 expected_result.error = self.error
57 expected_result.output = self.output
58 if 'exit_code' in rc_kv:
59 expected_result.returncode = self.proc_mock.returncode
60
61 arg_dict = dict()
62 for attr in 'cwd stdin stdout stderr shell'.split():
63 if attr in sp_kv:
64 arg_dict[attr] = sp_kv[attr]
65 else:
66 if attr == 'shell':
67 arg_dict[attr] = False
68 else:
69 arg_dict[attr] = None
70
71 subprocess.Popen(self.cmd, **arg_dict).AndReturn(self.proc_mock)
72 self.proc_mock.communicate(None).AndReturn((self.output, self.error))
73 self.mox.ReplayAll()
74 actual_result = cros_build_lib.RunCommand(cmd, **rc_kv)
75 self._assertCrEqual(expected_result, actual_result)
76
77 def testReturnCodeZeroWithArrayCmd(self):
78 """--enter_chroot=False and --cmd is an array of strings."""
79 self.proc_mock.returncode = 0
80 cmd_list = ['foo', 'bar', 'roger']
81 self.cmd = 'foo bar roger'
82 self._testCmd(cmd_list, rc_kv=dict(exit_code=True))
83
84 def testReturnCodeZeroWithArrayCmdEnterChroot(self):
85 """--enter_chroot=True and --cmd is an array of strings."""
86 self.proc_mock.returncode = 0
87 cmd_list = ['foo', 'bar', 'roger']
88 self.cmd = './enter_chroot.sh -- %s' % ' '.join(cmd_list)
89 self._testCmd(cmd_list, rc_kv=dict(enter_chroot=True))
90
91 def testReturnCodeNotZeroErrorOkNotRaisesError(self):
92 """Raise error when proc.communicate() returns non-zero."""
93 self.proc_mock.returncode = 1
94 self._testCmd(self.cmd, rc_kv=dict(error_ok=True))
95
96 def testSubprocessCommunicateExceptionRaisesError(self):
97 """Verify error raised by communicate() is caught."""
98 subprocess.Popen(self.cmd, cwd=None, stdin=None, stdout=None, stderr=None,
99 shell=False).AndReturn(self.proc_mock)
100 self.proc_mock.communicate(None).AndRaise(ValueError)
101 self.mox.ReplayAll()
102 self.assertRaises(ValueError, cros_build_lib.RunCommand, self.cmd)
103
104 def testSubprocessCommunicateExceptionNotRaisesError(self):
105 """Don't re-raise error from communicate() when --error_ok=True."""
106 expected_result = cros_build_lib.CommandResult()
107 cmd_str = './enter_chroot.sh -- %s' % self.cmd
108 expected_result.cmd = cmd_str
109
110 subprocess.Popen(cmd_str, cwd=None, stdin=None, stdout=None, stderr=None,
111 shell=False).AndReturn(self.proc_mock)
112 self.proc_mock.communicate(None).AndRaise(ValueError)
113 self.mox.ReplayAll()
114 actual_result = cros_build_lib.RunCommand(self.cmd, error_ok=True,
115 enter_chroot=True)
116 self._assertCrEqual(expected_result, actual_result)
117
10 118
11 class TestListFiles(unittest.TestCase): 119 class TestListFiles(unittest.TestCase):
12 120
13 def setUp(self): 121 def setUp(self):
14 self.root_dir = tempfile.mkdtemp(prefix='listfiles_unittest') 122 self.root_dir = tempfile.mkdtemp(prefix='listfiles_unittest')
15 123
16 def tearDown(self): 124 def tearDown(self):
17 shutil.rmtree(self.root_dir) 125 shutil.rmtree(self.root_dir)
18 126
19 def _createNestedDir(self, dir_structure): 127 def _createNestedDir(self, dir_structure):
20 for entry in dir_structure: 128 for entry in dir_structure:
21 full_path = os.path.join(os.path.join(self.root_dir, entry)) 129 full_path = os.path.join(os.path.join(self.root_dir, entry))
22 # ensure dirs are created 130 # ensure dirs are created
23 try: 131 try:
24 os.makedirs(os.path.dirname(full_path)) 132 os.makedirs(os.path.dirname(full_path))
25 if full_path.endswith('/'): 133 if full_path.endswith('/'):
26 # we only want to create directories 134 # we only want to create directories
27 return 135 return
28 except OSError, err: 136 except OSError, err:
29 if err.errno == errno.EEXIST: 137 if err.errno == errno.EEXIST:
30 # we don't care if the dir already exists 138 # we don't care if the dir already exists
31 pass 139 pass
32 else: 140 else:
33 raise 141 raise
34 # create dummy files 142 # create dummy files
35 tmp = open(full_path, 'w') 143 tmp = open(full_path, 'w')
36 tmp.close() 144 tmp.close()
37 145
38 def testTraverse(self): 146 def testTraverse(self):
39 """ 147 """Test that we are traversing the directory properly."""
40 Test that we are traversing the directory properly
41 """
42 dir_structure = ['one/two/test.txt', 'one/blah.py', 148 dir_structure = ['one/two/test.txt', 'one/blah.py',
43 'three/extra.conf'] 149 'three/extra.conf']
44 self._createNestedDir(dir_structure) 150 self._createNestedDir(dir_structure)
45 151
46 files = cros_build_lib.ListFiles(self.root_dir) 152 files = cros_build_lib.ListFiles(self.root_dir)
47 for file in files: 153 for file in files:
48 file = file.replace(self.root_dir, '').lstrip('/') 154 file = file.replace(self.root_dir, '').lstrip('/')
49 if file not in dir_structure: 155 if file not in dir_structure:
50 self.fail('%s was not found in %s' % (file, dir_structure)) 156 self.fail('%s was not found in %s' % (file, dir_structure))
51 157
52 def testEmptyFilePath(self): 158 def testEmptyFilePath(self):
53 """ 159 """Test that we return nothing when directories are empty."""
54 Test that we return nothing when directories are empty
55 """
56 dir_structure = ['one/', 'two/', 'one/a/'] 160 dir_structure = ['one/', 'two/', 'one/a/']
57 self._createNestedDir(dir_structure) 161 self._createNestedDir(dir_structure)
58 files = cros_build_lib.ListFiles(self.root_dir) 162 files = cros_build_lib.ListFiles(self.root_dir)
59 self.assertEqual(files, []) 163 self.assertEqual(files, [])
60 164
61 def testNoSuchDir(self): 165 def testNoSuchDir(self):
62 try: 166 try:
63 cros_build_lib.ListFiles('/me/no/existe') 167 cros_build_lib.ListFiles('/me/no/existe')
64 except OSError, err: 168 except OSError, err:
65 self.assertEqual(err.errno, errno.ENOENT) 169 self.assertEqual(err.errno, errno.ENOENT)
66 170
67 171
68 if __name__ == '__main__': 172 if __name__ == '__main__':
69 unittest.main() 173 unittest.main()
OLDNEW
« no previous file with comments | « chromite/lib/cros_build_lib.py ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698