Upstream version 8.36.161.0
[platform/framework/web/crosswalk.git] / src / third_party / chromite / scripts / check_gdata_token_unittest.py
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 cros_portage_upgrade.py."""
8
9 import filecmp
10 import mox
11 import os
12 import shutil
13
14 import gdata.service
15 from gdata.projecthosting import client as gdata_ph_client
16 from gdata.spreadsheet import service as gdata_ss_service
17
18 from chromite.lib import cros_build_lib as build_lib
19 from chromite.lib import cros_test_lib
20 from chromite.lib import gdata_lib
21 from chromite.scripts import check_gdata_token as cgt
22
23 # pylint: disable=W0212,R0904,E1120,E1101
24
25
26 class MainTest(cros_test_lib.MoxOutputTestCase):
27   """Test argument handling at the main method level."""
28
29   def testHelp(self):
30     """Test that --help is functioning"""
31     argv = [ '--help' ]
32
33     with self.OutputCapturer() as output:
34       # Running with --help should exit with code==0.
35       self.AssertFuncSystemExitZero(cgt.main, argv)
36
37     # Verify that a message beginning with "Usage: " was printed.
38     stdout = output.GetStdout()
39     self.assertTrue(stdout.startswith('Usage: '))
40
41   def testMainOutsideChroot(self):
42     """Test flow outside chroot"""
43     argv = []
44     mocked_outsidechroot = self.mox.CreateMock(cgt.OutsideChroot)
45
46     # Create replay script.
47     self.mox.StubOutWithMock(build_lib, 'IsInsideChroot')
48     self.mox.StubOutWithMock(cgt.OutsideChroot, '__new__')
49
50     build_lib.IsInsideChroot().AndReturn(False)
51     cgt.OutsideChroot.__new__(cgt.OutsideChroot, argv,
52                               ).AndReturn(mocked_outsidechroot)
53     mocked_outsidechroot.Run()
54     self.mox.ReplayAll()
55
56     # Run test verification.
57     with self.OutputCapturer():
58       cgt.main(argv)
59     self.mox.VerifyAll()
60
61   def testMainInsideChroot(self):
62     """Test flow inside chroot"""
63     argv = []
64     mocked_insidechroot = self.mox.CreateMock(cgt.InsideChroot)
65
66     # Create replay script.
67     self.mox.StubOutWithMock(build_lib, 'IsInsideChroot')
68     self.mox.StubOutWithMock(cgt.InsideChroot, '__new__')
69
70     build_lib.IsInsideChroot().AndReturn(True)
71     cgt.InsideChroot.__new__(cgt.InsideChroot
72                              ).AndReturn(mocked_insidechroot)
73     mocked_insidechroot.Run()
74     self.mox.ReplayAll()
75
76     # Run test verification.
77     with self.OutputCapturer():
78       cgt.main(argv)
79     self.mox.VerifyAll()
80
81
82 class OutsideChrootTest(cros_test_lib.MoxOutputTestCase):
83   """Test flow when run outside chroot."""
84
85   def _MockOutsideChroot(self, *args):
86     """Prepare mocked OutsideChroot object with |args|."""
87     mocked_outsidechroot = self.mox.CreateMock(cgt.OutsideChroot)
88
89     mocked_outsidechroot.args = list(args) if args else []
90
91     return mocked_outsidechroot
92
93   def testOutsideChrootRestartFail(self):
94     mocked_outsidechroot = self._MockOutsideChroot()
95
96     self.mox.StubOutWithMock(build_lib, 'RunCommand')
97     cmd = ['check_gdata_token']
98     run_result = cros_test_lib.EasyAttr(returncode=1)
99
100     # Create replay script.
101     build_lib.RunCommand(cmd, enter_chroot=True,
102                          print_cmd=False,
103                          error_code_ok=True).AndReturn(run_result)
104     self.mox.ReplayAll()
105
106     # Run test verification.
107     with self.OutputCapturer():
108       # Test should exit with failure.
109       self.AssertFuncSystemExitNonZero(cgt.OutsideChroot.Run,
110                                        mocked_outsidechroot)
111
112     self.mox.VerifyAll()
113
114     self.AssertOutputContainsError()
115
116   def testOutsideChrootNoTokenFile(self):
117     mocked_outsidechroot = self._MockOutsideChroot('foo')
118
119     self.mox.StubOutWithMock(cgt, '_ChrootPathToExternalPath')
120     self.mox.StubOutWithMock(os.path, 'exists')
121     self.mox.StubOutWithMock(build_lib, 'RunCommand')
122     cmd = ['check_gdata_token', 'foo']
123     run_result = cros_test_lib.EasyAttr(returncode=0)
124
125     # Create replay script.
126     build_lib.RunCommand(cmd, enter_chroot=True,
127                          print_cmd=False,
128                          error_code_ok=True).AndReturn(run_result)
129     cgt._ChrootPathToExternalPath(cgt.TOKEN_FILE).AndReturn('chr-tok')
130     os.path.exists('chr-tok').AndReturn(False)
131     self.mox.ReplayAll()
132
133     # Run test verification.
134     with self.OutputCapturer():
135       # Test should exit with failure.
136       self.AssertFuncSystemExitNonZero(cgt.OutsideChroot.Run,
137                                        mocked_outsidechroot)
138
139     self.mox.VerifyAll()
140
141     self.AssertOutputContainsError()
142
143   def testOutsideChrootNewTokenFile(self):
144     mocked_outsidechroot = self._MockOutsideChroot('foo')
145
146     self.mox.StubOutWithMock(cgt, '_ChrootPathToExternalPath')
147     self.mox.StubOutWithMock(os.path, 'exists')
148     self.mox.StubOutWithMock(shutil, 'copy2')
149     self.mox.StubOutWithMock(build_lib, 'RunCommand')
150     cmd = ['check_gdata_token', 'foo']
151     run_result = cros_test_lib.EasyAttr(returncode=0)
152
153     # Create replay script.
154     build_lib.RunCommand(cmd, enter_chroot=True,
155                          print_cmd=False,
156                          error_code_ok=True).AndReturn(run_result)
157     cgt._ChrootPathToExternalPath(cgt.TOKEN_FILE).AndReturn('chr-tok')
158     os.path.exists('chr-tok').AndReturn(True)
159     os.path.exists(cgt.TOKEN_FILE).AndReturn(False)
160     shutil.copy2('chr-tok', cgt.TOKEN_FILE)
161     self.mox.ReplayAll()
162
163     # Run test verification.
164     with self.OutputCapturer():
165       cgt.OutsideChroot.Run(mocked_outsidechroot)
166     self.mox.VerifyAll()
167
168   def testOutsideChrootDifferentTokenFile(self):
169     mocked_outsidechroot = self._MockOutsideChroot('foo')
170
171     self.mox.StubOutWithMock(cgt, '_ChrootPathToExternalPath')
172     self.mox.StubOutWithMock(os.path, 'exists')
173     self.mox.StubOutWithMock(shutil, 'copy2')
174     self.mox.StubOutWithMock(filecmp, 'cmp')
175     self.mox.StubOutWithMock(build_lib, 'RunCommand')
176     cmd = ['check_gdata_token', 'foo']
177     run_result = cros_test_lib.EasyAttr(returncode=0)
178
179     # Create replay script.
180     build_lib.RunCommand(cmd, enter_chroot=True,
181                          print_cmd=False,
182                          error_code_ok=True).AndReturn(run_result)
183     cgt._ChrootPathToExternalPath(cgt.TOKEN_FILE).AndReturn('chr-tok')
184     os.path.exists('chr-tok').AndReturn(True)
185     os.path.exists(cgt.TOKEN_FILE).AndReturn(True)
186     filecmp.cmp(cgt.TOKEN_FILE, 'chr-tok').AndReturn(False)
187     shutil.copy2('chr-tok', cgt.TOKEN_FILE)
188     self.mox.ReplayAll()
189
190     # Run test verification.
191     with self.OutputCapturer():
192       cgt.OutsideChroot.Run(mocked_outsidechroot)
193     self.mox.VerifyAll()
194
195   def testOutsideChrootNoChangeInTokenFile(self):
196     mocked_outsidechroot = self._MockOutsideChroot('foo')
197
198     self.mox.StubOutWithMock(cgt, '_ChrootPathToExternalPath')
199     self.mox.StubOutWithMock(os.path, 'exists')
200     self.mox.StubOutWithMock(filecmp, 'cmp')
201     self.mox.StubOutWithMock(build_lib, 'RunCommand')
202     cmd = ['check_gdata_token', 'foo']
203     run_result = cros_test_lib.EasyAttr(returncode=0)
204
205     # Create replay script.
206     build_lib.RunCommand(cmd, enter_chroot=True,
207                          print_cmd=False,
208                          error_code_ok=True).AndReturn(run_result)
209     cgt._ChrootPathToExternalPath(cgt.TOKEN_FILE).AndReturn('chr-tok')
210     os.path.exists('chr-tok').AndReturn(True)
211     os.path.exists(cgt.TOKEN_FILE).AndReturn(True)
212     filecmp.cmp(cgt.TOKEN_FILE, 'chr-tok').AndReturn(True)
213     self.mox.ReplayAll()
214
215     # Run test verification.
216     with self.OutputCapturer():
217       cgt.OutsideChroot.Run(mocked_outsidechroot)
218     self.mox.VerifyAll()
219
220 class InsideChrootTest(cros_test_lib.MoxOutputTestCase):
221   """Test flow when run inside chroot."""
222
223   def _MockInsideChroot(self):
224     """Prepare mocked OutsideChroot object."""
225     mic = self.mox.CreateMock(cgt.InsideChroot)
226
227     mic.creds = self.mox.CreateMock(gdata_lib.Creds)
228     mic.gd_client = self.mox.CreateMock(gdata_ss_service.SpreadsheetsService)
229     mic.it_client = self.mox.CreateMock(gdata_ph_client.ProjectHostingClient)
230
231     return mic
232
233   def testLoadTokenFile(self):
234     mocked_insidechroot = self._MockInsideChroot()
235
236     self.mox.StubOutWithMock(os.path, 'exists')
237
238     # Create replay script
239     os.path.exists(cgt.TOKEN_FILE).AndReturn(True)
240     mocked_insidechroot.creds.LoadAuthToken(cgt.TOKEN_FILE)
241     self.mox.ReplayAll()
242
243     # Run test verification.
244     with self.OutputCapturer():
245       result = cgt.InsideChroot._LoadTokenFile(mocked_insidechroot)
246     self.mox.VerifyAll()
247     self.assertTrue(result)
248
249   def testSaveTokenFile(self):
250     mocked_insidechroot = self._MockInsideChroot()
251
252     # Create replay script.
253     mocked_insidechroot.creds.StoreAuthTokenIfNeeded(cgt.TOKEN_FILE)
254     self.mox.ReplayAll()
255
256     # Run test verification.
257     with self.OutputCapturer():
258       cgt.InsideChroot._SaveTokenFile(mocked_insidechroot)
259     self.mox.VerifyAll()
260
261   def testLoadTokenFileMissing(self):
262     mocked_insidechroot = self._MockInsideChroot()
263
264     self.mox.StubOutWithMock(os.path, 'exists')
265
266     # Create replay script
267     os.path.exists(cgt.TOKEN_FILE).AndReturn(False)
268     self.mox.ReplayAll()
269
270     # Run test verification.
271     with self.OutputCapturer():
272       result = cgt.InsideChroot._LoadTokenFile(mocked_insidechroot)
273     self.mox.VerifyAll()
274     self.assertFalse(result)
275
276   def testInsideChrootValidateOK(self):
277     mocked_insidechroot = self._MockInsideChroot()
278
279     # Create replay script.
280     mocked_insidechroot._LoadTokenFile()
281     mocked_insidechroot._ValidateTrackerToken().AndReturn(True)
282     mocked_insidechroot._ValidateDocsToken().AndReturn(True)
283     mocked_insidechroot._SaveTokenFile()
284     self.mox.ReplayAll()
285
286     # Run test verification.
287     with self.OutputCapturer():
288       cgt.InsideChroot.Run(mocked_insidechroot)
289     self.mox.VerifyAll()
290
291   def testInsideChrootTrackerValidateFailGenerateOK(self):
292     mocked_insidechroot = self._MockInsideChroot()
293
294     # Create replay script.
295     mocked_insidechroot._LoadTokenFile()
296     mocked_insidechroot._ValidateTrackerToken().AndReturn(True)
297     mocked_insidechroot._ValidateDocsToken().AndReturn(False)
298     mocked_insidechroot._GenerateDocsToken().AndReturn(True)
299     mocked_insidechroot._SaveTokenFile()
300     self.mox.ReplayAll()
301
302     # Run test verification.
303     with self.OutputCapturer():
304       cgt.InsideChroot.Run(mocked_insidechroot)
305     self.mox.VerifyAll()
306
307   def testInsideChrootDocsValidateFailGenerateOK(self):
308     mocked_insidechroot = self._MockInsideChroot()
309
310     # Create replay script.
311     mocked_insidechroot._LoadTokenFile()
312     mocked_insidechroot._ValidateTrackerToken().AndReturn(False)
313     mocked_insidechroot._GenerateTrackerToken().AndReturn(True)
314     mocked_insidechroot._ValidateDocsToken().AndReturn(True)
315     mocked_insidechroot._SaveTokenFile()
316     self.mox.ReplayAll()
317
318     # Run test verification.
319     with self.OutputCapturer():
320       cgt.InsideChroot.Run(mocked_insidechroot)
321     self.mox.VerifyAll()
322
323   def testInsideChrootTrackerValidateFailGenerateFail(self):
324     mocked_insidechroot = self._MockInsideChroot()
325
326     # Create replay script.
327     mocked_insidechroot._LoadTokenFile()
328     mocked_insidechroot._ValidateTrackerToken().AndReturn(False)
329     mocked_insidechroot._GenerateTrackerToken().AndReturn(False)
330     self.mox.ReplayAll()
331
332     # Run test verification.
333     with self.OutputCapturer():
334       # Test should exit with failure.
335       self.AssertFuncSystemExitNonZero(cgt.InsideChroot.Run,
336                                        mocked_insidechroot)
337     self.mox.VerifyAll()
338
339     self.AssertOutputContainsError()
340
341   def testInsideChrootDocsValidateFailGenerateFail(self):
342     mocked_insidechroot = self._MockInsideChroot()
343
344     # Create replay script.
345     mocked_insidechroot._LoadTokenFile()
346     mocked_insidechroot._ValidateTrackerToken().AndReturn(True)
347     mocked_insidechroot._ValidateDocsToken().AndReturn(False)
348     mocked_insidechroot._GenerateDocsToken().AndReturn(False)
349     self.mox.ReplayAll()
350
351     # Run test verification.
352     with self.OutputCapturer():
353       # Test should exit with failure.
354       self.AssertFuncSystemExitNonZero(cgt.InsideChroot.Run,
355                                        mocked_insidechroot)
356     self.mox.VerifyAll()
357
358     self.AssertOutputContainsError()
359
360   def testGenerateTrackerTokenOK(self):
361     mocked_insidechroot = self._MockInsideChroot()
362
363     # Create replay script.
364     mocked_creds = mocked_insidechroot.creds
365     mocked_itclient = mocked_insidechroot.it_client
366     mocked_creds.user = 'joe@chromium.org'
367     mocked_creds.password = 'shhh'
368     auth_token = 'SomeToken'
369     mocked_itclient.auth_token = cros_test_lib.EasyAttr(token_string=auth_token)
370
371     mocked_creds.LoadCreds(cgt.CRED_FILE)
372     mocked_itclient.ClientLogin(mocked_creds.user, mocked_creds.password,
373                                 source='Package Status', service='code',
374                                 account_type='GOOGLE')
375     mocked_creds.SetTrackerAuthToken(auth_token)
376     self.mox.ReplayAll()
377
378     # Run test verification.
379     with self.OutputCapturer():
380       result = cgt.InsideChroot._GenerateTrackerToken(mocked_insidechroot)
381       self.assertTrue(result, '_GenerateTrackerToken should have passed')
382     self.mox.VerifyAll()
383
384   def testGenerateTrackerTokenFail(self):
385     mocked_insidechroot = self._MockInsideChroot()
386
387     # Create replay script.
388     mocked_creds = mocked_insidechroot.creds
389     mocked_itclient = mocked_insidechroot.it_client
390     mocked_creds.user = 'joe@chromium.org'
391     mocked_creds.password = 'shhh'
392
393     mocked_creds.LoadCreds(cgt.CRED_FILE)
394     mocked_itclient.ClientLogin(mocked_creds.user, mocked_creds.password,
395                                 source='Package Status', service='code',
396                                 account_type='GOOGLE'
397                                 ).AndRaise(gdata.client.BadAuthentication())
398     self.mox.ReplayAll()
399
400     # Run test verification.
401     with self.OutputCapturer():
402       result = cgt.InsideChroot._GenerateTrackerToken(mocked_insidechroot)
403       self.assertFalse(result, '_GenerateTrackerToken should have failed')
404     self.mox.VerifyAll()
405
406     self.AssertOutputContainsError()
407
408   def testValidateTrackerTokenOK(self):
409     mocked_insidechroot = self._MockInsideChroot()
410     mocked_itclient = mocked_insidechroot.it_client
411
412     self.mox.StubOutWithMock(gdata.gauth.ClientLoginToken, '__new__')
413
414     # Create replay script.
415     auth_token = 'SomeToken'
416     mocked_insidechroot.creds.tracker_auth_token = auth_token
417
418     gdata.gauth.ClientLoginToken.__new__(gdata.gauth.ClientLoginToken,
419                                          auth_token).AndReturn('TokenObj')
420     mocked_itclient.get_issues('chromium-os', query=mox.IgnoreArg())
421     self.mox.ReplayAll()
422
423     # Run test verification.
424     with self.OutputCapturer():
425       result = cgt.InsideChroot._ValidateTrackerToken(mocked_insidechroot)
426     self.mox.VerifyAll()
427     self.assertTrue(result, '_ValidateTrackerToken should have passed')
428
429   def testValidateTrackerTokenFail(self):
430     mocked_insidechroot = self._MockInsideChroot()
431     mocked_itclient = mocked_insidechroot.it_client
432
433     self.mox.StubOutWithMock(gdata.gauth.ClientLoginToken, '__new__')
434
435     # Create replay script.
436     auth_token = 'SomeToken'
437     mocked_insidechroot.creds.tracker_auth_token = auth_token
438
439     gdata.gauth.ClientLoginToken.__new__(gdata.gauth.ClientLoginToken,
440                                          auth_token).AndReturn('TokenObj')
441     mocked_itclient.get_issues('chromium-os', query=mox.IgnoreArg()
442                                ).AndRaise(gdata.client.Error())
443     self.mox.ReplayAll()
444
445     # Run test verification.
446     with self.OutputCapturer():
447       result = cgt.InsideChroot._ValidateTrackerToken(mocked_insidechroot)
448       self.assertFalse(result, '_ValidateTrackerToken should have failed')
449     self.mox.VerifyAll()
450
451   def testGenerateDocsTokenOK(self):
452     mocked_insidechroot = self._MockInsideChroot()
453
454     # Create replay script.
455     mocked_creds = mocked_insidechroot.creds
456     mocked_gdclient = mocked_insidechroot.gd_client
457     mocked_creds.user = 'joe@chromium.org'
458     mocked_creds.password = 'shhh'
459     auth_token = 'SomeToken'
460
461     mocked_creds.LoadCreds(cgt.CRED_FILE)
462     mocked_gdclient.ProgrammaticLogin()
463     mocked_gdclient.GetClientLoginToken().AndReturn(auth_token)
464     mocked_creds.SetDocsAuthToken(auth_token)
465     self.mox.ReplayAll()
466
467     # Run test verification.
468     with self.OutputCapturer():
469       result = cgt.InsideChroot._GenerateDocsToken(mocked_insidechroot)
470       self.assertTrue(result, '_GenerateDocsToken should have passed')
471     self.mox.VerifyAll()
472
473   def testGenerateDocsTokenFail(self):
474     mocked_insidechroot = self._MockInsideChroot()
475
476     # Create replay script.
477     mocked_creds = mocked_insidechroot.creds
478     mocked_gdclient = mocked_insidechroot.gd_client
479     mocked_creds.user = 'joe@chromium.org'
480     mocked_creds.password = 'shhh'
481
482     mocked_creds.LoadCreds(cgt.CRED_FILE)
483     mocked_gdclient.ProgrammaticLogin(
484       ).AndRaise(gdata.service.BadAuthentication())
485     self.mox.ReplayAll()
486
487     # Run test verification.
488     with self.OutputCapturer():
489       result = cgt.InsideChroot._GenerateDocsToken(mocked_insidechroot)
490       self.assertFalse(result, '_GenerateTrackerToken should have failed')
491     self.mox.VerifyAll()
492
493     self.AssertOutputContainsError()
494
495   def testValidateDocsTokenOK(self):
496     mocked_insidechroot = self._MockInsideChroot()
497
498     # Create replay script.
499     auth_token = 'SomeToken'
500     mocked_insidechroot.creds.docs_auth_token = auth_token
501
502     mocked_insidechroot.gd_client.SetClientLoginToken(auth_token)
503     mocked_insidechroot.gd_client.GetSpreadsheetsFeed()
504     self.mox.ReplayAll()
505
506     # Run test verification.
507     with self.OutputCapturer():
508       result = cgt.InsideChroot._ValidateDocsToken(mocked_insidechroot)
509       self.assertTrue(result, '_ValidateDocsToken should have passed')
510     self.mox.VerifyAll()
511
512   def testValidateDocsTokenFail(self):
513     mocked_insidechroot = self._MockInsideChroot()
514
515     # Create replay script.
516     auth_token = 'SomeToken'
517     mocked_insidechroot.creds.docs_auth_token = auth_token
518
519     mocked_insidechroot.gd_client.SetClientLoginToken(auth_token)
520     expired_error = gdata.service.RequestError({'reason': 'Token expired'})
521     mocked_insidechroot.gd_client.GetSpreadsheetsFeed().AndRaise(expired_error)
522     self.mox.ReplayAll()
523
524     # Run test verification.
525     with self.OutputCapturer():
526       result = cgt.InsideChroot._ValidateDocsToken(mocked_insidechroot)
527       self.assertFalse(result, '_ValidateDocsToken should have failed')
528     self.mox.VerifyAll()
529
530 if __name__ == '__main__':
531   cros_test_lib.main()