Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # Copyright (c) 2012 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. |
| 6 | |
| 7 | """Unit tests for gsutil_util module.""" |
| 8 | |
| 9 | import mox |
| 10 | import subprocess |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 11 | import time |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 12 | import unittest |
| 13 | |
| 14 | import gsutil_util |
| 15 | |
| 16 | |
| 17 | class GSUtilUtilTest(mox.MoxTestBase): |
| 18 | |
| 19 | def setUp(self): |
| 20 | mox.MoxTestBase.setUp(self) |
| 21 | |
| 22 | self._good_mock_process = self.mox.CreateMock(subprocess.Popen) |
| 23 | self._good_mock_process.returncode = 0 |
| 24 | self._bad_mock_process = self.mox.CreateMock(subprocess.Popen) |
| 25 | self._bad_mock_process.returncode = 1 |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 26 | self.mox.StubOutWithMock(time, 'sleep') |
| 27 | time.sleep(mox.IgnoreArg()).MultipleTimes() |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 28 | |
| 29 | def _CallRunGS(self, str_should_contain, attempts=1): |
| 30 | """Helper that wraps a RunGS for tests.""" |
| 31 | for attempt in range(attempts): |
| 32 | if attempt == gsutil_util.GSUTIL_ATTEMPTS: |
| 33 | # We can't mock more than we can attempt. |
| 34 | return |
| 35 | |
| 36 | # Return 1's for all but last attempt. |
| 37 | if attempt != attempts - 1: |
| 38 | mock_process = self._bad_mock_process |
| 39 | else: |
| 40 | mock_process = self._good_mock_process |
| 41 | |
| 42 | subprocess.Popen(mox.StrContains(str_should_contain), shell=True, |
| 43 | stdout=subprocess.PIPE).AndReturn(mock_process) |
| 44 | mock_process.communicate().AndReturn(('Does not matter', None)) |
| 45 | |
| 46 | def testDownloadFromGS(self): |
| 47 | """Tests that we can run download build from gs with one error.""" |
| 48 | self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True) |
| 49 | |
| 50 | # Make sure we our retry works. |
| 51 | self._CallRunGS('from to', attempts=2) |
| 52 | self.mox.ReplayAll() |
| 53 | gsutil_util.DownloadFromGS('from', 'to') |
| 54 | self.mox.VerifyAll() |
| 55 | |
| 56 | def testDownloadFromGSButGSDown(self): |
| 57 | """Tests that we fail correctly if we can't reach GS.""" |
| 58 | self.mox.StubOutWithMock(subprocess, 'Popen', use_mock_anything=True) |
| 59 | self._CallRunGS('from to', attempts=gsutil_util.GSUTIL_ATTEMPTS + 1) |
| 60 | |
| 61 | self.mox.ReplayAll() |
| 62 | self.assertRaises( |
| 63 | gsutil_util.GSUtilError, |
| 64 | gsutil_util.DownloadFromGS, |
| 65 | 'from', 'to') |
| 66 | self.mox.VerifyAll() |
| 67 | |
| 68 | |
| 69 | if __name__ == '__main__': |
| 70 | unittest.main() |