summaryrefslogtreecommitdiffstats
path: root/chrome/test/webdriver/chromedriver_tests.py
blob: e51e411bbae62e20e36b258244197107c586f7a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#!/usr/bin/python

# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for ChromeDriver.

If your test is testing a specific part of the WebDriver API, consider adding
it to the appropriate place in the WebDriver tree instead.
"""

import hashlib
import os
import platform
import sys
import unittest
import urllib
import urllib2
import urlparse

from chromedriver_launcher import ChromeDriverLauncher
import chromedriver_paths
from gtest_text_test_runner import GTestTextTestRunner

sys.path += [chromedriver_paths.SRC_THIRD_PARTY]
sys.path += [chromedriver_paths.PYTHON_BINDINGS]

try:
  import simplejson as json
except ImportError:
  import json

from selenium.webdriver.remote.command import Command
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


def DataDir():
  """Returns the path to the data dir chrome/test/data."""
  return os.path.normpath(
    os.path.join(os.path.dirname(__file__), os.pardir, "data"))


def GetFileURLForPath(path):
  """Get file:// url for the given path.
  Also quotes the url using urllib.quote().
  """
  abs_path = os.path.abspath(path)
  if sys.platform == 'win32':
    # Don't quote the ':' in drive letter ( say, C: ) on win.
    # Also, replace '\' with '/' as expected in a file:/// url.
    drive, rest = os.path.splitdrive(abs_path)
    quoted_path = drive.upper() + urllib.quote((rest.replace('\\', '/')))
    return 'file:///' + quoted_path
  else:
    quoted_path = urllib.quote(abs_path)
    return 'file://' + quoted_path


class Request(urllib2.Request):
  """Extends urllib2.Request to support all HTTP request types."""

  def __init__(self, url, method=None, data=None):
    """Initialise a new HTTP request.

    Arguments:
      url: The full URL to send the request to.
      method: The HTTP request method to use; defaults to 'GET'.
      data: The data to send with the request as a string. Defaults to
          None and is ignored if |method| is not 'POST' or 'PUT'.
    """
    if method is None:
      method = data is not None and 'POST' or 'GET'
    elif method not in ('POST', 'PUT'):
      data = None
    self.method = method
    urllib2.Request.__init__(self, url, data=data)

  def get_method(self):
    """Returns the HTTP method used by this request."""
    return self.method


def SendRequest(url, method=None, data=None):
  """Sends a HTTP request to the WebDriver server.

  Return values and exceptions raised are the same as those of
  |urllib2.urlopen|.

  Arguments:
    url: The full URL to send the request to.
    method: The HTTP request method to use; defaults to 'GET'.
    data: The data to send with the request as a string. Defaults to
        None and is ignored if |method| is not 'POST' or 'PUT'.

    Returns:
      A file-like object.
  """
  request = Request(url, method=method, data=data)
  request.add_header('Accept', 'application/json')
  opener = urllib2.build_opener(urllib2.HTTPRedirectHandler())
  return opener.open(request)


class BasicTest(unittest.TestCase):
  """Basic ChromeDriver tests."""

  def setUp(self):
    self._launcher = ChromeDriverLauncher()

  def tearDown(self):
    self._launcher.Kill()

  def testShouldReturn404WhenSentAnUnknownCommandURL(self):
    request_url = self._launcher.GetURL() + '/foo'
    try:
      SendRequest(request_url, method='GET')
      self.fail('Should have raised a urllib.HTTPError for returned 404')
    except urllib2.HTTPError, expected:
      self.assertEquals(404, expected.code)

  def testShouldReturnHTTP405WhenSendingANonPostToTheSessionURL(self):
    request_url = self._launcher.GetURL() + '/session'
    try:
      SendRequest(request_url, method='GET')
      self.fail('Should have raised a urllib.HTTPError for returned 405')
    except urllib2.HTTPError, expected:
      self.assertEquals(405, expected.code)
      self.assertEquals('POST', expected.hdrs['Allow'])

  def testShouldGetA404WhenAttemptingToDeleteAnUnknownSession(self):
    request_url = self._launcher.GetURL() + '/session/unkown_session_id'
    try:
      SendRequest(request_url, method='DELETE')
      self.fail('Should have raised a urllib.HTTPError for returned 404')
    except urllib2.HTTPError, expected:
      self.assertEquals(404, expected.code)

  def testShouldReturn204ForFaviconRequests(self):
    # Disabled until new python bindings are pulled in.
    return
    request_url = self._launcher.GetURL() + '/favicon.ico'
    response = SendRequest(request_url, method='GET')
    try:
      self.assertEquals(204, response.code)
    finally:
      response.close()

  def testCanStartChromeDriverOnSpecificPort(self):
    launcher = ChromeDriverLauncher(port=9520)
    self.assertEquals(9520, launcher.GetPort())
    driver = WebDriver(launcher.GetURL(), DesiredCapabilities.CHROME)
    driver.quit()
    launcher.Kill()


class NativeInputTest(unittest.TestCase):
  """Native input ChromeDriver tests."""

  def setUp(self):
    self._launcher = ChromeDriverLauncher(root_path=os.path.dirname(__file__))
    self._capabilities = DesiredCapabilities.CHROME
    self._capabilities["chrome"] = { "nativeEvents" : True }

  def tearDown(self):
    self._launcher.Kill()

  def testCanStartsWithNativeEvents(self):
    driver = WebDriver(self._launcher.GetURL(), self._capabilities)
    self.assertTrue(driver.capabilities["chrome"].has_key("nativeEvents"))
    self.assertTrue(driver.capabilities["chrome"]["nativeEvents"])

  def testSendKeysNative(self):
    driver = WebDriver(self._launcher.GetURL(), self._capabilities)
    driver.get(self._launcher.GetURL() + '/test_page.html')
    # Find the text input.
    q = driver.find_element_by_name("key_input_test")
    # Send some keys.
    q.send_keys("tokyo")
    #TODO(timothe): change to .text when beta 4 wrappers are out.
    self.assertEqual(q.value, "tokyo")

  #@unittest.skip("Need to run this on a machine with an IME installed.")
  def DISABLED_testSendKeysNativeProcessedByIME(self):
    driver = WebDriver(self._launcher.GetURL(), self.capabilities)
    driver.get(self._launcher.GetURL() + '/test_page.html')
    q = driver.find_element_by_name("key_input_test")
    # Send key combination to turn IME on.
    q.send_keys(Keys.F7)
    q.send_keys("toukyou")
    # Now turning it off.
    q.send_keys(Keys.F7)
    self.assertEqual(q.value, "\xe6\x9d\xb1\xe4\xba\xac")


class CookieTest(unittest.TestCase):
  """Cookie test for the json webdriver protocol"""

  def setUp(self):
    self._launcher = ChromeDriverLauncher()
    self._driver = WebDriver(self._launcher.GetURL(),
                             DesiredCapabilities.CHROME)

  def tearDown(self):
    self._driver.quit()
    self._launcher.Kill()

  def testAddCookie(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    cookie_dict = None
    cookie_dict = self._driver.get_cookie("chromedriver_cookie_test")
    cookie_dict = {}
    cookie_dict["name"]= "chromedriver_cookie_test"
    cookie_dict["value"] = "this is a test"
    self._driver.add_cookie(cookie_dict)
    cookie_dict = self._driver.get_cookie("chromedriver_cookie_test")
    self.assertNotEqual(cookie_dict, None)
    self.assertEqual(cookie_dict["value"], "this is a test")

  def testDeleteCookie(self):
    self.testAddCookie();
    self._driver.delete_cookie("chromedriver_cookie_test")
    cookie_dict = self._driver.get_cookie("chromedriver_cookie_test")
    self.assertEqual(cookie_dict, None)


class ScreenshotTest(unittest.TestCase):
  """Tests to verify screenshot retrieval"""

  REDBOX = "automation_proxy_snapshot/set_size.html"

  def setUp(self):
    self._launcher = ChromeDriverLauncher()
    self._driver = WebDriver(self._launcher.GetURL(), {})

  def tearDown(self):
    self._driver.quit()
    self._launcher.Kill()

  def testScreenCaptureAgainstReference(self):
    # Create a red square of 2000x2000 pixels.
    url = GetFileURLForPath(os.path.join(DataDir(),
                                         self.REDBOX))
    url += "?2000,2000"
    self._driver.get(url)
    s = self._driver.get_screenshot_as_base64();
    self._driver.get_screenshot_as_file("/tmp/foo.png")
    h = hashlib.md5(s).hexdigest()
    # Compare the PNG created to the reference hash.
    self.assertEquals(h, '12c0ade27e3875da3d8866f52d2fa84f')


class SessionTest(unittest.TestCase):
  """Tests dealing with WebDriver sessions."""

  def setUp(self):
    self._launcher = ChromeDriverLauncher()

  def tearDown(self):
    self._launcher.Kill()

  def testCreatingSessionShouldRedirectToCorrectURL(self):
    request_url = self._launcher.GetURL() + '/session'
    response = SendRequest(request_url, method='POST', data='{}')
    self.assertEquals(200, response.code)
    self.session_url = response.geturl()  # TODO(jleyba): verify this URL?

    data = json.loads(response.read())
    self.assertTrue(isinstance(data, dict))
    self.assertEquals(0, data['status'])

    url_parts = urlparse.urlparse(self.session_url)[2].split('/')
    self.assertEquals(3, len(url_parts))
    self.assertEquals('', url_parts[0])
    self.assertEquals('session', url_parts[1])
    self.assertEquals(data['sessionId'], url_parts[2])

  def testShouldBeGivenCapabilitiesWhenStartingASession(self):
    driver = WebDriver(self._launcher.GetURL(), {})
    capabilities = driver.capabilities

    self.assertEquals('chrome', capabilities['browserName'])
    self.assertTrue(capabilities['javascriptEnabled'])

    # Value depends on what version the server is starting.
    self.assertTrue('version' in capabilities)
    self.assertTrue(
        isinstance(capabilities['version'], unicode),
        'Expected a %s, but was %s' % (unicode,
                                       type(capabilities['version'])))

    system = platform.system()
    if system == 'Linux':
      self.assertEquals('linux', capabilities['platform'].lower())
    elif system == 'Windows':
      self.assertEquals('windows', capabilities['platform'].lower())
    elif system == 'Darwin':
      self.assertEquals('mac', capabilities['platform'].lower())
    else:
      # No python on ChromeOS, so we won't have a platform value, but
      # the server will know and return the value accordingly.
      self.assertEquals('chromeos', capabilities['platform'].lower())
    driver.quit()

  def testSessionCreationDeletion(self):
    driver = WebDriver(self._launcher.GetURL(), DesiredCapabilities.CHROME)
    driver.quit()

  def testMultipleSessionCreationDeletion(self):
    for i in range(10):
      driver = WebDriver(self._launcher.GetURL(), DesiredCapabilities.CHROME)
      driver.quit()

  def testSessionCommandsAfterSessionDeletionReturn404(self):
    driver = WebDriver(self._launcher.GetURL(), DesiredCapabilities.CHROME)
    session_id = driver.session_id
    driver.quit()
    try:
      response = SendRequest(self._launcher.GetURL() + '/session/' + session_id,
                             method='GET')
      self.fail('Should have thrown 404 exception')
    except urllib2.HTTPError, expected:
      self.assertEquals(404, expected.code)

  def testMultipleConcurrentSessions(self):
    drivers = []
    for i in range(10):
      drivers += [WebDriver(self._launcher.GetURL(),
                            DesiredCapabilities.CHROME)]
    for driver in drivers:
      driver.quit()


class MouseTest(unittest.TestCase):
  """Mouse command tests for the json webdriver protocol"""

  def setUp(self):
    self._launcher = ChromeDriverLauncher(root_path=os.path.dirname(__file__))
    self._driver = WebDriver(self._launcher.GetURL(),
                             DesiredCapabilities.CHROME)

  def tearDown(self):
    self._driver.quit()
    self._launcher.Kill()

  def testClickElementThatNeedsContainerScrolling(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    self._driver.find_element_by_name('hidden_scroll').click()
    self.assertTrue(self._driver.execute_script('return window.success'))

  def testClickElementThatNeedsIframeScrolling(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    self._driver.switch_to_frame('iframe')
    self._driver.find_element_by_name('hidden_scroll').click()
    self.assertTrue(self._driver.execute_script('return window.success'))

  def testClickElementThatNeedsPageScrolling(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    self._driver.find_element_by_name('far_away').click()
    self.assertTrue(self._driver.execute_script('return window.success'))

  def testDoNotScrollUnnecessarilyToClick(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    self._driver.find_element_by_name('near_top').click()
    self.assertTrue(self._driver.execute_script('return window.success'))
    script = 'return document.body.scrollTop == 0 && ' \
             '       document.body.scrollLeft == 0'
    self.assertTrue(self._driver.execute_script(script))


class UrlBaseTest(unittest.TestCase):
  """Tests that the server can be configured for a different URL base."""

  def setUp(self):
    self._launcher = ChromeDriverLauncher(url_base='/wd/hub')

  def tearDown(self):
    self._launcher.Kill()

  def testCreatingSessionShouldRedirectToCorrectURL(self):
    request_url = self._launcher.GetURL() + '/session'
    response = SendRequest(request_url, method='POST', data='{}')
    self.assertEquals(200, response.code)
    self.session_url = response.geturl()  # TODO(jleyba): verify this URL?

    data = json.loads(response.read())
    self.assertTrue(isinstance(data, dict))
    self.assertEquals(0, data['status'])

    url_parts = urlparse.urlparse(self.session_url)[2].split('/')
    self.assertEquals(5, len(url_parts))
    self.assertEquals('', url_parts[0])
    self.assertEquals('wd', url_parts[1])
    self.assertEquals('hub', url_parts[2])
    self.assertEquals('session', url_parts[3])
    self.assertEquals(data['sessionId'], url_parts[4])


# TODO(jleyba): Port this to WebDriver's own python test suite.
class ElementEqualityTest(unittest.TestCase):
  """Tests that the server properly checks element equality."""

  def setUp(self):
    self._launcher = ChromeDriverLauncher(root_path=os.path.dirname(__file__))
    self._driver = WebDriver(self._launcher.GetURL(), {})

  def tearDown(self):
    self._driver.quit()
    self._launcher.Kill()

  def testElementEquality(self):
    self._driver.get(self._launcher.GetURL() + '/test_page.html')
    body1 = self._driver.find_element_by_tag_name('body')
    body2 = self._driver.execute_script('return document.body')

    # TODO(jleyba): WebDriver's python bindings should expose a proper API
    # for this.
    result = body1.execute(Command.ELEMENT_EQUALS, {
      'other': body2.id
    })
    self.assertTrue(result['value'])


"""Chrome functional test section. All implementation tests of ChromeDriver
should go above.

