1# Copyright 2012 The Chromium Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4import os 5import tempfile 6import unittest 7 8from telemetry.internal.browser import browser_credentials 9 10 11SIMPLE_CREDENTIALS_STRING = """ 12{ 13 "google": { 14 "username": "example", 15 "password": "asdf" 16 } 17} 18""" 19 20class BackendStub(object): 21 def __init__(self, credentials_type): 22 self.login_needed_called = None 23 self.login_no_longer_needed_called = None 24 self.credentials_type = credentials_type 25 26 def LoginNeeded(self, config, _, tab): 27 self.login_needed_called = (config, tab) 28 return True 29 30 def LoginNoLongerNeeded(self, tab): 31 self.login_no_longer_needed_called = (tab, ) 32 33 34class TestBrowserCredentials(unittest.TestCase): 35 def testCredentialsInfrastructure(self): 36 google_backend = BackendStub("google") 37 othersite_backend = BackendStub("othersite") 38 browser_cred = browser_credentials.BrowserCredentials( 39 [google_backend, 40 othersite_backend]) 41 try: 42 with tempfile.NamedTemporaryFile(delete=False) as f: 43 f.write(SIMPLE_CREDENTIALS_STRING) 44 45 browser_cred.credentials_path = f.name 46 47 # Should true because it has a password and a backend. 48 self.assertTrue(browser_cred.CanLogin('google')) 49 50 # Should be false succeed because it has no password. 51 self.assertFalse(browser_cred.CanLogin('othersite')) 52 53 # Should fail because it has no backend. 54 self.assertRaises( 55 Exception, 56 lambda: browser_cred.CanLogin('foobar')) 57 58 tab = {} 59 ret = browser_cred.LoginNeeded(tab, 'google') 60 self.assertTrue(ret) 61 self.assertTrue(google_backend.login_needed_called is not None) 62 self.assertEqual(tab, google_backend.login_needed_called[0]) 63 self.assertEqual("example", 64 google_backend.login_needed_called[1]["username"]) 65 self.assertEqual("asdf", 66 google_backend.login_needed_called[1]["password"]) 67 68 browser_cred.LoginNoLongerNeeded(tab, 'google') 69 self.assertTrue(google_backend.login_no_longer_needed_called is not None) 70 self.assertEqual(tab, google_backend.login_no_longer_needed_called[0]) 71 finally: 72 os.remove(f.name) 73