Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / local_server_unittest.py
1 # Copyright 2014 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 import BaseHTTPServer
5 import SimpleHTTPServer
6
7 from telemetry.core import local_server
8 from telemetry.unittest import tab_test_case
9
10 class SimpleLocalServerBackendRequestHandler(
11     SimpleHTTPServer.SimpleHTTPRequestHandler):
12   def do_GET(self):
13     msg = """<!DOCTYPE html>
14 <html>
15 <body>
16 hello world
17 </body>
18 """
19     self.send_response(200)
20     self.send_header('Content-Type', 'text/html')
21     self.send_header('Content-Length', len(msg))
22     self.end_headers()
23     self.wfile.write(msg)
24
25   def log_request(self, code='-', size='-'):
26     pass
27
28 class SimpleLocalServerBackend(BaseHTTPServer.HTTPServer,
29                                local_server.LocalServerBackend):
30   def __init__(self):
31     BaseHTTPServer.HTTPServer.__init__(
32       self, ('127.0.0.1', 0), SimpleLocalServerBackendRequestHandler)
33     local_server.LocalServerBackend.__init__(self)
34
35   def StartAndGetNamedPorts(self, args):
36     assert 'hello' in args
37     assert args['hello'] == 'world'
38     return [local_server.NamedPort('http', self.server_address[1])]
39
40   def ServeForever(self):
41     self.serve_forever()
42
43 class SimpleLocalServer(local_server.LocalServer):
44   def __init__(self):
45     super(SimpleLocalServer, self).__init__(SimpleLocalServerBackend)
46
47   def GetBackendStartupArgs(self):
48     return {'hello': 'world'}
49
50   @property
51   def url(self):
52     return self.forwarder.url + '/'
53
54 class LocalServerUnittest(tab_test_case.TabTestCase):
55   def testLocalServer(self):
56     server = SimpleLocalServer()
57     self._browser.StartLocalServer(server)
58     self.assertTrue(server in self._browser.local_servers)
59     self._tab.Navigate(server.url)
60     self._tab.WaitForDocumentReadyStateToBeComplete()
61     body_text = self._tab.EvaluateJavaScript('document.body.textContent')
62     body_text = body_text.strip()
63     self.assertEquals('hello world', body_text)
64
65   def testStartingAndRestarting(self):
66     server1 = SimpleLocalServer()
67     self._browser.StartLocalServer(server1)
68
69     server2 = SimpleLocalServer()
70     self.assertRaises(Exception,
71                       lambda: self._browser.StartLocalServer(server2))
72
73     server1.Close()
74     self.assertTrue(server1 not in self._browser.local_servers)
75
76     self._browser.StartLocalServer(server2)