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

Side by Side Diff: gslib/tests/test_command_runner.py

Issue 698893003: Update checked in version of gsutil to version 4.6 (Closed) Base URL: http://dart.googlecode.com/svn/third_party/gsutil/
Patch Set: Created 6 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 | Annotate | Revision Log
« no previous file with comments | « gslib/tests/test_cat.py ('k') | gslib/tests/test_compose.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 # -*- coding: utf-8 -*-
1 # Copyright 2011 Google Inc. All Rights Reserved. 2 # Copyright 2011 Google Inc. All Rights Reserved.
2 #coding=utf8
3 # 3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License. 5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at 6 # You may obtain a copy of the License at
7 # 7 #
8 # http://www.apache.org/licenses/LICENSE-2.0 8 # http://www.apache.org/licenses/LICENSE-2.0
9 # 9 #
10 # Unless required by applicable law or agreed to in writing, software 10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, 11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and 13 # See the License for the specific language governing permissions and
14 # limitations under the License. 14 # limitations under the License.
15 """Unit and integration tests for gsutil command_runner module."""
16
17 from __future__ import absolute_import
15 18
16 import logging 19 import logging
17 import os 20 import os
18 import time 21 import time
19 22
20 import boto
21
22 import gslib 23 import gslib
23 from boto.pyami.config import Config, BotoConfigLocations
24 from gslib import command_runner 24 from gslib import command_runner
25 from gslib.command_runner import HandleArgCoding 25 from gslib.command_runner import HandleArgCoding
26 from gslib.exception import CommandException 26 from gslib.exception import CommandException
27 import gslib.tests.testcase as testcase 27 import gslib.tests.testcase as testcase
28 import gslib.tests.util as util
29 from gslib.tests.util import SetBotoConfigFileForTest
30 from gslib.tests.util import SetBotoConfigForTest
31 from gslib.tests.util import unittest
28 from gslib.util import GSUTIL_PUB_TARBALL 32 from gslib.util import GSUTIL_PUB_TARBALL
29 from gslib.util import SECONDS_PER_DAY 33 from gslib.util import SECONDS_PER_DAY
30 34
31 35
32 class TestCommandRunnerUnitTests( 36 class TestCommandRunnerUnitTests(
33 testcase.unit_testcase.GsUtilUnitTestCase): 37 testcase.unit_testcase.GsUtilUnitTestCase):
34 """Unit tests for gsutil update check in command_runner module.""" 38 """Unit tests for gsutil update check in command_runner module."""
35 39
36 def setUp(self): 40 def setUp(self):
41 """Sets up the command runner mock objects."""
37 super(TestCommandRunnerUnitTests, self).setUp() 42 super(TestCommandRunnerUnitTests, self).setUp()
38 43
39 # Mock out the timestamp file so we can manipulate it. 44 # Mock out the timestamp file so we can manipulate it.
40 self.previous_update_file = ( 45 self.previous_update_file = (
41 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE) 46 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE)
42 self.timestamp_file = self.CreateTempFile() 47 self.timestamp_file = self.CreateTempFile()
43 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = ( 48 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = (
44 self.timestamp_file) 49 self.timestamp_file)
45 50
46 # Mock out the gsutil version checker. 51 # Mock out the gsutil version checker.
47 base_version = unicode(gslib.VERSION) 52 base_version = unicode(gslib.VERSION)
48 while not base_version.isnumeric(): 53 while not base_version.isnumeric():
49 if not base_version: 54 if not base_version:
50 raise CommandException( 55 raise CommandException(
51 'Version number (%s) is not numeric.' % gslib.VERSION) 56 'Version number (%s) is not numeric.' % gslib.VERSION)
52 base_version = base_version[:-1] 57 base_version = base_version[:-1]
53 command_runner.LookUpGsutilVersion = lambda u: float(base_version) + 1 58 command_runner.LookUpGsutilVersion = lambda u, v: float(base_version) + 1
54 59
55 # Mock out raw_input to trigger yes prompt. 60 # Mock out raw_input to trigger yes prompt.
56 command_runner.raw_input = lambda p: 'y' 61 command_runner.raw_input = lambda p: 'y'
57 62
58 # Mock out TTY check to pretend we're on a TTY even if we're not. 63 # Mock out TTY check to pretend we're on a TTY even if we're not.
59 self.running_interactively = True 64 self.running_interactively = True
60 command_runner.IsRunningInteractively = lambda: self.running_interactively 65 command_runner.IsRunningInteractively = lambda: self.running_interactively
61 66
62 # Mock out the modified time of the VERSION file. 67 # Mock out the modified time of the VERSION file.
63 self.version_mod_time = 0 68 self.version_mod_time = 0
64 self.previous_version_mod_time = command_runner.GetGsutilVersionModifiedTime 69 self.previous_version_mod_time = command_runner.GetGsutilVersionModifiedTime
65 command_runner.GetGsutilVersionModifiedTime = lambda: self.version_mod_time 70 command_runner.GetGsutilVersionModifiedTime = lambda: self.version_mod_time
66 71
67 # Create a fake pub tarball that will be used to check for gsutil version. 72 # Create a fake pub tarball that will be used to check for gsutil version.
68 self.pub_bucket_uri = self.CreateBucket('pub') 73 self.pub_bucket_uri = self.CreateBucket('pub')
69 self.gsutil_tarball_uri = self.CreateObject( 74 self.gsutil_tarball_uri = self.CreateObject(
70 bucket_uri=self.pub_bucket_uri, object_name='gsutil.tar.gz', 75 bucket_uri=self.pub_bucket_uri, object_name='gsutil.tar.gz',
71 contents='foo') 76 contents='foo')
72 77
73 # Stores list of boto configs to set back to what they were.
74 self.boto_configs = []
75
76 def tearDown(self): 78 def tearDown(self):
79 """Tears down the command runner mock objects."""
77 super(TestCommandRunnerUnitTests, self).tearDown() 80 super(TestCommandRunnerUnitTests, self).tearDown()
78 81
79 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = ( 82 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = (
80 self.previous_update_file) 83 self.previous_update_file)
81 command_runner.LookUpGsutilVersion = gslib.util.LookUpGsutilVersion 84 command_runner.LookUpGsutilVersion = gslib.util.LookUpGsutilVersion
82 command_runner.raw_input = raw_input 85 command_runner.raw_input = raw_input
83 86
84 command_runner.GetGsutilVersionModifiedTime = self.previous_version_mod_time 87 command_runner.GetGsutilVersionModifiedTime = self.previous_version_mod_time
85 88
86 command_runner.IsRunningInteractively = gslib.util.IsRunningInteractively 89 command_runner.IsRunningInteractively = gslib.util.IsRunningInteractively
87 90
88 self.gsutil_tarball_uri.delete_key() 91 self.gsutil_tarball_uri.delete_key()
89 self.pub_bucket_uri.delete_bucket() 92 self.pub_bucket_uri.delete_bucket()
90 93
91 for section, name, value in self.boto_configs: 94 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
92 if value is None:
93 boto.config.remove_option(section, name)
94 else:
95 boto.config.set(section, name, value)
96
97 def _SetBotoConfig(self, section, name, value):
98 prev_value = boto.config.get(section, name, None)
99 self.boto_configs.append((section, name, prev_value))
100 boto.config.set(section, name, value)
101
102 def test_not_interactive(self): 95 def test_not_interactive(self):
103 """Tests that update is not triggered if not running interactively.""" 96 """Tests that update is not triggered if not running interactively."""
104 self._SetBotoConfig('GSUtil', 'software_update_check_period', '1') 97 with SetBotoConfigForTest([
105 with open(self.timestamp_file, 'w') as f: 98 ('GSUtil', 'software_update_check_period', '1')]):
106 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY))) 99 with open(self.timestamp_file, 'w') as f:
107 self.running_interactively = False 100 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY)))
108 self.assertEqual( 101 self.running_interactively = False
109 False, 102 self.assertEqual(
110 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 103 False,
104 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
111 105
106 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
112 def test_no_tracker_file_version_recent(self): 107 def test_no_tracker_file_version_recent(self):
113 """Tests when no timestamp file exists and VERSION file is recent.""" 108 """Tests when no timestamp file exists and VERSION file is recent."""
114 if os.path.exists(self.timestamp_file): 109 if os.path.exists(self.timestamp_file):
115 os.remove(self.timestamp_file) 110 os.remove(self.timestamp_file)
116 self.assertFalse(os.path.exists(self.timestamp_file)) 111 self.assertFalse(os.path.exists(self.timestamp_file))
117 self.version_mod_time = time.time() 112 self.version_mod_time = time.time()
118 self.assertEqual( 113 self.assertEqual(
119 False, 114 False,
120 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 115 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
121 116
117 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
122 def test_no_tracker_file_version_old(self): 118 def test_no_tracker_file_version_old(self):
123 """Tests when no timestamp file exists and VERSION file is old.""" 119 """Tests when no timestamp file exists and VERSION file is old."""
124 if os.path.exists(self.timestamp_file): 120 if os.path.exists(self.timestamp_file):
125 os.remove(self.timestamp_file) 121 os.remove(self.timestamp_file)
126 self.assertFalse(os.path.exists(self.timestamp_file)) 122 self.assertFalse(os.path.exists(self.timestamp_file))
127 self.version_mod_time = 0 123 self.version_mod_time = 0
128 expect = not gslib.IS_PACKAGE_INSTALL 124 expect = not gslib.IS_PACKAGE_INSTALL
129 self.assertEqual( 125 self.assertEqual(
130 expect, 126 expect,
131 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 127 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
132 128
129 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
133 def test_invalid_commands(self): 130 def test_invalid_commands(self):
134 """Tests that update is not triggered for certain commands.""" 131 """Tests that update is not triggered for certain commands."""
135 self.assertEqual( 132 self.assertEqual(
136 False, 133 False,
137 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('update', 0)) 134 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('update', 0))
138 135
136 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
139 def test_invalid_file_contents(self): 137 def test_invalid_file_contents(self):
140 """Tests no update if timestamp file has invalid value.""" 138 """Tests no update if timestamp file has invalid value."""
141 with open(self.timestamp_file, 'w') as f: 139 with open(self.timestamp_file, 'w') as f:
142 f.write('NaN') 140 f.write('NaN')
143 self.assertEqual( 141 self.assertEqual(
144 False, 142 False,
145 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 143 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
146 144
145 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
147 def test_update_should_trigger(self): 146 def test_update_should_trigger(self):
148 """Tests update should be triggered if time is up.""" 147 """Tests update should be triggered if time is up."""
149 self._SetBotoConfig('GSUtil', 'software_update_check_period', '1') 148 with SetBotoConfigForTest([
150 with open(self.timestamp_file, 'w') as f: 149 ('GSUtil', 'software_update_check_period', '1')]):
151 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY))) 150 with open(self.timestamp_file, 'w') as f:
152 # Update will not trigger for package installs. 151 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY)))
153 expect = not gslib.IS_PACKAGE_INSTALL 152 # Update will not trigger for package installs.
154 self.assertEqual( 153 expect = not gslib.IS_PACKAGE_INSTALL
155 expect, 154 self.assertEqual(
156 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 155 expect,
156 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
157 157
158 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
158 def test_not_time_for_update_yet(self): 159 def test_not_time_for_update_yet(self):
159 """Tests update not triggered if not time yet.""" 160 """Tests update not triggered if not time yet."""
160 self._SetBotoConfig('GSUtil', 'software_update_check_period', '3') 161 with SetBotoConfigForTest([
161 with open(self.timestamp_file, 'w') as f: 162 ('GSUtil', 'software_update_check_period', '3')]):
162 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY))) 163 with open(self.timestamp_file, 'w') as f:
163 self.assertEqual( 164 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY)))
164 False, 165 self.assertEqual(
165 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 166 False,
167 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
166 168
167 def test_user_says_no_to_update(self): 169 def test_user_says_no_to_update(self):
168 """Tests no update triggered if user says no at the prompt.""" 170 """Tests no update triggered if user says no at the prompt."""
169 self._SetBotoConfig('GSUtil', 'software_update_check_period', '1') 171 with SetBotoConfigForTest([
170 with open(self.timestamp_file, 'w') as f: 172 ('GSUtil', 'software_update_check_period', '1')]):
171 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY))) 173 with open(self.timestamp_file, 'w') as f:
172 command_runner.raw_input = lambda p: 'n' 174 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY)))
173 self.assertEqual( 175 command_runner.raw_input = lambda p: 'n'
174 False, 176 self.assertEqual(
175 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 177 False,
178 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
176 179
180 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
177 def test_update_check_skipped_with_quiet_mode(self): 181 def test_update_check_skipped_with_quiet_mode(self):
178 """Tests that update isn't triggered when loglevel is in quiet mode.""" 182 """Tests that update isn't triggered when loglevel is in quiet mode."""
179 self._SetBotoConfig('GSUtil', 'software_update_check_period', '1') 183 with SetBotoConfigForTest([
180 with open(self.timestamp_file, 'w') as f: 184 ('GSUtil', 'software_update_check_period', '1')]):
181 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY))) 185 with open(self.timestamp_file, 'w') as f:
186 f.write(str(int(time.time() - 2 * SECONDS_PER_DAY)))
182 187
183 # With regular loglevel, should return True except for package installs. 188 # With regular loglevel, should return True except for package installs.
184 expect = not gslib.IS_PACKAGE_INSTALL 189 expect = not gslib.IS_PACKAGE_INSTALL
185 self.assertEqual( 190 self.assertEqual(
186 expect, 191 expect,
187 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 192 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
188 193
189 prev_loglevel = logging.getLogger().getEffectiveLevel() 194 prev_loglevel = logging.getLogger().getEffectiveLevel()
190 try: 195 try:
191 logging.getLogger().setLevel(logging.ERROR) 196 logging.getLogger().setLevel(logging.ERROR)
192 # With reduced loglevel, should return False. 197 # With reduced loglevel, should return False.
193 self.assertEqual( 198 self.assertEqual(
194 False, 199 False,
195 self.command_runner._MaybeCheckForAndOfferSoftwareUpdate('ls', 0)) 200 self.command_runner.MaybeCheckForAndOfferSoftwareUpdate('ls', 0))
196 finally: 201 finally:
197 logging.getLogger().setLevel(prev_loglevel) 202 logging.getLogger().setLevel(prev_loglevel)
198 203
204 # pylint: disable=invalid-encoded-data
199 def test_valid_arg_coding(self): 205 def test_valid_arg_coding(self):
200 """ 206 """Tests that gsutil encodes valid args correctly."""
201 Tests that gsutil encodes valid args correctly.
202 """
203 # Args other than -h and -p should be utf-8 decoded. 207 # Args other than -h and -p should be utf-8 decoded.
204 args = HandleArgCoding(['ls', '-l']) 208 args = HandleArgCoding(['ls', '-l'])
205 self.assertIs(type(args[0]), unicode) 209 self.assertIs(type(args[0]), unicode)
206 self.assertIs(type(args[1]), unicode) 210 self.assertIs(type(args[1]), unicode)
207 211
208 # -p and -h args other than x-goog-meta should not be decoded. 212 # -p and -h args other than x-goog-meta should not be decoded.
209 args = HandleArgCoding(['ls', '-p', 'abc:def', 'gs://bucket']) 213 args = HandleArgCoding(['ls', '-p', 'abc:def', 'gs://bucket'])
210 self.assertIs(type(args[0]), unicode) 214 self.assertIs(type(args[0]), unicode)
211 self.assertIs(type(args[1]), unicode) 215 self.assertIs(type(args[1]), unicode)
212 self.assertIsNot(type(args[2]), unicode) 216 self.assertIsNot(type(args[2]), unicode)
(...skipping 28 matching lines...) Expand all
241 self.assertTrue(False) 245 self.assertTrue(False)
242 except CommandException as e: 246 except CommandException as e:
243 self.assertIn('Invalid non-ASCII header', e.reason) 247 self.assertIn('Invalid non-ASCII header', e.reason)
244 248
245 249
246 class TestCommandRunnerIntegrationTests( 250 class TestCommandRunnerIntegrationTests(
247 testcase.GsUtilIntegrationTestCase): 251 testcase.GsUtilIntegrationTestCase):
248 """Integration tests for gsutil update check in command_runner module.""" 252 """Integration tests for gsutil update check in command_runner module."""
249 253
250 def setUp(self): 254 def setUp(self):
255 """Sets up the command runner mock objects."""
251 super(TestCommandRunnerIntegrationTests, self).setUp() 256 super(TestCommandRunnerIntegrationTests, self).setUp()
252 257
253 # Mock out the timestamp file so we can manipulate it. 258 # Mock out the timestamp file so we can manipulate it.
254 self.previous_update_file = ( 259 self.previous_update_file = (
255 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE) 260 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE)
256 self.timestamp_file = self.CreateTempFile(contents='0') 261 self.timestamp_file = self.CreateTempFile(contents='0')
257 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = ( 262 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = (
258 self.timestamp_file) 263 self.timestamp_file)
259 264
260 # Mock out raw_input to trigger yes prompt. 265 # Mock out raw_input to trigger yes prompt.
261 command_runner.raw_input = lambda p: 'y' 266 command_runner.raw_input = lambda p: 'y'
262 267
263 # Create a credential-less boto config file.
264 self.orig_config = boto.config
265 config_file = path=self.CreateTempFile(
266 contents='[GSUtil]\nsoftware_update_check_period=1')
267 boto.config = Config(path=config_file)
268 # Need to copy config into boto.connection.config because it gets loaded
269 # before tests run.
270 boto.connection.config = boto.config
271 self.command_runner = command_runner.CommandRunner(config_file)
272
273 def tearDown(self): 268 def tearDown(self):
269 """Tears down the command runner mock objects."""
274 super(TestCommandRunnerIntegrationTests, self).tearDown() 270 super(TestCommandRunnerIntegrationTests, self).tearDown()
275
276 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = ( 271 command_runner.LAST_CHECKED_FOR_GSUTIL_UPDATE_TIMESTAMP_FILE = (
277 self.previous_update_file) 272 self.previous_update_file)
278 command_runner.raw_input = raw_input 273 command_runner.raw_input = raw_input
279 boto.config = self.orig_config
280 boto.connection.config = boto.config
281 274
275 @unittest.skipUnless(not util.HAS_GS_HOST, 'gs_host is defined in config')
282 def test_lookup_version_without_credentials(self): 276 def test_lookup_version_without_credentials(self):
283 """ 277 """Tests that gsutil tarball version lookup works without credentials."""
284 Tests that gsutil tarball version lookup works without credentials. 278 with SetBotoConfigFileForTest(self.CreateTempFile(
285 """ 279 contents='[GSUtil]\nsoftware_update_check_period=1')):
286 self.command_runner = command_runner.CommandRunner(config_file_list=[]) 280 self.command_runner = command_runner.CommandRunner()
287 # Looking up software version shouldn't get auth failure exception. 281 # Looking up software version shouldn't get auth failure exception.
288 self.command_runner.RunNamedCommand('ls', [GSUTIL_PUB_TARBALL]) 282 self.command_runner.RunNamedCommand('ls', [GSUTIL_PUB_TARBALL])
OLDNEW
« no previous file with comments | « gslib/tests/test_cat.py ('k') | gslib/tests/test_compose.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698