1 # Copyright 2013 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.
6 from telemetry.core import util
9 def _WaitForLoginFormToLoad(backend, login_form_id, tab):
10 def IsFormLoadedOrAlreadyLoggedIn():
11 return (tab.EvaluateJavaScript(
12 'document.querySelector("#%s")!== null' % login_form_id) or
13 backend.IsAlreadyLoggedIn(tab))
15 # Wait until the form is submitted and the page completes loading.
16 util.WaitFor(IsFormLoadedOrAlreadyLoggedIn, 60)
18 def _SubmitFormAndWait(form_id, tab):
19 tab.ExecuteJavaScript(
20 'document.getElementById("%s").submit();' % form_id)
22 def FinishedLoading():
23 return not tab.EvaluateJavaScript(
24 'document.querySelector("#%s") !== null' % form_id)
26 # Wait until the form is submitted and the page completes loading.
27 util.WaitFor(FinishedLoading, 60)
29 class FormBasedCredentialsBackend(object):
31 self._logged_in = False
33 def IsAlreadyLoggedIn(self, tab):
34 raise NotImplementedError()
37 def credentials_type(self):
38 raise NotImplementedError()
42 raise NotImplementedError()
45 def login_form_id(self):
46 raise NotImplementedError()
49 def login_input_id(self):
50 raise NotImplementedError()
53 def password_input_id(self):
54 raise NotImplementedError()
57 return self._logged_in
59 def _ResetLoggedInState(self):
60 """Makes the backend think we're not logged in even though we are.
61 Should only be used in unit tests to simulate --dont-override-profile.
63 self._logged_in = False
65 def LoginNeeded(self, tab, config):
66 """Logs in to a test account.
69 RuntimeError: if could not get credential information.
74 if 'username' not in config or 'password' not in config:
75 message = ('Credentials for "%s" must include username and password.' %
76 self.credentials_type)
77 raise RuntimeError(message)
79 logging.debug('Logging into %s account...' % self.credentials_type)
87 logging.info('Loading %s...', url)
89 _WaitForLoginFormToLoad(self, self.login_form_id, tab)
91 if self.IsAlreadyLoggedIn(tab):
92 self._logged_in = True
95 tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
96 logging.info('Loaded page: %s', url)
98 email_id = 'document.querySelector("#%s").%s.value = "%s"; ' % (
99 self.login_form_id, self.login_input_id, config['username'])
100 password = 'document.querySelector("#%s").%s.value = "%s"; ' % (
101 self.login_form_id, self.password_input_id, config['password'])
102 tab.ExecuteJavaScript(email_id)
103 tab.ExecuteJavaScript(password)
105 _SubmitFormAndWait(self.login_form_id, tab)
107 self._logged_in = True
109 except util.TimeoutException:
110 logging.warning('Timed out while loading: %s', url)
113 def LoginNoLongerNeeded(self, tab): # pylint: disable=W0613
114 assert self._logged_in