Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / page / actions / media_action.py
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
5 """Common media action functions."""
6
7 import logging
8 import os
9
10 from telemetry.core import util
11 from telemetry.page.actions import page_action
12
13
14 class MediaAction(page_action.PageAction):
15   def WillRunAction(self, tab):
16     """Loads the common media action JS code prior to running the action."""
17     self.LoadJS(tab, 'media_action.js')
18
19   def RunAction(self, tab):
20     super(MediaAction, self).RunAction(tab)
21
22   def LoadJS(self, tab, js_file_name):
23     """Loads and executes a JS file in the tab."""
24     with open(os.path.join(os.path.dirname(__file__), js_file_name)) as f:
25       js = f.read()
26       tab.ExecuteJavaScript(js)
27
28   def WaitForEvent(self, tab, selector, event_name, timeout_in_seconds):
29     """Halts media action until the selector's event is fired.
30
31     Args:
32       tab: The tab to check for event on.
33       selector: Media element selector.
34       event_name: Name of the event to check if fired or not.
35       timeout_in_seconds: Timeout to check for event, throws an exception if
36           not fired.
37     """
38     util.WaitFor(lambda:
39                      self.HasEventCompletedOrError(tab, selector, event_name),
40                  timeout=timeout_in_seconds)
41
42   def HasEventCompletedOrError(self, tab, selector, event_name):
43     if tab.EvaluateJavaScript(
44         'window.__hasEventCompleted("%s", "%s");' % (selector, event_name)):
45       return True
46     error = tab.EvaluateJavaScript('window.__error')
47     if error:
48       logging.error('Detected media error while waiting for %s: %s', event_name,
49                     error)
50       return True
51     return False