TODO(dyu): Move these tests out of here when pyauto has these capabilities.
"""


def GetPathForDataFile(relative_path):
  """Returns the path for a test data file residing in this directory."""
  return os.path.join(os.path.dirname(__file__), relative_path)


class AutofillTest(unittest.TestCase):
  AUTOFILL_EDIT_ADDRESS = 'chrome://settings/autoFillEditAddress'

  def setUp(self):
    self._launcher = ChromeDriverLauncher()

  def tearDown(self):
    self._launcher.Kill()

  def DISABLED_testPostalCodeAndStateLabelsBasedOnCountry(self):
    """Verify postal code and state labels based on selected country."""
    import simplejson
    test_data = simplejson.loads(
        open(GetPathForDataFile('state_zip_labels.txt')).read())

    driver = WebDriver(self._launcher.GetURL(), {})
    driver.get(self.AUTOFILL_EDIT_ADDRESS)
    state_label = driver.find_element_by_id('state-label').text
    self.assertEqual('State', state_label)
    for country_code in test_data:
      query = '//option[@value="%s"]' % country_code
      driver.find_element_by_id('country').find_element_by_xpath(query).select()
      # Compare postal labels.
      actual_postal_label = driver.find_element_by_id(
          'postal-code-label').text
      expected_postal_label = test_data[country_code]['postalCodeLabel']
      self.assertEqual(
          actual_postal_label, expected_postal_label,
          'Postal code label does not match Country "%s"' % country_code)
      # Compare state labels.
      actual_state_label = driver.find_element_by_id('state-label').text
      expected_state_label = test_data[country_code]['stateLabel']
      self.assertEqual(
          actual_state_label, expected_state_label,
          'State label does not match Country "%s"' % country_code)

if __name__ == '__main__':
  unittest.main(module='chromedriver_tests',
                testRunner=GTestTextTestRunner(verbosity=1))