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. 4 5from telemetry.core import exceptions 6from telemetry.core import util 7from telemetry.unittest import tab_test_case 8 9 10class InspectorRuntimeTest(tab_test_case.TabTestCase): 11 def testRuntimeEvaluateSimple(self): 12 res = self._tab.EvaluateJavaScript('1+1') 13 assert res == 2 14 15 def testRuntimeEvaluateThatFails(self): 16 self.assertRaises(exceptions.EvaluateException, 17 lambda: self._tab.EvaluateJavaScript('fsdfsdfsf')) 18 19 def testRuntimeEvaluateOfSomethingThatCantJSONize(self): 20 21 def test(): 22 self._tab.EvaluateJavaScript(""" 23 var cur = {}; 24 var root = {next: cur}; 25 for (var i = 0; i < 1000; i++) { 26 next = {}; 27 cur.next = next; 28 cur = next; 29 } 30 root;""") 31 self.assertRaises(exceptions.EvaluateException, test) 32 33 def testRuntimeExecuteOfSomethingThatCantJSONize(self): 34 self._tab.ExecuteJavaScript('window') 35 36 def testIFrame(self): 37 starting_contexts = self._tab.EnableAllContexts() 38 39 self.Navigate('host.html') 40 41 # Access host page. 42 test_defined_js = "typeof(testVar) != 'undefined'" 43 self._tab.WaitForJavaScriptExpression(test_defined_js, timeout=10) 44 45 expected_contexts = 4 + starting_contexts 46 47 util.WaitFor(lambda: self._tab.EnableAllContexts() == expected_contexts, 48 timeout=10) 49 50 self.assertEquals(self._tab.EvaluateJavaScript('testVar'), 'host') 51 52 def TestVarReady(context_id): 53 """Returns True if the context and testVar are both ready.""" 54 try: 55 return self._tab.EvaluateJavaScriptInContext(test_defined_js, 56 context_id) 57 except exceptions.EvaluateException: 58 # This happens when the context is not ready. 59 return False 60 61 def TestVar(context_id): 62 """Waits for testVar and the context to be ready, then returns the value 63 of testVar.""" 64 util.WaitFor(lambda: TestVarReady(context_id), timeout=10) 65 return self._tab.EvaluateJavaScriptInContext('testVar', context_id) 66 67 # Access parent page using EvaluateJavaScriptInContext. 68 self.assertEquals(TestVar(context_id=starting_contexts+1), 'host') 69 70 # Access the iframes without guarantees on which order they loaded. 71 iframe1 = TestVar(context_id=starting_contexts+2) 72 iframe2 = TestVar(context_id=starting_contexts+3) 73 iframe3 = TestVar(context_id=starting_contexts+4) 74 self.assertEqual(set([iframe1, iframe2, iframe3]), 75 set(['iframe1', 'iframe2', 'iframe3'])) 76 77 # Accessing a non-existent iframe throws an exception. 78 self.assertRaises(exceptions.EvaluateException, 79 lambda: self._tab.EvaluateJavaScriptInContext( 80 '1+1', context_id=starting_contexts+5)) 81