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