Commit 80aedca1 authored by perezju's avatar perezju Committed by Commit bot

[tools/perf] Fix JavaScript interpolation in action_runner calls

The API on action_runner to run JavaScript now supports safe and simple
interpolation of values into code templates. This CL fixes and cleans
up many of the callers which weren't using robust methods for quoting
such values.

BUG=catapult:#3028

Review-Url: https://codereview.chromium.org/2618333006
Cr-Commit-Position: refs/heads/master@{#443194}
parent 7bc84c96
......@@ -25,9 +25,8 @@ class BlobCreateThenRead(page_module.Page):
for size_bytes in self._blob_sizes:
with action_runner.CreateInteraction('Action_CreateAndReadBlob',
repeatable=True):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript(
'createAndRead(' + str(size_bytes) + ');')
'createAndRead({{ size }});', size=size_bytes)
action_runner.WaitForJavaScriptCondition(
'doneReading === true || errors', timeout_in_seconds=60)
......@@ -51,8 +50,8 @@ class BlobMassCreate(page_module.Page):
for size_bytes in self._blob_sizes:
with action_runner.CreateInteraction('Action_CreateBlob',
repeatable=True):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('createBlob(' + str(size_bytes) + ');')
action_runner.ExecuteJavaScript(
'createBlob({{ size }});', size=size_bytes)
# Read blobs
for _ in range(0, NUM_BLOB_MASS_CREATE_READS):
......
......@@ -6,6 +6,7 @@ from page_sets.login_helpers import google_login
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry.util import js_template
import os
......@@ -67,8 +68,8 @@ class AdwordCampaignDesktopPage(page_module.Page):
page_set=page_set, name='AdwordsCampaign',
credentials_path='data/credentials.json',
shared_page_state_class=shared_page_state.SharedDesktopPageState)
self.script_to_evaluate_on_commit = (
'console.time("%s");' % INTERACTION_NAME)
self.script_to_evaluate_on_commit = js_template.Render(
'console.time({{ label }});', label=INTERACTION_NAME)
def RunNavigateSteps(self, action_runner):
google_login.LoginGoogleAccount(action_runner, 'google3',
......@@ -77,5 +78,5 @@ class AdwordCampaignDesktopPage(page_module.Page):
def RunPageInteractions(self, action_runner):
action_runner.WaitForElement(text='Welcome to AdWords!')
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('console.timeEnd("%s");' % INTERACTION_NAME)
action_runner.ExecuteJavaScript(
'console.timeEnd({{ label }});', label=INTERACTION_NAME)
......@@ -15,9 +15,8 @@ class IndexedDBEndurePage(page_module.Page):
self._subtest = subtest
def RunPageInteractions(self, action_runner):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('window.testFilter = "' +
self._subtest + '";')
action_runner.ExecuteJavaScript(
'window.testFilter = {{ subtest }};', subtest=self._subtest)
with action_runner.CreateInteraction('Action_Test'):
action_runner.ExecuteJavaScript('window.test();')
action_runner.WaitForJavaScriptCondition(
......
......@@ -418,9 +418,9 @@ class GwsExpansionPage(KeySilkCasesPage):
def ScrollKnowledgeCardToTop(self, action_runner, card_id):
# scroll until the knowledge card is at the top
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript(
"document.getElementById('%s').scrollIntoView()" % card_id)
"document.getElementById({{ card_id }}).scrollIntoView()",
card_id=card_id)
def PerformPageInteractions(self, action_runner):
self.ExpandKnowledgeCard(action_runner)
......@@ -648,20 +648,19 @@ class PolymerTopeka(KeySilkCasesPage):
first_name = profile + 'paper-input#first /deep/ input'
action_runner.WaitForElement(selector=first_name)
# Input First Name:
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('''
var fn = document.querySelector('%s');
var fn = document.querySelector({{ first_name }});
fn.value = 'Chrome';
fn.fire('input');''' % first_name)
fn.fire('input');''',
first_name=first_name)
# Input Last Initial:
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('''
var li = document.querySelector('%s paper-input#last /deep/ input');
var li = document.querySelector({{ selector }});
li.value = 'E';
li.fire('input');''' % profile)
li.fire('input');''',
selector='%s paper-input#last /deep/ input' % profile)
with action_runner.CreateInteraction('animation_interaction'):
# Click the check-mark to login:
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('''
window.topeka_page_transitions = 0;
[].forEach.call(document.querySelectorAll(
......@@ -671,7 +670,8 @@ class PolymerTopeka(KeySilkCasesPage):
window.topeka_page_transitions++;
});
});
document.querySelector('%s paper-fab').fire('tap')''' % profile)
document.querySelector({{ selector }}).fire('tap')''',
selector='%s paper-fab' % profile)
# Wait for category list to animate in:
action_runner.WaitForJavaScriptCondition('''
window.topeka_page_transitions === 1''')
......
......@@ -32,13 +32,13 @@ def LoginAccount(action_runner, credential,
# Wait until the "Sign in" button is enabled and then click it.
login_button_selector = '.login-form .login-button'
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.WaitForJavaScriptCondition('''
(function() {
var loginButton = document.querySelector("%s");
var loginButton = document.querySelector({{ selector }});
if (!loginButton)
return false;
return !loginButton.disabled;
})();''' % login_button_selector)
})();''',
selector=login_button_selector)
action_runner.ClickElement(selector=login_button_selector)
action_runner.WaitForNavigate()
......@@ -43,9 +43,8 @@ def LoginGoogleAccount(action_runner,
'https%3A%2F%2Faccounts.google.com%2FManageAccount')
# Wait until either the email or password input is visible.
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.WaitForJavaScriptCondition('%s || %s' % (
_EMAIL_INPUT_VISIBLE_CONDITION, _PASSWORD_INPUT_VISIBLE_CONDITION))
action_runner.WaitForJavaScriptCondition('{{ @a }} || {{ @b }}',
a=_EMAIL_INPUT_VISIBLE_CONDITION, b=_PASSWORD_INPUT_VISIBLE_CONDITION)
# If the email input is visible, this is the first Google login within the
# browser session, so we must enter both email and password. Otherwise, only
......
......@@ -45,10 +45,9 @@ def InputWithSelector(action_runner, input_text, input_selector):
possible exceptions.
"""
action_runner.WaitForElement(selector=input_selector)
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript(
'document.querySelector("%s").value = "%s";' %
(input_selector, input_text))
'document.querySelector({{ selector }}).value = {{ value }};',
selector=input_selector, value=input_text)
def InputForm(action_runner, input_text, input_id, form_id=None):
"""Sets the text value of an input field in a form on the page.
......
......@@ -4,6 +4,7 @@
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
from telemetry.util import js_template
class PolymerPage(page_module.Page):
......@@ -111,9 +112,8 @@ class PolymerShadowPage(PolymerPage):
def AnimateShadow(self, action_runner, eid):
for i in range(1, 6):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript(
'document.getElementById("{0}").z = {1}'.format(eid, i))
'document.getElementById({{ eid }}).z = {{ i }}', eid=eid, i=i)
action_runner.Wait(1)
......@@ -138,15 +138,13 @@ class PolymerSampler(PolymerPage):
def RunNavigateSteps(self, action_runner):
super(PolymerSampler, self).RunNavigateSteps(action_runner)
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
waitForLoadJS = """
action_runner.ExecuteJavaScript("""
window.Polymer.whenPolymerReady(function() {
%s.contentWindow.Polymer.whenPolymerReady(function() {
{{ @iframe }}.contentWindow.Polymer.whenPolymerReady(function() {
window.__polymer_ready = true;
})
});
""" % self.iframe_js
action_runner.ExecuteJavaScript(waitForLoadJS)
""", iframe=self.iframe_js)
action_runner.WaitForJavaScriptCondition(
'window.__polymer_ready')
......@@ -192,14 +190,15 @@ class PolymerSampler(PolymerPage):
def DoActionOnWidgetType(self, action_runner, widget_type, action_function):
# Find all widgets of this type, but skip any that are disabled or are
# currently active as they typically don't produce animation frames.
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
element_list_query = (self.iframe_js +
('.querySelectorAll("body %s:not([disabled]):'
'not([active])")' % widget_type))
element_list_query = js_template.Render(
'{{ @iframe }}.querySelectorAll({{ selector }})',
iframe=self.iframe_js,
selector='body %s:not([disabled]):not([active])' % widget_type)
roles_count_query = element_list_query + '.length'
for i in range(action_runner.EvaluateJavaScript(roles_count_query)):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
element_query = element_list_query + ("[%d]" % i)
element_query = js_template.Render(
'{{ @query }}[{{ i }}]', query=element_list_query, i=i)
if action_runner.EvaluateJavaScript(
element_query + '.offsetParent != null'):
# Only try to tap on visible elements (offsetParent != null)
......
......@@ -26,9 +26,10 @@ def Repaint(action_runner, mode='viewport', width=None, height=None):
chrome.gpuBenchmarking.runMicroBenchmark(
"invalidation_benchmark",
function(value) {},
""" + str(args) + """
{{ args }}
);
""")
""",
args=args)
micro_benchmark_id = action_runner.EvaluateJavaScript(
'window.benchmark_results.id')
......@@ -39,14 +40,14 @@ def Repaint(action_runner, mode='viewport', width=None, height=None):
with action_runner.CreateInteraction('Repaint'):
action_runner.RepaintContinuously(seconds=5)
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript("""
window.benchmark_results.message_handled =
chrome.gpuBenchmarking.sendMessageToMicroBenchmark(
""" + str(micro_benchmark_id) + """, {
{{ micro_benchmark_id }}, {
"notify_done": true
});
""")
""",
micro_benchmark_id=micro_benchmark_id)
def WaitThenRepaint(action_runner):
......
......@@ -222,9 +222,9 @@ class WashingtonPostMobileStory(_NewsBrowsingStory):
# window does not have a "Close" button, instead it has only a "Send link
# to phone" button. So on tablets we run with the popup window open. The
# popup is transparent, so this is mostly an aesthetical issue.
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
has_button = action_runner.EvaluateJavaScript(
'!!document.querySelector("%s")' % self._CLOSE_BUTTON_SELECTOR)
'!!document.querySelector({{ selector }})',
selector=self._CLOSE_BUTTON_SELECTOR)
if has_button:
action_runner.ClickElement(selector=self._CLOSE_BUTTON_SELECTOR)
super(WashingtonPostMobileStory, self)._DidLoadDocument(action_runner)
......
......@@ -187,9 +187,9 @@ class LoadWashingtonPostMobileStory(_LoadingStory):
# window does not have a "Close" button, instead it has only a "Send link
# to phone" button. So on tablets we run with the popup window open. The
# popup is transparent, so this is mostly an aesthetical issue.
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
has_button = action_runner.EvaluateJavaScript(
'!!document.querySelector("%s")' % self._CLOSE_BUTTON_SELECTOR)
'!!document.querySelector({{ selector }})',
selector=self._CLOSE_BUTTON_SELECTOR)
if has_button:
action_runner.ClickElement(selector=self._CLOSE_BUTTON_SELECTOR)
......
......@@ -35,9 +35,8 @@ class _MediaStory(system_health_story.SystemHealthStory):
raise NotImplementedError
def _WaitForAndClickElementBySelector(self, action_runner, selector):
element_function = 'document.querySelector("%s")' % selector
action_runner.WaitForElement(element_function=element_function)
action_runner.ClickElement(element_function=element_function)
action_runner.WaitForElement(selector=selector)
action_runner.ClickElement(selector=selector)
def _WaitForPlayTime(self, action_runner):
action_runner.Wait(self.PLAY_DURATION)
......@@ -46,10 +45,9 @@ class _MediaStory(system_health_story.SystemHealthStory):
self.PLAY_DURATION - self._GetTimeInSeconds(action_runner))
def _GetTimeInSeconds(self, action_runner):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
time_func = (
'document.querySelector("%s").textContent' % self.TIME_SELECTOR)
minutes, seconds = action_runner.EvaluateJavaScript(time_func).split(':')
minutes, seconds = action_runner.EvaluateJavaScript(
'document.querySelector({{ selector }}).textContent',
selector=self.TIME_SELECTOR).split(':')
return int(minutes * 60 + seconds)
......
......@@ -5,6 +5,7 @@
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
from telemetry import story
from telemetry.util import js_template
URL_LIST = [
......@@ -31,8 +32,8 @@ class TodoMVCPage(page_module.Page):
# TODO(jochen): This interaction does not include the
# WindowProxy::initialize portion before the commit. To fix this, we'll
# have to migrate to TBMv2.
self.script_to_evaluate_on_commit = (
'console.time("%s");' % INTERACTION_NAME)
self.script_to_evaluate_on_commit = js_template.Render(
'console.time({{ label }});', label=INTERACTION_NAME)
def RunPageInteractions(self, action_runner):
action_runner.ExecuteJavaScript(
......@@ -48,8 +49,8 @@ class TodoMVCPage(page_module.Page):
"""
)
action_runner.WaitForJavaScriptCondition('this.becameIdle === true')
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.ExecuteJavaScript('console.timeEnd("%s");' % INTERACTION_NAME)
action_runner.ExecuteJavaScript(
'console.timeEnd({{ label }});', label=INTERACTION_NAME)
class TodoMVCPageSet(story.StorySet):
......
......@@ -11,9 +11,8 @@ def _GetCurrentLocation(action_runner):
def _WaitForLocationChange(action_runner, old_href):
# TODO(catapult:#3028): Fix interpolation of JavaScript values.
action_runner.WaitForJavaScriptCondition(
'document.location.href != "%s"' % old_href)
'document.location.href != {{ old_href }}', old_href=old_href)
class Top7StressPage(page_module.Page):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment