def testIsServiceRunning(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) self.assertTrue(cri.IsServiceRunning('openssh-server'))
def testGetRemotePortAndIsHTTPServerRunningOnPort(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) # Create local server. sock = socket.socket() sock.bind(('', 0)) port = sock.getsockname()[1] sock.listen(0) # Get remote port and ensure that it was unused. remote_port = cri.GetRemotePort() self.assertFalse(cri.IsHTTPServerRunningOnPort(remote_port)) # Forward local server's port to remote device's remote_port. forwarder = cros_browser_backend.SSHForwarder( cri, 'R', util.PortPair(port, remote_port)) # At this point, remote device should be able to connect to local server. self.assertTrue(cri.IsHTTPServerRunningOnPort(remote_port)) # Next remote port shouldn't be the same as remote_port, since remote_port # is now in use. self.assertTrue(cri.GetRemotePort() != remote_port) # Close forwarder and local server ports. forwarder.Close() sock.close() # Device should no longer be able to connect to remote_port since it is no # longer in use. self.assertFalse(cri.IsHTTPServerRunningOnPort(remote_port))
def testGetFileContentsForSomethingThatDoesntExist(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) self.assertRaises( OSError, lambda: cri.GetFileContents('/tmp/209fuslfskjf/dfsfsf'))
def testGetFileContents(self): # pylint: disable=R0201 remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) hosts = cri.GetFileContents('/etc/hosts') assert hosts.startswith('# /etc/hosts')
def testExists(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) self.assertTrue(cri.FileExistsOnDevice('/proc/cpuinfo')) self.assertTrue(cri.FileExistsOnDevice('/etc/passwd')) self.assertFalse(cri.FileExistsOnDevice('/etc/sdlfsdjflskfjsflj'))
def testPushContents(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) cri.RunCmdOnDevice(['rm', '-rf', '/tmp/testPushContents']) cri.PushContents('hello world', '/tmp/testPushContents') contents = cri.GetFileContents('/tmp/testPushContents') self.assertEquals(contents, 'hello world')
def testGetRemotePortReservedPorts(self): remote = options_for_unittests.GetCopy().cros_remote cri = cros_interface.CrOSInterface( remote, options_for_unittests.GetCopy().cros_ssh_identity) # Should return 2 separate ports even though the first one isn't technically # being used yet. remote_port_1 = cri.GetRemotePort() remote_port_2 = cri.GetRemotePort() self.assertTrue(remote_port_1 != remote_port_2)
def testUserAgent(self): ps = page_set.PageSet() page = page_module.Page( 'file:///' + os.path.join('..', '..', 'unittest_data', 'blank.html'), ps, base_dir=os.path.dirname(__file__)) ps.pages.append(page) ps.user_agent_type = 'tablet' class TestUserAgent(page_test.PageTest): def RunTest(self, page, tab, results): # pylint: disable=W0613,R0201 actual_user_agent = tab.EvaluateJavaScript( 'window.navigator.userAgent') expected_user_agent = user_agent.UA_TYPE_MAPPING['tablet'] assert actual_user_agent.strip() == expected_user_agent # This is so we can check later that the test actually made it into this # function. Previously it was timing out before even getting here, which # should fail, but since it skipped all the asserts, it slipped by. self.hasRun = True # pylint: disable=W0201 test = TestUserAgent('RunTest') with page_runner.PageRunner(ps) as runner: options = options_for_unittests.GetCopy() possible_browser = browser_finder.FindBrowser(options) results = page_test.PageTestResults() runner.Run(options, possible_browser, test, results) self.assertTrue(hasattr(test, 'hasRun') and test.hasRun)
def runCredentialsTest( self, # pylint: disable=R0201 credentials_backend, results): ps = page_set.PageSet() page = page_module.Page('http://www.google.com', ps) page.credentials = "test" ps.pages.append(page) did_run = [False] with tempfile.NamedTemporaryFile() as f: f.write(SIMPLE_CREDENTIALS_STRING) f.flush() ps.credentials_path = f.name class TestThatInstallsCredentialsBackend(page_test.PageTest): def __init__(self, credentials_backend): super(TestThatInstallsCredentialsBackend, self).__init__('RunTest') self._credentials_backend = credentials_backend def SetUpBrowser(self, browser): browser.credentials.AddBackend(self._credentials_backend) def RunTest(self, page, tab, results): # pylint: disable=W0613,R0201 did_run[0] = True test = TestThatInstallsCredentialsBackend(credentials_backend) with page_runner.PageRunner(ps) as runner: options = options_for_unittests.GetCopy() possible_browser = browser_finder.FindBrowser(options) runner.Run(options, possible_browser, test, results) return did_run[0]
def testLoginStatus(self): extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') load_extension = extension_to_load.ExtensionToLoad( extension_path, True) options = options_for_unittests.GetCopy() options.extensions_to_load = [load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) with browser_to_create.Create() as b: extension = b.extensions[load_extension] self.assertTrue(extension) extension.ExecuteJavaScript(''' chrome.autotestPrivate.loginStatus(function(s) { window.__autotest_result = s; }); ''') login_status = extension.EvaluateJavaScript( 'window.__autotest_result') self.assertEquals(type(login_status), dict) self.assertEquals(not self._is_guest, login_status['isRegularUser']) self.assertEquals(self._is_guest, login_status['isGuest']) self.assertEquals(login_status['email'], self._email) self.assertFalse(login_status['isScreenLocked'])
def testOneTab(self): ps = page_set.PageSet() page = page_module.Page( 'file:///' + os.path.join('..', '..', 'unittest_data', 'blank.html'), ps, base_dir=os.path.dirname(__file__)) ps.pages.append(page) class TestOneTab(page_test.PageTest): def __init__(self, test_method_name, action_name_to_run='', needs_browser_restart_after_each_run=False): super(TestOneTab, self).__init__(test_method_name, action_name_to_run, needs_browser_restart_after_each_run) self._browser = None def SetUpBrowser(self, browser): self._browser = browser self._browser.tabs.New() def RunTest(self, page, tab, results): # pylint: disable=W0613,R0201 assert len(self._browser.tabs) == 1 test = TestOneTab('RunTest') with page_runner.PageRunner(ps) as runner: options = options_for_unittests.GetCopy() possible_browser = browser_finder.FindBrowser(options) results = page_test.PageTestResults() runner.Run(options, possible_browser, test, results)
def _RebuildCredentials(self): credentials = {} if self._credentials_path == None: pass elif os.path.exists(self._credentials_path): with open(self._credentials_path, 'r') as f: credentials = json.loads(f.read()) # TODO(nduca): use system keychain, if possible. homedir_credentials_path = os.path.expanduser( '~/.telemetry-credentials') homedir_credentials = {} if (not options_for_unittests.GetCopy() and os.path.exists(homedir_credentials_path)): logging.info( "Found ~/.telemetry-credentials. Its contents will be used " "when no other credentials can be found.") with open(homedir_credentials_path, 'r') as f: homedir_credentials = json.loads(f.read()) self._credentials = {} all_keys = set(credentials.keys()).union( homedir_credentials.keys()).union(self._extra_credentials.keys()) for k in all_keys: if k in credentials: self._credentials[k] = credentials[k] if k in homedir_credentials: logging.info( "Will use ~/.telemetry-credentials for %s logins." % k) self._credentials[k] = homedir_credentials[k] if k in self._extra_credentials: self._credentials[k] = self._extra_credentials[k]
def testTabCallByReference(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: tab = b.tabs[0] tab.Navigate('http://www.google.com/') b.tabs[0].WaitForDocumentReadyStateToBeInteractiveOrBetter()
def testVersionDetection(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: # pylint: disable=W0212 self.assertTrue(b._browser_backend._inspector_protocol_version > 0) self.assertTrue(b._browser_backend._chrome_branch_number > 0) self.assertTrue(b._browser_backend._webkit_base_revision > 0)
def testCloseReferencedTab(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: b.tabs.New() tab = b.tabs[0] tab.Navigate('http://www.google.com/') tab.Close() self.assertEquals(1, len(b.tabs))
def testBrowserCreation(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) if not browser_to_create: raise Exception('No browser found, cannot continue test.') with browser_to_create.Create() as b: self.assertEquals(1, len(b.tabs)) # Different browsers boot up to different things assert b.tabs[0].url
def testCryptohomeMounted(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) if not browser_to_create: raise Exception('No browser found, cannot continue test.') with browser_to_create.Create() as b: self.assertEquals(1, len(b.tabs)) self.assertTrue(b.tabs[0].url) self.assertTrue(self._IsCryptohomeMounted()) self.assertFalse(self._IsCryptohomeMounted())
def testExtensionNotLoaded(self): """Querying an extension that was not loaded will return None""" extension_path = os.path.join(os.path.dirname(__file__), '..', '..', 'unittest_data', 'simple_extension') load_extension = extension_to_load.ExtensionToLoad(extension_path) options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: if b.supports_extensions: self.assertRaises( extension_dict_backend.ExtensionNotFoundException, lambda: b.extensions[load_extension])
def testRealLoginIfPossible(self): credentials_path = _GetCredentialsPath() if not credentials_path: logging.warning('Credentials file not found, skipping test.') return options = options_for_unittests.GetCopy() with browser_finder.FindBrowser(options).Create() as b: b.credentials.credentials_path = credentials_path if not b.credentials.CanLogin(self._credentials_type): return ret = b.credentials.LoginNeeded(b.tabs[0], self._credentials_type) self.assertTrue(ret)
def testBasicHosting(self): unittest_data_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'unittest_data') options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: b.SetHTTPServerDirectories(unittest_data_dir) t = b.tabs[0] t.Navigate(b.http_server.UrlOf('/blank.html')) t.WaitForDocumentReadyStateToBeComplete() x = t.EvaluateJavaScript('document.body.innerHTML') x = x.strip() self.assertEquals(x, 'Hello world')
def _CreateBrowser(self, with_autotest_ext): """Finds and creates a browser for tests. if with_autotest_ext is True, also loads the autotest extension""" options = options_for_unittests.GetCopy() if with_autotest_ext: extension_path = os.path.join(os.path.dirname(__file__), 'autotest_ext') self._load_extension = extension_to_load.ExtensionToLoad( extension_path, True) options.extensions_to_load = [self._load_extension] browser_to_create = browser_finder.FindBrowser(options) self.assertTrue(browser_to_create) return browser_to_create.Create()
def testNewCloseTab(self): options = options_for_unittests.GetCopy() browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: existing_tab = b.tabs[0] self.assertEquals(1, len(b.tabs)) existing_tab_url = existing_tab.url new_tab = b.tabs.New() self.assertEquals(2, len(b.tabs)) self.assertEquals(existing_tab.url, existing_tab_url) self.assertEquals(new_tab.url, 'about:blank') new_tab.Close() self.assertEquals(1, len(b.tabs)) self.assertEquals(existing_tab.url, existing_tab_url)
def testCommandLineOverriding(self): # This test starts the browser with --enable-benchmarking, which should # create a chrome.Interval namespace. This tests whether the command line is # being set. options = options_for_unittests.GetCopy() flag1 = '--user-agent=telemetry' options.extra_browser_args.append(flag1) browser_to_create = browser_finder.FindBrowser(options) with browser_to_create.Create() as b: t = b.tabs[0] t.Navigate('http://www.google.com/') t.WaitForDocumentReadyStateToBeInteractiveOrBetter() self.assertEquals(t.EvaluateJavaScript('navigator.userAgent'), 'telemetry')
def testHandlingOfCrashedTab(self): ps = page_set.PageSet() page1 = page_module.Page('chrome://crash', ps) ps.pages.append(page1) results = page_test.PageTestResults() class Test(page_test.PageTest): def RunTest(self, *args): pass with page_runner.PageRunner(ps) as runner: options = options_for_unittests.GetCopy() possible_browser = browser_finder.FindBrowser(options) runner.Run(options, possible_browser, Test('RunTest'), results) self.assertEquals(0, len(results.page_successes)) self.assertEquals(1, len(results.page_failures))
def testRealLoginWithDontOverrideProfileIfPossible(self): credentials_path = _GetCredentialsPath() if not credentials_path: logging.warning('Credentials file not found, skipping test.') return options = options_for_unittests.GetCopy() # Login once to make sure our default profile is logged in. with browser_finder.FindBrowser(options).Create() as b: b.credentials.credentials_path = credentials_path if not b.credentials.CanLogin(self._credentials_type): return tab = b.tabs[0] # Should not be logged in, since this is a fresh credentials # instance. self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type)) # Log in. ret = b.credentials.LoginNeeded(tab, self._credentials_type) # Make sure login was successful. self.assertTrue(ret) self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type)) # Reset state. Now the backend thinks we're logged out, even # though we are logged in in our current browser session. This # simulates the effects of running with --dont-override-profile. b.credentials._ResetLoggedInState() # pylint: disable=W0212 # Make sure the backend thinks we're logged out. self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type)) self.assertTrue(b.credentials.CanLogin(self._credentials_type)) # Attempt to login again. This should detect that we've hit # the 'logged in' page instead of the login form, and succeed # instead of timing out. ret = b.credentials.LoginNeeded(tab, self._credentials_type) # Make sure our login attempt did in fact succeed and set the # backend's internal state to 'logged in'. self.assertTrue(ret) self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type))
def setUp(self): extension_path = os.path.join(os.path.dirname(__file__), '..', '..', 'unittest_data', 'simple_extension') load_extension = extension_to_load.ExtensionToLoad(extension_path) options = options_for_unittests.GetCopy() options.extensions_to_load = [load_extension] browser_to_create = browser_finder.FindBrowser(options) self._browser = None self._extension = None if not browser_to_create: # May not find a browser that supports extensions. return self._browser = browser_to_create.Create() self._extension = self._browser.extensions[load_extension] self.assertTrue(self._extension)
def testComponentExtensionBasic(self): extension_path = os.path.join(os.path.dirname(__file__), '..', '..', 'unittest_data', 'component_extension') load_extension = extension_to_load.ExtensionToLoad( extension_path, True) options = options_for_unittests.GetCopy() options.extensions_to_load = [load_extension] browser_to_create = browser_finder.FindBrowser(options) if not browser_to_create: logging.warning('Did not find a browser that supports extensions, ' 'skipping test.') return with browser_to_create.Create() as b: extension = b.extensions[load_extension] extension.ExecuteJavaScript('setTestVar("abcdef")') self.assertEquals('abcdef', extension.EvaluateJavaScript('_testVar'))
def setUp(self): self._browser = None self._tab = None options = options_for_unittests.GetCopy() self.CustomizeBrowserOptions(options) if self._extra_browser_args: for arg in self._extra_browser_args: options.extra_browser_args.append(arg) browser_to_create = browser_finder.FindBrowser(options) if not browser_to_create: raise Exception('No browser found, cannot continue test.') try: self._browser = browser_to_create.Create() self._tab = self._browser.tabs[0] except: self.tearDown() raise
def RunBenchmark(self, benchmark, ps, options=None): """Runs a benchmark against a pageset, returning the rows its outputs.""" if options is None: options = options_for_unittests.GetCopy() assert options temp_parser = options.CreateParser() benchmark.AddCommandLineOptions(temp_parser) defaults = temp_parser.get_default_values() for k, v in defaults.__dict__.items(): if hasattr(options, k): continue setattr(options, k, v) benchmark.CustomizeBrowserOptions(options) possible_browser = browser_finder.FindBrowser(options) results = page_benchmark_results.PageBenchmarkResults() with page_runner.PageRunner(ps) as runner: runner.Run(options, possible_browser, benchmark, results) return results
def setUp(self): """ Copy the manifest and background.js files of simple_extension to a number of temporary directories to load as extensions""" self._extension_dirs = [tempfile.mkdtemp() for i in range(3)] # pylint: disable=W0612 src_extension_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', 'unittest_data', 'simple_extension')) manifest_path = os.path.join(src_extension_dir, 'manifest.json') script_path = os.path.join(src_extension_dir, 'background.js') for d in self._extension_dirs: shutil.copy(manifest_path, d) shutil.copy(script_path, d) self._extensions_to_load = [ extension_to_load.ExtensionToLoad(d) for d in self._extension_dirs ] options = options_for_unittests.GetCopy() options.extensions_to_load = self._extensions_to_load browser_to_create = browser_finder.FindBrowser(options) self._browser = None # May not find a browser that supports extensions. if browser_to_create: self._browser = browser_to_create.Create()