1# Copyright 2015 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.
4import logging
5import math
6import os
7
8from telemetry import decorators
9from telemetry.internal.actions import drag
10from telemetry.internal.actions import page_action
11from telemetry.testing import tab_test_case
12
13
14class DragActionTest(tab_test_case.TabTestCase):
15  def CheckWithinRange(self, value, expected, error_ratio):
16    error_range = abs(expected * error_ratio)
17    return abs(value - expected) <= error_range
18
19  @decorators.Disabled('chromeos')  # crbug.com/483212
20  def testDragAction(self):
21    self.Navigate('draggable.html')
22
23    with open(os.path.join(os.path.dirname(__file__),
24                           'gesture_common.js')) as f:
25      js = f.read()
26      self._tab.ExecuteJavaScript(js)
27
28    div_width = self._tab.EvaluateJavaScript(
29        '__GestureCommon_GetBoundingVisibleRect(document.body).width')
30    div_height = self._tab.EvaluateJavaScript(
31        '__GestureCommon_GetBoundingVisibleRect(document.body).height')
32
33    i = drag.DragAction(left_start_ratio=0.5, top_start_ratio=0.5,
34            left_end_ratio=0.25, top_end_ratio=0.25)
35    try:
36      i.WillRunAction(self._tab)
37    except page_action.PageActionNotSupported:
38      logging.warning('This browser does not support drag gesture. Please try'
39                      ' updating chrome.')
40      return
41
42    self._tab.ExecuteJavaScript('''
43        window.__dragAction.beginMeasuringHook = function() {
44            window.__didBeginMeasuring = true;
45        };
46        window.__dragAction.endMeasuringHook = function() {
47            window.__didEndMeasuring = true;
48        };''')
49    i.RunAction(self._tab)
50
51    self.assertTrue(self._tab.EvaluateJavaScript('window.__didBeginMeasuring'))
52    self.assertTrue(self._tab.EvaluateJavaScript('window.__didEndMeasuring'))
53
54    div_position_x = self._tab.EvaluateJavaScript(
55        'document.getElementById("drag_div").offsetLeft')
56    div_position_y = self._tab.EvaluateJavaScript(
57        'document.getElementById("drag_div").offsetTop')
58
59    # 0.25 is the ratio of displacement to the initial size.
60    expected_x = math.floor(div_width * -0.25)
61    expected_y = math.floor(div_height * -0.25)
62    error_ratio = 0.1
63
64    self.assertTrue(
65        self.CheckWithinRange(div_position_x, expected_x, error_ratio),
66        msg="Moved element's left coordinate: %d, expected: %d" %
67        (div_position_x, expected_x))
68    self.assertTrue(
69        self.CheckWithinRange(div_position_y, expected_y, error_ratio),
70        msg="Moved element's top coordinate: %d, expected: %d" %
71        (div_position_y, expected_y))
72