How to use server method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

gcdwebserver.gyp

Source: gcdwebserver.gyp Github

copy
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{
5  'targets' : [
6    {
7      'target_name' : 'gcdwebserver',
8      'type': 'static_library',
9      'include_dirs': [
10        'src/GCDWebServer/Core',
11        'src/GCDWebServer/Requests',
12        'src/GCDWebServer/Responses',
13      ],
14      'direct_dependent_settings': {
15        'include_dirs': [
16          'src/GCDWebServer/Core',
17          'src/GCDWebServer/Requests',
18          'src/GCDWebServer/Responses',
19        ],
20      },
21      'xcode_settings': {
22        'CLANG_ENABLE_OBJC_ARC': 'YES',
23      },
24      'sources': [
25        'src/GCDWebServer/Core/GCDWebServer.h',
26        'src/GCDWebServer/Core/GCDWebServer.m',
27        'src/GCDWebServer/Core/GCDWebServerConnection.h',
28        'src/GCDWebServer/Core/GCDWebServerConnection.m',
29        'src/GCDWebServer/Core/GCDWebServerFunctions.h',
30        'src/GCDWebServer/Core/GCDWebServerFunctions.m',
31        'src/GCDWebServer/Core/GCDWebServerHTTPStatusCodes.h',
32        'src/GCDWebServer/Core/GCDWebServerPrivate.h',
33        'src/GCDWebServer/Core/GCDWebServerRequest.h',
34        'src/GCDWebServer/Core/GCDWebServerRequest.m',
35        'src/GCDWebServer/Core/GCDWebServerResponse.h',
36        'src/GCDWebServer/Core/GCDWebServerResponse.m',
37        'src/GCDWebServer/Requests/GCDWebServerDataRequest.h',
38        'src/GCDWebServer/Requests/GCDWebServerDataRequest.m',
39        'src/GCDWebServer/Requests/GCDWebServerFileRequest.h',
40        'src/GCDWebServer/Requests/GCDWebServerFileRequest.m',
41        'src/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.h',
42        'src/GCDWebServer/Requests/GCDWebServerMultiPartFormRequest.m',
43        'src/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.h',
44        'src/GCDWebServer/Requests/GCDWebServerURLEncodedFormRequest.m',
45        'src/GCDWebServer/Responses/GCDWebServerDataResponse.h',
46        'src/GCDWebServer/Responses/GCDWebServerDataResponse.m',
47        'src/GCDWebServer/Responses/GCDWebServerErrorResponse.h',
48        'src/GCDWebServer/Responses/GCDWebServerErrorResponse.m',
49        'src/GCDWebServer/Responses/GCDWebServerFileResponse.h',
50        'src/GCDWebServer/Responses/GCDWebServerFileResponse.m',
51        'src/GCDWebServer/Responses/GCDWebServerStreamedResponse.h',
52        'src/GCDWebServer/Responses/GCDWebServerStreamedResponse.m',
53      ],
54      'link_settings': {
55        'libraries': [
56          '$(SDKROOT)/System/Library/Frameworks/CFNetwork.framework',
57          '$(SDKROOT)/System/Library/Frameworks/MobileCoreServices.framework',
58        ],
59        'xcode_settings': {
60          'OTHER_LDFLAGS': [
61            '-lz',
62          ],
63        },
64      },
65    },
66  ],
67}
68
Full Screen

iperf_server_test.py

Source: iperf_server_test.py Github

copy
1#!/usr/bin/env python3
2#
3#   Copyright 2019 - The Android Open Source Project
4#
5#   Licensed under the Apache License, Version 2.0 (the "License");
6#   you may not use this file except in compliance with the License.
7#   You may obtain a copy of the License at
8#
9#       http://www.apache.org/licenses/LICENSE-2.0
10#
11#   Unless required by applicable law or agreed to in writing, software
12#   distributed under the License is distributed on an "AS IS" BASIS,
13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14#   See the License for the specific language governing permissions and
15#   limitations under the License.
16import logging
17import unittest
18
19import mock
20import os
21
22from acts.controllers import iperf_server
23from acts.controllers.iperf_server import IPerfServer
24from acts.controllers.iperf_server import IPerfServerOverAdb
25from acts.controllers.iperf_server import IPerfServerOverSsh
26
27# The position in the call tuple that represents the args array.
28ARGS = 0
29
30# The position in the call tuple that represents the kwargs dict.
31KWARGS = 1
32
33MOCK_LOGFILE_PATH = '/path/to/foo'
34
35
36class IPerfServerModuleTest(unittest.TestCase):
37    """Tests the acts.controllers.iperf_server module."""
38
39    def test_create_creates_local_iperf_server_with_int(self):
40        self.assertIsInstance(
41            iperf_server.create([12345])[0],
42            IPerfServer,
43            'create() failed to create IPerfServer for integer input.'
44        )
45
46    def test_create_creates_local_iperf_server_with_str(self):
47        self.assertIsInstance(
48            iperf_server.create(['12345'])[0],
49            IPerfServer,
50            'create() failed to create IPerfServer for integer input.'
51        )
52
53    def test_create_cannot_create_local_iperf_server_with_bad_str(self):
54        with self.assertRaises(ValueError):
55            iperf_server.create(['12345BAD_STRING'])
56
57    @mock.patch('acts.controllers.iperf_server.utils')
58    def test_create_creates_server_over_ssh_with_ssh_config_and_port(self, _):
59        self.assertIsInstance(
60            iperf_server.create([{'ssh_config': {'user': '', 'host': ''},
61                                  'port': ''}])[0],
62            IPerfServerOverSsh,
63            'create() failed to create IPerfServerOverSsh for a valid config.'
64        )
65
66    def test_create_creates_server_over_adb_with_proper_config(self):
67        self.assertIsInstance(
68            iperf_server.create([{'AndroidDevice': '53R147', 'port': 0}])[0],
69            IPerfServerOverAdb,
70            'create() failed to create IPerfServerOverAdb for a valid config.'
71        )
72
73    def test_create_raises_value_error_on_bad_config_dict(self):
74        with self.assertRaises(ValueError):
75            iperf_server.create([{'AndroidDevice': '53R147', 'ssh_config': {}}])
76
77    def test_get_port_from_ss_output_returns_correct_port_ipv4(self):
78        ss_output = ('tcp LISTEN  0 5 127.0.0.1:<PORT>  *:*'
79                     ' users:(("cmd",pid=<PID>,fd=3))')
80        self.assertEqual(
81            iperf_server._get_port_from_ss_output(ss_output, '<PID>'), '<PORT>')
82
83    def test_get_port_from_ss_output_returns_correct_port_ipv6(self):
84        ss_output = ('tcp LISTEN  0 5 ff:ff:ff:ff:ff:ff:<PORT>  *:*'
85                     ' users:(("cmd",pid=<PID>,fd=3))')
86        self.assertEqual(
87            iperf_server._get_port_from_ss_output(ss_output, '<PID>'), '<PORT>')
88
89
90class IPerfServerBaseTest(unittest.TestCase):
91    """Tests acts.controllers.iperf_server.IPerfServerBase."""
92
93    @mock.patch('os.makedirs')
94    def test_get_full_file_path_creates_parent_directory(self, mock_makedirs):
95        # Will never actually be created/used.
96        logging.log_path = '/tmp/unit_test_garbage'
97
98        server = IPerfServer('port')
99
100        full_file_path = server._get_full_file_path()
101
102        self.assertTrue(
103            mock_makedirs.called,
104            'Did not attempt to create a directory.'
105        )
106        self.assertEqual(
107            os.path.dirname(full_file_path),
108            mock_makedirs.call_args[ARGS][0],
109            'The parent directory of the full file path was not created.'
110        )
111
112
113class IPerfServerTest(unittest.TestCase):
114    """Tests acts.controllers.iperf_server.IPerfServer."""
115
116    PID = 123456
117
118    def setUp(self):
119        iperf_server._get_port_from_ss_output = lambda *_: IPerfServerTest.PID
120
121    @mock.patch('builtins.open')
122    @mock.patch('acts.controllers.iperf_server.subprocess')
123    @mock.patch('acts.controllers.iperf_server.job')
124    def test_start_makes_started_true(self, mock_job, __, ___):
125        """Tests calling start() without calling stop() makes started True."""
126        server = IPerfServer('port')
127        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
128        server.start()
129
130        self.assertTrue(server.started)
131
132    @mock.patch('builtins.open')
133    @mock.patch('acts.controllers.iperf_server.subprocess')
134    @mock.patch('acts.controllers.iperf_server.job')
135    def test_start_stop_makes_started_false(self, _, __, ___):
136        """Tests calling start() without calling stop() makes started True."""
137        server = IPerfServer('port')
138        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
139
140        server.start()
141        server.stop()
142
143        self.assertFalse(server.started)
144
145    @mock.patch('builtins.open')
146    @mock.patch('acts.controllers.iperf_server.subprocess')
147    @mock.patch('acts.controllers.iperf_server.job')
148    def test_start_sets_current_log_file(self, _, __, ___):
149        server = IPerfServer('port')
150        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
151
152        server.start()
153
154        self.assertEqual(
155            server._current_log_file,
156            MOCK_LOGFILE_PATH,
157            'The _current_log_file was not received from _get_full_file_path.'
158        )
159
160    @mock.patch('builtins.open')
161    @mock.patch('acts.controllers.iperf_server.subprocess')
162    def test_stop_returns_current_log_file(self, _, __):
163        server = IPerfServer('port')
164        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
165        server._current_log_file = MOCK_LOGFILE_PATH
166        server._iperf_process = mock.Mock()
167
168        log_file = server.stop()
169
170        self.assertEqual(
171            log_file,
172            MOCK_LOGFILE_PATH,
173            'The _current_log_file was not returned by stop().'
174        )
175
176    @mock.patch('builtins.open')
177    @mock.patch('acts.controllers.iperf_server.subprocess')
178    @mock.patch('acts.controllers.iperf_server.job')
179    def test_start_does_not_run_two_concurrent_processes(self, start_proc, _, __):
180        server = IPerfServer('port')
181        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
182        server._iperf_process = mock.Mock()
183
184        server.start()
185
186        self.assertFalse(
187            start_proc.called,
188            'start() should not begin a second process if another is running.'
189        )
190
191    @mock.patch('acts.utils.stop_standing_subprocess')
192    def test_stop_exits_early_if_no_process_has_started(self, stop_proc):
193        server = IPerfServer('port')
194        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
195        server._iperf_process = None
196
197        server.stop()
198
199        self.assertFalse(
200            stop_proc.called,
201            'stop() should not kill a process if no process is running.'
202        )
203
204
205class IPerfServerOverSshTest(unittest.TestCase):
206    """Tests acts.controllers.iperf_server.IPerfServerOverSsh."""
207
208    INIT_ARGS = [{'host': 'TEST_HOST', 'user': 'test'}, 'PORT']
209
210    @mock.patch('acts.controllers.iperf_server.connection')
211    def test_start_makes_started_true(self, _):
212        """Tests calling start() without calling stop() makes started True."""
213        server = IPerfServerOverSsh(*self.INIT_ARGS)
214        server._ssh_session = mock.Mock()
215        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
216
217        server.start()
218
219        self.assertTrue(server.started)
220
221    @mock.patch('builtins.open')
222    @mock.patch('acts.controllers.iperf_server.connection')
223    def test_start_stop_makes_started_false(self, _, __):
224        """Tests calling start() without calling stop() makes started True."""
225        server = IPerfServerOverSsh(*self.INIT_ARGS)
226        server._ssh_session = mock.Mock()
227        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
228
229        server.start()
230        server.stop()
231
232        self.assertFalse(server.started)
233
234    @mock.patch('builtins.open')
235    @mock.patch('acts.controllers.iperf_server.connection')
236    def test_stop_returns_expected_log_file(self, _, __):
237        server = IPerfServerOverSsh(*self.INIT_ARGS)
238        server._ssh_session = mock.Mock()
239        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
240        server._iperf_pid = mock.Mock()
241
242        log_file = server.stop()
243
244        self.assertEqual(
245            log_file,
246            MOCK_LOGFILE_PATH,
247            'The expected log file was not returned by stop().'
248        )
249
250    @mock.patch('acts.controllers.iperf_server.connection')
251    def test_start_does_not_run_two_concurrent_processes(self, _):
252        server = IPerfServerOverSsh(*self.INIT_ARGS)
253        server._ssh_session = mock.Mock()
254        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
255        server._iperf_pid = mock.Mock()
256
257        server.start()
258
259        self.assertFalse(
260            server._ssh_session.run_async.called,
261            'start() should not begin a second process if another is running.'
262        )
263
264    @mock.patch('acts.utils.stop_standing_subprocess')
265    @mock.patch('acts.controllers.iperf_server.connection')
266    def test_stop_exits_early_if_no_process_has_started(self, _, __):
267        server = IPerfServerOverSsh(*self.INIT_ARGS)
268        server._ssh_session = mock.Mock()
269        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
270        server._iperf_pid = None
271
272        server.stop()
273
274        self.assertFalse(
275            server._ssh_session.run_async.called,
276            'stop() should not kill a process if no process is running.'
277        )
278
279
280class IPerfServerOverAdbTest(unittest.TestCase):
281    """Tests acts.controllers.iperf_server.IPerfServerOverSsh."""
282
283    ANDROID_DEVICE_PROP = ('acts.controllers.iperf_server.'
284                           'IPerfServerOverAdb._android_device')
285
286    @mock.patch(ANDROID_DEVICE_PROP)
287    def test_start_makes_started_true(self, mock_ad):
288        """Tests calling start() without calling stop() makes started True."""
289        server = IPerfServerOverAdb('53R147', 'PORT')
290        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
291        mock_ad.adb.shell.return_value = '<PID>'
292
293        server.start()
294
295        self.assertTrue(server.started)
296
297    @mock.patch('acts.libs.proc.job.run')
298    @mock.patch('builtins.open')
299    @mock.patch(ANDROID_DEVICE_PROP)
300    def test_start_stop_makes_started_false(self, mock_ad, _, __):
301        """Tests calling start() without calling stop() makes started True."""
302        server = IPerfServerOverAdb('53R147', 'PORT')
303        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
304        mock_ad.adb.shell.side_effect = ['<PID>', '', '', '']
305
306        server.start()
307        server.stop()
308
309        self.assertFalse(server.started)
310
311    @mock.patch('acts.libs.proc.job.run')
312    @mock.patch('builtins.open')
313    @mock.patch(ANDROID_DEVICE_PROP)
314    def test_stop_returns_expected_log_file(self, mock_ad, _, __):
315        server = IPerfServerOverAdb('53R147', 'PORT')
316        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
317        server._iperf_process = mock.Mock()
318        server._iperf_process_adb_pid = '<PID>'
319        mock_ad.adb.shell.side_effect = ['', '', '']
320
321        log_file = server.stop()
322
323        self.assertEqual(
324            log_file,
325            MOCK_LOGFILE_PATH,
326            'The expected log file was not returned by stop().'
327        )
328
329    @mock.patch(ANDROID_DEVICE_PROP)
330    def test_start_does_not_run_two_concurrent_processes(self, android_device):
331        server = IPerfServerOverAdb('53R147', 'PORT')
332        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
333        server._iperf_process = mock.Mock()
334
335        server.start()
336
337        self.assertFalse(
338            android_device.adb.shell_nb.called,
339            'start() should not begin a second process if another is running.'
340        )
341
342    @mock.patch('acts.libs.proc.job.run')
343    @mock.patch('builtins.open')
344    @mock.patch(ANDROID_DEVICE_PROP)
345    def test_stop_exits_early_if_no_process_has_started(self, android_device, _,
346                                                        __):
347        server = IPerfServerOverAdb('53R147', 'PORT')
348        server._get_full_file_path = lambda _: MOCK_LOGFILE_PATH
349        server._iperf_pid = None
350
351        server.stop()
352
353        self.assertFalse(
354            android_device.adb.shell_nb.called,
355            'stop() should not kill a process if no process is running.'
356        )
357
358
359if __name__ == '__main__':
360    unittest.main()
361
Full Screen

wsgi_server_test.py

Source: wsgi_server_test.py Github

copy
1#!/usr/bin/env python
2#
3# Copyright 2007 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Tests for google.appengine.tools.devappserver2.wsgi_server."""
18
19
20
21import errno
22import json
23import os
24import select
25import socket
26import sys
27import time
28import unittest
29import urllib2
30
31import google
32import mox
33
34
35
36
37
38
39
40
41
42
43
44
45
46from cherrypy import wsgiserver
47
48from google.appengine.tools.devappserver2 import wsgi_server
49
50
51class TestError(Exception):
52  pass
53
54
55class _SingleAddressWsgiServerTest(unittest.TestCase):
56  def setUp(self):
57    super(_SingleAddressWsgiServerTest, self).setUp()
58    self.server = wsgi_server._SingleAddressWsgiServer(('localhost', 0),
59                                                       self.wsgi_application)
60    self.server.start()
61
62  def tearDown(self):
63    super(_SingleAddressWsgiServerTest, self).tearDown()
64    self.server.quit()
65
66  def test_serve(self):
67    result = urllib2.urlopen('http://localhost:%d/foo?bar=baz' %
68                             self.server.port)
69    body = result.read()
70    environ = json.loads(body)
71    self.assertEqual(200, result.code)
72    self.assertEqual('/foo', environ['PATH_INFO'])
73    self.assertEqual('bar=baz', environ['QUERY_STRING'])
74
75  def wsgi_application(self, environ, start_response):
76    start_response('200 OK', [('Content-Type', 'application/json')])
77    serializable_environ = environ.copy()
78    del serializable_environ['wsgi.input']
79    del serializable_environ['wsgi.errors']
80    return [json.dumps(serializable_environ)]
81
82  def other_wsgi_application(self, environ, start_response):
83    start_response('200 OK', [('Content-Type', 'text/plain')])
84    return ['Hello World']
85
86  def test_set_app(self):
87    self.server.set_app(self.other_wsgi_application)
88    result = urllib2.urlopen('http://localhost:%d/foo?bar=baz' %
89                             self.server.port)
90    body = result.read()
91    self.assertEqual(200, result.code)
92    self.assertEqual('Hello World', body)
93
94  def test_set_error(self):
95    self.server.set_error(204)
96    result = urllib2.urlopen('http://localhost:%d/foo?bar=baz' %
97                             self.server.port)
98    self.assertEqual(204, result.code)
99
100
101class SharedCherryPyThreadPoolTest(unittest.TestCase):
102
103  def setUp(self):
104    self.mox = mox.Mox()
105    self.mox.StubOutWithMock(wsgi_server._THREAD_POOL, 'submit')
106    self.thread_pool = wsgi_server._SharedCherryPyThreadPool()
107
108  def tearDown(self):
109    self.mox.UnsetStubs()
110
111  def test_put(self):
112    connection = object()
113    wsgi_server._THREAD_POOL.submit(self.thread_pool._handle, connection)
114    self.mox.ReplayAll()
115    self.thread_pool.put(connection)
116    self.mox.VerifyAll()
117    self.assertEqual(set([connection]), self.thread_pool._connections)
118
119  def test_handle(self):
120    connection = self.mox.CreateMock(wsgiserver.HTTPConnection)
121    self.mox.StubOutWithMock(self.thread_pool._condition, 'notify')
122    self.thread_pool._connections.add(connection)
123    connection.communicate()
124    connection.close()
125    self.thread_pool._condition.notify()
126    self.mox.ReplayAll()
127    self.thread_pool._handle(connection)
128    self.mox.VerifyAll()
129    self.assertEqual(set(), self.thread_pool._connections)
130
131  def test_handle_with_exception(self):
132    connection = self.mox.CreateMock(wsgiserver.HTTPConnection)
133    self.mox.StubOutWithMock(self.thread_pool._condition, 'notify')
134    self.thread_pool._connections.add(connection)
135    connection.communicate().AndRaise(TestError)
136    connection.close()
137    self.thread_pool._condition.notify()
138    self.mox.ReplayAll()
139    self.assertRaises(TestError, self.thread_pool._handle, connection)
140    self.mox.VerifyAll()
141    self.assertEqual(set(), self.thread_pool._connections)
142
143  def test_stop(self):
144    self.mox.ReplayAll()
145    self.thread_pool.stop(3)
146    self.mox.VerifyAll()
147
148  def test_stop_no_connections(self):
149    self.mox.ReplayAll()
150    self.thread_pool.stop(0.1)
151    self.mox.VerifyAll()
152
153  def test_stop_with_connections(self):
154    connection = self.mox.CreateMock(wsgiserver.HTTPConnection)
155    self.thread_pool._connections.add(connection)
156    self.mox.StubOutWithMock(self.thread_pool, '_shutdown_connection')
157    self.thread_pool._shutdown_connection(connection)
158
159    self.mox.ReplayAll()
160    self.thread_pool.stop(1)
161    self.mox.VerifyAll()
162
163  def test_shutdown_connection(self):
164
165    class DummyObect(object):
166      pass
167
168    connection = DummyObect()
169    connection.rfile = DummyObect()
170    connection.rfile.closed = False
171    connection.socket = self.mox.CreateMockAnything()
172    connection.socket.shutdown(socket.SHUT_RD)
173
174    self.mox.ReplayAll()
175    self.thread_pool._shutdown_connection(connection)
176    self.mox.VerifyAll()
177
178  def test_shutdown_connection_rfile_already_close(self):
179
180    class DummyObect(object):
181      pass
182
183    connection = DummyObect()
184    connection.rfile = DummyObect()
185    connection.rfile.closed = True
186    connection.socket = self.mox.CreateMockAnything()
187
188    self.mox.ReplayAll()
189    self.thread_pool._shutdown_connection(connection)
190    self.mox.VerifyAll()
191
192
193class SelectThreadTest(unittest.TestCase):
194
195  class _MockSocket(object):
196    def fileno(self):
197      return id(self)
198
199  def setUp(self):
200    self.select_thread = wsgi_server.SelectThread()
201    self.original_has_poll = wsgi_server._HAS_POLL
202    self.mox = mox.Mox()
203    self.mox.StubOutWithMock(select, 'select')
204    if hasattr(select, 'poll'):
205      self.mox.StubOutWithMock(select, 'poll')
206    self.mox.StubOutWithMock(time, 'sleep')
207
208  def tearDown(self):
209    self.mox.UnsetStubs()
210    wsgi_server._HAS_POLL = self.original_has_poll
211
212  def test_add_socket(self):
213    file_descriptors = self.select_thread._file_descriptors
214    file_descriptor_to_callback = (
215        self.select_thread._file_descriptor_to_callback)
216    file_descriptors_copy = frozenset(self.select_thread._file_descriptors)
217    file_descriptor_to_callback_copy = (
218        self.select_thread._file_descriptor_to_callback.copy())
219    s = self._MockSocket()
220    callback = object()
221    self.select_thread.add_socket(s, callback)
222    self.assertEqual(file_descriptors_copy, file_descriptors)
223    self.assertEqual(file_descriptor_to_callback_copy,
224                     file_descriptor_to_callback)
225    self.assertEqual(frozenset([s.fileno()]),
226                     self.select_thread._file_descriptors)
227    self.assertEqual({s.fileno(): callback},
228                     self.select_thread._file_descriptor_to_callback)
229
230  def test_remove_socket(self):
231    s1 = self._MockSocket()
232    callback1 = object()
233    s2 = self._MockSocket()
234    callback2 = object()
235    self.select_thread._file_descriptors = frozenset([s1.fileno(), s2.fileno()])
236    self.select_thread._file_descriptor_to_callback = {
237        s1.fileno(): callback1, s2.fileno(): callback2}
238    file_descriptors = self.select_thread._file_descriptors
239    file_descriptor_to_callback = (
240        self.select_thread._file_descriptor_to_callback)
241    file_descriptors_copy = frozenset(self.select_thread._file_descriptors)
242    file_descriptor_to_callback_copy = (
243        self.select_thread._file_descriptor_to_callback.copy())
244    self.select_thread.remove_socket(s1)
245    self.assertEqual(file_descriptors_copy, file_descriptors)
246    self.assertEqual(file_descriptor_to_callback_copy,
247                     file_descriptor_to_callback)
248    self.assertEqual(frozenset([s2.fileno()]),
249                     self.select_thread._file_descriptors)
250    self.assertEqual({s2.fileno(): callback2},
251                     self.select_thread._file_descriptor_to_callback)
252
253  def test_select_no_sockets(self):
254    time.sleep(1)
255    self.mox.ReplayAll()
256    self.select_thread._select()
257    self.mox.VerifyAll()
258
259  def test_select_no_poll(self):
260    wsgi_server._HAS_POLL = False
261    s = self._MockSocket()
262    callback = self.mox.CreateMockAnything()
263    select.select(frozenset([s.fileno()]), [], [], 1).AndReturn(
264        ([s.fileno()], [], []))
265    callback()
266    self.mox.ReplayAll()
267    self.select_thread.add_socket(s, callback)
268    self.select_thread._select()
269    self.mox.VerifyAll()
270
271  @unittest.skipUnless(wsgi_server._HAS_POLL, 'requires select.poll')
272  def test_select_with_poll(self):
273    s = self._MockSocket()
274    callback = self.mox.CreateMockAnything()
275    poll = self.mox.CreateMockAnything()
276
277    select.poll().AndReturn(poll)
278    poll.register(s.fileno(), select.POLLIN)
279    poll.poll(1000).AndReturn([(s.fileno(), select.POLLIN)])
280
281    callback()
282    self.mox.ReplayAll()
283    self.select_thread.add_socket(s, callback)
284    self.select_thread._select()
285    self.mox.VerifyAll()
286
287  def test_select_not_ready_no_poll(self):
288    wsgi_server._HAS_POLL = False
289    s = self._MockSocket()
290    callback = self.mox.CreateMockAnything()
291    select.select(frozenset([s.fileno()]), [], [], 1).AndReturn(([], [], []))
292    self.mox.ReplayAll()
293    self.select_thread.add_socket(s, callback)
294    self.select_thread._select()
295    self.mox.VerifyAll()
296
297  @unittest.skipUnless(wsgi_server._HAS_POLL, 'requires select.poll')
298  def test_select_not_ready_with_poll(self):
299    s = self._MockSocket()
300    callback = self.mox.CreateMockAnything()
301    poll = self.mox.CreateMockAnything()
302
303    select.poll().AndReturn(poll)
304    poll.register(s.fileno(), select.POLLIN)
305    poll.poll(1000).AndReturn([])
306
307    self.mox.ReplayAll()
308    self.select_thread.add_socket(s, callback)
309    self.select_thread._select()
310    self.mox.VerifyAll()
311
312
313class WsgiServerStartupTest(unittest.TestCase):
314
315  def setUp(self):
316    self.mox = mox.Mox()
317    self.server = wsgi_server.WsgiServer(('localhost', 123), None)
318
319  def tearDown(self):
320    self.mox.UnsetStubs()
321
322  def test_start_some_fail_to_bind(self):
323    failing_server = self.mox.CreateMock(
324        wsgi_server._SingleAddressWsgiServer)
325    starting_server = self.mox.CreateMock(
326        wsgi_server._SingleAddressWsgiServer)
327    another_starting_server = self.mox.CreateMock(
328        wsgi_server._SingleAddressWsgiServer)
329    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
330    self.mox.StubOutWithMock(socket, 'getaddrinfo')
331    socket.getaddrinfo('localhost', 123, socket.AF_UNSPEC, socket.SOCK_STREAM,
332                       0, socket.AI_PASSIVE).AndReturn(
333                           [(None, None, None, None, ('foo', 'bar', 'baz')),
334                            (None, None, None, None, (1, 2, 3, 4, 5)),
335                            (None, None, None, None, (3, 4))])
336    wsgi_server._SingleAddressWsgiServer(('foo', 'bar'), None).AndReturn(
337        failing_server)
338    wsgi_server._SingleAddressWsgiServer((1, 2), None).AndReturn(
339        starting_server)
340    wsgi_server._SingleAddressWsgiServer((3, 4), None).AndReturn(
341        another_starting_server)
342    starting_server.start()
343    failing_server.start().AndRaise(wsgi_server.BindError)
344    another_starting_server.start()
345
346    self.mox.ReplayAll()
347    self.server.start()
348    self.mox.VerifyAll()
349    self.assertItemsEqual([starting_server, another_starting_server],
350                          self.server._servers)
351
352  def test_start_all_fail_to_bind(self):
353    failing_server = self.mox.CreateMock(
354        wsgi_server._SingleAddressWsgiServer)
355    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
356    self.mox.StubOutWithMock(socket, 'getaddrinfo')
357    socket.getaddrinfo('localhost', 123, socket.AF_UNSPEC, socket.SOCK_STREAM,
358                       0, socket.AI_PASSIVE).AndReturn(
359                           [(None, None, None, None, ('foo', 'bar', 'baz'))])
360    wsgi_server._SingleAddressWsgiServer(('foo', 'bar'), None).AndReturn(
361        failing_server)
362    failing_server.start().AndRaise(wsgi_server.BindError)
363
364    self.mox.ReplayAll()
365    self.assertRaises(wsgi_server.BindError, self.server.start)
366    self.mox.VerifyAll()
367
368  def test_remove_duplicates(self):
369    foo_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
370    foo2_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
371    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
372    self.mox.StubOutWithMock(socket, 'getaddrinfo')
373    socket.getaddrinfo('localhost', 123, socket.AF_UNSPEC, socket.SOCK_STREAM,
374                       0, socket.AI_PASSIVE).AndReturn(
375                           [(0, 0, 0, '', ('127.0.0.1', 123)),
376                            (0, 0, 0, '', ('::1', 123, 0, 0)),
377                            (0, 0, 0, '', ('127.0.0.1', 123))])
378    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 123), None).AndReturn(
379        foo_server)
380    foo_server.start()
381    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
382        foo2_server)
383    foo2_server.start()
384
385    self.mox.ReplayAll()
386    self.server.start()
387    self.mox.VerifyAll()
388
389  def test_quit(self):
390    running_server = self.mox.CreateMock(
391        wsgi_server._SingleAddressWsgiServer)
392    self.server._servers = [running_server]
393    running_server.quit()
394    self.mox.ReplayAll()
395    self.server.quit()
396    self.mox.VerifyAll()
397
398
399class WsgiServerPort0StartupTest(unittest.TestCase):
400
401  def setUp(self):
402    self.mox = mox.Mox()
403    self.server = wsgi_server.WsgiServer(('localhost', 0), None)
404
405  def tearDown(self):
406    self.mox.UnsetStubs()
407
408  def test_basic_behavior(self):
409    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
410    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
411    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
412    self.mox.StubOutWithMock(socket, 'getaddrinfo')
413    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
414                       socket.AI_PASSIVE).AndReturn(
415                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
416                            (None, None, None, None, ('::1', 0, 'baz'))])
417    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
418        inet4_server)
419    inet4_server.start()
420    inet4_server.port = 123
421    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
422        inet6_server)
423    inet6_server.start()
424    self.mox.ReplayAll()
425    self.server.start()
426    self.mox.VerifyAll()
427    self.assertItemsEqual([inet4_server, inet6_server],
428                          self.server._servers)
429
430  def test_retry_eaddrinuse(self):
431    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
432    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
433    inet4_server_retry = self.mox.CreateMock(
434        wsgi_server._SingleAddressWsgiServer)
435    inet6_server_retry = self.mox.CreateMock(
436        wsgi_server._SingleAddressWsgiServer)
437    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
438    self.mox.StubOutWithMock(socket, 'getaddrinfo')
439    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
440                       socket.AI_PASSIVE).AndReturn(
441                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
442                            (None, None, None, None, ('::1', 0, 'baz'))])
443    # First try
444    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
445        inet4_server)
446    inet4_server.start()
447    inet4_server.port = 123
448    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
449        inet6_server)
450    inet6_server.start().AndRaise(
451        wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
452    inet4_server.quit()
453    # Retry
454    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
455        inet4_server_retry)
456    inet4_server_retry.start()
457    inet4_server_retry.port = 456
458    wsgi_server._SingleAddressWsgiServer(('::1', 456), None).AndReturn(
459        inet6_server_retry)
460    inet6_server_retry.start()
461    self.mox.ReplayAll()
462    self.server.start()
463    self.mox.VerifyAll()
464    self.assertItemsEqual([inet4_server_retry, inet6_server_retry],
465                          self.server._servers)
466
467  def test_retry_limited(self):
468    inet4_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
469                     for _ in range(wsgi_server._PORT_0_RETRIES)]
470    inet6_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
471                     for _ in range(wsgi_server._PORT_0_RETRIES)]
472    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
473    self.mox.StubOutWithMock(socket, 'getaddrinfo')
474    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
475                       socket.AI_PASSIVE).AndReturn(
476                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
477                            (None, None, None, None, ('::1', 0, 'baz'))])
478    for offset, (inet4_server, inet6_server) in enumerate(zip(
479        inet4_servers, inet6_servers)):
480      wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
481          inet4_server)
482      inet4_server.start()
483      inet4_server.port = offset + 1
484      wsgi_server._SingleAddressWsgiServer(('::1', offset + 1), None).AndReturn(
485          inet6_server)
486      inet6_server.start().AndRaise(
487          wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
488      inet4_server.quit()
489    self.mox.ReplayAll()
490    self.assertRaises(wsgi_server.BindError, self.server.start)
491    self.mox.VerifyAll()
492
493  def test_ignore_other_errors(self):
494    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
495    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
496    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
497    self.mox.StubOutWithMock(socket, 'getaddrinfo')
498    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
499                       socket.AI_PASSIVE).AndReturn(
500                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
501                            (None, None, None, None, ('::1', 0, 'baz'))])
502    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
503        inet4_server)
504    inet4_server.start()
505    inet4_server.port = 123
506    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
507        inet6_server)
508    inet6_server.start().AndRaise(
509        wsgi_server.BindError('message', (errno.ENOPROTOOPT, 'no protocol')))
510    self.mox.ReplayAll()
511    self.server.start()
512    self.mox.VerifyAll()
513    self.assertItemsEqual([inet4_server],
514                          self.server._servers)
515
516
517class _SingleAddressWsgiServerStartupTest(unittest.TestCase):
518
519  def setUp(self):
520    self.mox = mox.Mox()
521    self.server = wsgi_server._SingleAddressWsgiServer(('localhost', 0), None)
522
523  def tearDown(self):
524    self.mox.UnsetStubs()
525
526  def test_start_port_in_use(self):
527    self.mox.StubOutWithMock(socket, 'getaddrinfo')
528    self.mox.StubOutWithMock(self.server, 'bind')
529    af = object()
530    socktype = object()
531    proto = object()
532    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
533                       socket.AI_PASSIVE).AndReturn(
534                           [(af, socktype, proto, None, None)])
535    self.server.bind(af, socktype, proto).AndRaise(socket.error)
536    self.mox.ReplayAll()
537    self.assertRaises(wsgi_server.BindError, self.server.start)
538    self.mox.VerifyAll()
539
540  def test_start(self):
541    # Ensure no CherryPy thread pools are started.
542    self.mox.StubOutWithMock(wsgiserver.ThreadPool, 'start')
543    self.mox.StubOutWithMock(wsgi_server._SELECT_THREAD, 'add_socket')
544    wsgi_server._SELECT_THREAD.add_socket(mox.IsA(socket.socket),
545                                          self.server.tick)
546    self.mox.ReplayAll()
547    self.server.start()
548    self.mox.VerifyAll()
549
550  def test_quit(self):
551    self.mox.StubOutWithMock(wsgi_server._SELECT_THREAD, 'remove_socket')
552    self.server.socket = object()
553    self.server.requests = self.mox.CreateMock(
554        wsgi_server._SharedCherryPyThreadPool)
555    wsgi_server._SELECT_THREAD.remove_socket(self.server.socket)
556    self.server.requests.stop(timeout=1)
557    self.mox.ReplayAll()
558    self.server.quit()
559    self.mox.VerifyAll()
560
561if __name__ == '__main__':
562  unittest.main()
563
Full Screen

index.js

Source: index.js Github

copy
1var app = {
2    init: function() {
3        if(localStorage.getItem("server")) {
4            app.setup_login();
5        } else {
6			app.show_server();
7        }
8        app.bind_events();
9		common.handle_external_links();
10    },
11    bind_events: function() {
12		app.bind_select_server();
13		app.bind_login();
14		app.bind_change_server();
15    },
16	bind_login: function() {
17		$(".btn-login").on("click", function() {
18
19			$me = $(this);
20			$me.prop("disabled", true);
21			$.ajax({
22				method: "POST",
23				url: localStorage.server + "/api/method/login",
24				data: {
25					usr: $("#usr").val(),
26					pwd: $("#pwd").val(),
27					device: "mobile"
28				}
29			}).success(function(data, status, xhr) {
30				localStorage.user = $("#usr").val();
31				var cookie_source = xhr.getResponseHeader('Set-Cookie');
32				localStorage.session_id = common.get_cookie("sid", cookie_source);
33				app.start_desk();
34			}).error(function() {
35				common.msgprint("Invalid Login");
36				$me.prop("disabled", false);
37			}).always(function() {
38				// $("#usr").val("");
39				// $("#pwd").val("");
40			});
41			return false;
42		});
43	},
44	bind_select_server: function() {
45        $(".btn-select-server").on("click", function() {
46            // check if erpnext / frappe server
47
48            $(this).prop("disabled", true);
49
50            var server = $("#server").val();
51            if(!server) {
52                app.retry_server();
53                return false;
54            }
55
56
57            if(server.substr(0, 7)!== "http://" && server.substr(0, 8)!== "https://") {
58                // http / https not provided
59                // try https
60                app.verify_server("https://" + server, select,
61                    function() {
62                        // try http
63                        app.verify_server("http://" + server, select, app.retry_server);
64                    }
65                );
66            } else {
67                app.verify_server(server, select, app.retry_server);
68            }
69
70            return false;
71        });
72		$(".recent-server-list").on("click", "a", function() {
73			$this = $(this);
74			$this.prop("disabled", true);
75			app.verify_server($this.text(), select, app.retry_server);
76		});
77
78		function select(server) {
79			localStorage.server = app.strip_trailing_slash(server);
80			app.save_server_in_recent(localStorage.server);
81			app.setup_login();
82		}
83	},
84    verify_server: function(server, valid, invalid) {
85        $.ajax({
86    			method: "GET",
87    			url: server + "/api/method/version",
88    		})
89            .success(function(data) {
90                if(data.message) {
91                    valid(server);
92                } else {
93                    invalid();
94                };
95            })
96            .fail(function() { invalid() })
97            .error(function() { invalid() });
98    },
99	bind_change_server: function() {
100		$(".change-server").on("click", function() {
101			localStorage.server = "";
102			app.show_server(true);
103			return false;
104		});
105	},
106    strip_trailing_slash: function(server) {
107        return server.replace(/(http[s]?:\/\/[^\/]*)(.*)/, "$1");
108    },
109	save_server_in_recent: function(server) {
110		server = server.toLowerCase().trim();
111
112		var recent_servers = localStorage.recent_servers ?
113			JSON.parse(localStorage.recent_servers) : [];
114
115		var index = recent_servers.indexOf(server);
116		if(index !== -1) {
117			recent_servers.splice(index, 1);
118		}
119		recent_servers.push(server);
120
121		localStorage.setItem("recent_servers", JSON.stringify(recent_servers));
122	},
123    setup_login: function() {
124		if(localStorage.server && localStorage.session_id) {
125			app.if_session_valid(app.start_desk, app.show_login);
126		} else {
127			app.show_login();
128		}
129    },
130	show_login: function() {
131		$(".app").removeClass("hide");
132        $(".div-select-server").addClass("hide");
133        $(".div-login").removeClass("hide");
134		$(".current-server").text(localStorage.server);
135	},
136	if_session_valid: function(if_yes, if_no) {
137		app.set_sid_cookie();
138		$.ajax({
139			method: "GET",
140			crossDomain: true,
141			url: localStorage.server + "/api/method/ping",
142		}).success(function(data) {
143			if(data.message === "pong") {
144				if_yes();
145			} else {
146				if_no();
147			}
148		}).error(function() {
149			if_no();
150		});
151	},
152	set_sid_cookie: function() {
153		document.cookie = "sid=" + localStorage.session_id +
154			"; expires=Fri, 31 Dec 9999 23:59:59 GMT";
155	},
156	start_desk: function() {
157		window.location.href = "desk.html";
158	},
159    retry_server: function() {
160        common.msgprint("Does not seem like a valid server address. Please try again.");
161		app.show_server();
162    },
163	show_server: function(clear) {
164		$(".app").removeClass("hide");
165        $(".btn-select-server").prop("disabled", false);
166        $(".div-select-server").removeClass("hide");
167        if(clear) {
168            $(".div-login").addClass("hide");
169        }
170		app.show_recent_servers();
171	},
172	show_recent_servers: function() {
173		if(localStorage.recent_servers) {
174			var recent_servers = JSON.parse(localStorage.recent_servers);
175			recent_servers.reverse().splice(2);
176
177			var html = "<li class='text-muted'>Recent:</li>"
178			$.each(recent_servers, function(i, server) {
179				html += '<li><a>'+server+'</a></li>';
180			});
181			$('.recent-server-list').empty().append(html).removeClass('hide');
182		}
183	}
184};
185
186document.addEventListener('deviceready', app.init, false);
187
Full Screen

browser.js

Source: browser.js Github

copy
1var __indexOf = [].indexOf || function (item) {
2    for (var i = 0, l = this.length; i < l; i++) {
3      if (i in this && this[i] === item) return i;
4    }
5    return -1;
6  };
7
8var xpathStringLiteral = function (s) {
9  if (s.indexOf('"') === -1)
10    return '"' + s + '"';
11  if (s.indexOf("'") === -1)
12    return "'" + s + "'";
13  return 'concat("' + s.replace(/"/g, '",\'"\',"') + '")';
14};
15
16Poltergeist.Browser = (function () {
17  /**
18   * Creates the "browser" inside phantomjs
19   * @param owner
20   * @param width
21   * @param height
22   * @constructor
23   */
24  function Browser(owner, width, height) {
25    this.owner = owner;
26    this.width = width || 1024;
27    this.height = height || 768;
28    this.pages = [];
29    this.js_errors = true;
30    this._debug = false;
31    this._counter = 0;
32    this.resetPage();
33  }
34
35  /**
36   * Resets the browser to a clean slate
37   * @return {Function}
38   */
39  Browser.prototype.resetPage = function () {
40    var _ref;
41    var self = this;
42
43    _ref = [0, []];
44    this._counter = _ref[0];
45    this.pages = _ref[1];
46
47    if (this.page != null) {
48      if (!this.page.closed) {
49        if (this.page.currentUrl() !== 'about:blank') {
50          this.page.clearLocalStorage();
51        }
52        this.page.release();
53      }
54      phantom.clearCookies();
55    }
56
57    this.page = this.currentPage = new Poltergeist.WebPage;
58    this.page.setViewportSize({
59      width: this.width,
60      height: this.height
61    });
62    this.page.handle = "" + (this._counter++);
63    this.pages.push(this.page);
64
65    return this.page.onPageCreated = function (newPage) {
66      var page;
67      page = new Poltergeist.WebPage(newPage);
68      page.handle = "" + (self._counter++);
69      return self.pages.push(page);
70    };
71  };
72
73  /**
74   * Given a page handle id, tries to get it from the browser page list
75   * @param handle
76   * @return {WebPage}
77   */
78  Browser.prototype.getPageByHandle = function (handle) {
79    var filteredPages;
80
81    //TODO: perhaps we should throw a PageNotFoundByHandle or something like that..
82    if (handle === null || typeof handle == "undefined") {
83      return null;
84    }
85
86    filteredPages = this.pages.filter(function (p) {
87      return !p.closed && p.handle === handle;
88    });
89
90    if (filteredPages.length === 1) {
91      return filteredPages[0];
92    }
93
94    return null;
95  };
96
97  /**
98   * Sends a debug message to the console
99   * @param message
100   * @return {*}
101   */
102  Browser.prototype.debug = function (message) {
103    if (this._debug) {
104      return console.log("poltergeist [" + (new Date().getTime()) + "] " + message);
105    }
106  };
107
108  /**
109   * Given a page_id and id, gets if possible the node in such page
110   * @param page_id
111   * @param id
112   * @return {Poltergeist.Node}
113   */
114  Browser.prototype.node = function (page_id, id) {
115    if (this.currentPage.id === page_id) {
116      return this.currentPage.get(id);
117    } else {
118      throw new Poltergeist.ObsoleteNode;
119    }
120  };
121
122  /**
123   * Returns the frameUrl related to the frame given by name
124   * @param frame_name
125   * @return {*}
126   */
127  Browser.prototype.frameUrl = function (frame_name) {
128    return this.currentPage.frameUrl(frame_name);
129  };
130
131  /**
132   * This method defines the rectangular area of the web page to be rasterized when render is invoked.
133   * If no clipping rectangle is set, render will process the entire web page.
134   * @param full
135   * @param selector
136   * @return {*}
137   */
138  Browser.prototype.set_clip_rect = function (full, selector) {
139    var dimensions, clipDocument, rect, clipViewport;
140
141    dimensions = this.currentPage.validatedDimensions();
142    clipDocument = dimensions.document;
143    clipViewport = dimensions.viewport;
144
145    if (full) {
146      rect = {
147        left: 0,
148        top: 0,
149        width: clipDocument.width,
150        height: clipDocument.height
151      };
152    } else {
153      if (selector != null) {
154        rect = this.currentPage.elementBounds(selector);
155      } else {
156        rect = {
157          left: 0,
158          top: 0,
159          width: clipViewport.width,
160          height: clipViewport.height
161        };
162      }
163    }
164
165    this.currentPage.setClipRect(rect);
166    return dimensions;
167  };
168
169  /**
170   * Kill the browser, i.e kill phantomjs current process
171   * @return {int}
172   */
173  Browser.prototype.exit = function () {
174    return phantom.exit(0);
175  };
176
177  /**
178   * Do nothing
179   */
180  Browser.prototype.noop = function () {
181  };
182
183  /**
184   * Throws a new Object error
185   */
186  Browser.prototype.browser_error = function () {
187    throw new Error('zomg');
188  };
189
190  /**
191   *  Visits a page and load its content
192   * @param serverResponse
193   * @param url
194   * @return {*}
195   */
196  Browser.prototype.visit = function (serverResponse, url) {
197    var prevUrl;
198    var self = this;
199    this.currentPage.state = 'loading';
200    prevUrl = this.currentPage.source === null ? 'about:blank' : this.currentPage.currentUrl();
201    this.currentPage.open(url);
202    if (/#/.test(url) && prevUrl.split('#')[0] === url.split('#')[0]) {
203      this.currentPage.state = 'default';
204      return this.serverSendResponse({
205        status: 'success'
206      }, serverResponse);
207    } else {
208      return this.currentPage.waitState('default', function () {
209        if (self.currentPage.statusCode === null && self.currentPage.status === 'fail') {
210          return self.owner.serverSendError(new Poltergeist.StatusFailError, serverResponse);
211        } else {
212          return self.serverSendResponse({
213            status: self.currentPage.status
214          }, serverResponse);
215        }
216      });
217    }
218  };
219
220  /**
221   *  Puts the control of the browser inside the IFRAME given by name
222   * @param serverResponse
223   * @param name
224   * @param timeout
225   * @return {*}
226   */
227  Browser.prototype.push_frame = function (serverResponse, name, timeout) {
228    var _ref;
229    var self = this;
230
231    if (timeout == null) {
232      timeout = new Date().getTime() + 2000;
233    }
234
235    //TODO: WTF, else if after a if with return COMMON
236    if (_ref = this.frameUrl(name), __indexOf.call(this.currentPage.blockedUrls(), _ref) >= 0) {
237      return this.serverSendResponse(true, serverResponse);
238    } else if (this.currentPage.pushFrame(name)) {
239      if (this.currentPage.currentUrl() === 'about:blank') {
240        this.currentPage.state = 'awaiting_frame_load';
241        return this.currentPage.waitState('default', function () {
242          return self.serverSendResponse(true, serverResponse);
243        });
244      } else {
245        return this.serverSendResponse(true, serverResponse);
246      }
247    } else {
248      if (new Date().getTime() < timeout) {
249        return setTimeout((function () {
250          return self.push_frame(serverResponse, name, timeout);
251        }), 50);
252      } else {
253        return this.owner.serverSendError(new Poltergeist.FrameNotFound(name), serverResponse);
254      }
255    }
256  };
257
258  /**
259   *  Injects a javascript into the current page
260   * @param serverResponse
261   * @param extension
262   * @return {*}
263   */
264  Browser.prototype.add_extension = function (serverResponse, extension) {
265    //TODO: error control when the injection was not possible
266    this.currentPage.injectExtension(extension);
267    return this.serverSendResponse('success', serverResponse);
268  };
269
270  /**
271   *  Returns the url we are currently in
272   * @param serverResponse
273   * @return {*}
274   */
275  Browser.prototype.current_url = function (serverResponse) {
276    return this.serverSendResponse(this.currentPage.currentUrl(), serverResponse);
277  };
278
279  /**
280   *  Returns the current page window name
281   * @param serverResponse
282   * @returns {*}
283   */
284  Browser.prototype.window_name = function (serverResponse) {
285    return this.serverSendResponse(this.currentPage.windowName(), serverResponse);
286  };
287
288  /**
289   *  Returns the status code associated to the page
290   * @param serverResponse
291   * @return {*}
292   */
293  Browser.prototype.status_code = function (serverResponse) {
294    if (this.currentPage.statusCode === undefined || this.currentPage.statusCode === null) {
295      return this.owner.serverSendError(new Poltergeist.StatusFailError("status_code_error"), serverResponse);
296    }
297    return this.serverSendResponse(this.currentPage.statusCode, serverResponse);
298  };
299
300  /**
301   *  Returns the source code of the active frame, useful for when inside an IFRAME
302   * @param serverResponse
303   * @return {*}
304   */
305  Browser.prototype.body = function (serverResponse) {
306    return this.serverSendResponse(this.currentPage.content(), serverResponse);
307  };
308
309  /**
310   * Returns the source code of the page all the html
311   * @param serverResponse
312   * @return {*}
313   */
314  Browser.prototype.source = function (serverResponse) {
315    return this.serverSendResponse(this.currentPage.source, serverResponse);
316  };
317
318  /**
319   * Returns the current page title
320   * @param serverResponse
321   * @return {*}
322   */
323  Browser.prototype.title = function (serverResponse) {
324    return this.serverSendResponse(this.currentPage.title(), serverResponse);
325  };
326
327  /**
328   *  Finds the elements that match a method of selection and a selector
329   * @param serverResponse
330   * @param method
331   * @param selector
332   * @return {*}
333   */
334  Browser.prototype.find = function (serverResponse, method, selector) {
335    return this.serverSendResponse({
336      page_id: this.currentPage.id,
337      ids: this.currentPage.find(method, selector)
338    }, serverResponse);
339  };
340
341  /**
342   * Find elements within a given element
343   * @param serverResponse
344   * @param page_id
345   * @param id
346   * @param method
347   * @param selector
348   * @return {*}
349   */
350  Browser.prototype.find_within = function (serverResponse, page_id, id, method, selector) {
351    return this.serverSendResponse(this.node(page_id, id).find(method, selector), serverResponse);
352  };
353
354  /**
355   * Returns ALL the text, visible and not visible from the given element
356   * @param serverResponse
357   * @param page_id
358   * @param id
359   * @return {*}
360   */
361  Browser.prototype.all_text = function (serverResponse, page_id, id) {
362    return this.serverSendResponse(this.node(page_id, id).allText(), serverResponse);
363  };
364
365  /**
366   * Returns the inner or outer html of a given id
367   * @param serverResponse
368   * @param page_id
369   * @param id
370   * @param type
371   * @returns Object
372   */
373  Browser.prototype.all_html = function (serverResponse, page_id, id, type) {
374    return this.serverSendResponse(this.node(page_id, id).allHTML(type), serverResponse);
375  };
376
377  /**
378   *  Returns only the visible text in a given element
379   * @param serverResponse
380   * @param page_id
381   * @param id
382   * @return {*}
383   */
384  Browser.prototype.visible_text = function (serverResponse, page_id, id) {
385    return this.serverSendResponse(this.node(page_id, id).visibleText(), serverResponse);
386  };
387
388  /**
389   * Deletes the text in a given element leaving it empty
390   * @param serverResponse
391   * @param page_id
392   * @param id
393   * @return {*}
394   */
395  Browser.prototype.delete_text = function (serverResponse, page_id, id) {
396    return this.serverSendResponse(this.node(page_id, id).deleteText(), serverResponse);
397  };
398
399  /**
400   *  Gets the value of a given attribute in an element
401   * @param serverResponse
402   * @param page_id
403   * @param id
404   * @param name
405   * @return {*}
406   */
407  Browser.prototype.attribute = function (serverResponse, page_id, id, name) {
408    return this.serverSendResponse(this.node(page_id, id).getAttribute(name), serverResponse);
409  };
410
411  /**
412   *  Allows the possibility to set an attribute on a given element
413   * @param serverResponse
414   * @param page_id
415   * @param id
416   * @param name
417   * @param value
418   * @returns {*}
419   */
420  Browser.prototype.set_attribute = function (serverResponse, page_id, id, name, value) {
421    return this.serverSendResponse(this.node(page_id, id).setAttribute(name, value), serverResponse);
422  };
423
424  /**
425   *  Allows the possibility to remove an attribute on a given element
426   * @param serverResponse
427   * @param page_id
428   * @param id
429   * @param name
430   * @returns {*}
431   */
432  Browser.prototype.remove_attribute = function (serverResponse, page_id, id, name) {
433    return this.serverSendResponse(this.node(page_id, id).removeAttribute(name), serverResponse);
434  };
435
436  /**
437   * Returns all the attributes of a given element
438   * @param serverResponse
439   * @param page_id
440   * @param id
441   * @param name
442   * @return {*}
443   */
444  Browser.prototype.attributes = function (serverResponse, page_id, id, name) {
445    return this.serverSendResponse(this.node(page_id, id).getAttributes(), serverResponse);
446  };
447
448  /**
449   *  Returns all the way to the document level the parents of a given element
450   * @param serverResponse
451   * @param page_id
452   * @param id
453   * @return {*}
454   */
455  Browser.prototype.parents = function (serverResponse, page_id, id) {
456    return this.serverSendResponse(this.node(page_id, id).parentIds(), serverResponse);
457  };
458
459  /**
460   * Returns the element.value of an element given by its page and id
461   * @param serverResponse
462   * @param page_id
463   * @param id
464   * @return {*}
465   */
466  Browser.prototype.value = function (serverResponse, page_id, id) {
467    return this.serverSendResponse(this.node(page_id, id).value(), serverResponse);
468  };
469
470  /**
471   *  Sets the element.value of an element by the given value
472   * @param serverResponse
473   * @param page_id
474   * @param id
475   * @param value
476   * @return {*}
477   */
478  Browser.prototype.set = function (serverResponse, page_id, id, value) {
479    this.node(page_id, id).set(value);
480    return this.serverSendResponse(true, serverResponse);
481  };
482
483  /**
484   *  Uploads a file to an input file element
485   * @param serverResponse
486   * @param page_id
487   * @param id
488   * @param file_path
489   * @return {*}
490   */
491  Browser.prototype.select_file = function (serverResponse, page_id, id, file_path) {
492    var node = this.node(page_id, id);
493
494    this.currentPage.beforeUpload(node.id);
495    this.currentPage.uploadFile('[_poltergeist_selected]', file_path);
496    this.currentPage.afterUpload(node.id);
497
498    return this.serverSendResponse(true, serverResponse);
499  };
500
501  /**
502   * Sets a value to the selected element (to be used in select elements)
503   * @param serverResponse
504   * @param page_id
505   * @param id
506   * @param value
507   * @return {*}
508   */
509  Browser.prototype.select = function (serverResponse, page_id, id, value) {
510    return this.serverSendResponse(this.node(page_id, id).select(value), serverResponse);
511  };
512
513  /**
514   *  Selects an option with the given value
515   * @param serverResponse
516   * @param page_id
517   * @param id
518   * @param value
519   * @param multiple
520   * @return {*}
521   */
522  Browser.prototype.select_option = function (serverResponse, page_id, id, value, multiple) {
523    return this.serverSendResponse(this.node(page_id, id).select_option(value, multiple), serverResponse);
524  };
525
526  /**
527   *
528   * @param serverResponse
529   * @param page_id
530   * @param id
531   * @return {*}
532   */
533  Browser.prototype.tag_name = function (serverResponse, page_id, id) {
534    return this.serverSendResponse(this.node(page_id, id).tagName(), serverResponse);
535  };
536
537
538  /**
539   * Tells if an element is visible or not
540   * @param serverResponse
541   * @param page_id
542   * @param id
543   * @return {*}
544   */
545  Browser.prototype.visible = function (serverResponse, page_id, id) {
546    return this.serverSendResponse(this.node(page_id, id).isVisible(), serverResponse);
547  };
548
549  /**
550   *  Tells if an element is disabled
551   * @param serverResponse
552   * @param page_id
553   * @param id
554   * @return {*}
555   */
556  Browser.prototype.disabled = function (serverResponse, page_id, id) {
557    return this.serverSendResponse(this.node(page_id, id).isDisabled(), serverResponse);
558  };
559
560  /**
561   *  Evaluates a javascript and returns the outcome to the client
562   *  This will be JSON response so your script better be returning objects that can be used
563   *  in JSON.stringify
564   * @param serverResponse
565   * @param script
566   * @return {*}
567   */
568  Browser.prototype.evaluate = function (serverResponse, script) {
569    return this.serverSendResponse(this.currentPage.evaluate("function() { return " + script + " }"), serverResponse);
570  };
571
572  /**
573   *  Executes a javascript and goes back to the client with true if there were no errors
574   * @param serverResponse
575   * @param script
576   * @return {*}
577   */
578  Browser.prototype.execute = function (serverResponse, script) {
579    this.currentPage.execute("function() { " + script + " }");
580    return this.serverSendResponse(true, serverResponse);
581  };
582
583  /**
584   * If inside a frame then we will go back to the parent
585   * Not defined behaviour if you pop and are not inside an iframe
586   * @param serverResponse
587   * @return {*}
588   */
589  Browser.prototype.pop_frame = function (serverResponse) {
590    return this.serverSendResponse(this.currentPage.popFrame(), serverResponse);
591  };
592
593  /**
594   * Gets the window handle id by a given window name
595   * @param serverResponse
596   * @param name
597   * @return {*}
598   */
599  Browser.prototype.window_handle = function (serverResponse, name) {
600    var handle, pageByWindowName;
601
602    if (name === null || typeof name == "undefined" || name.length === 0) {
603      return this.serverSendResponse(this.currentPage.handle, serverResponse);
604    }
605
606    handle = null;
607
608    //Lets search the handle by the given window name
609    var filteredPages = this.pages.filter(function (p) {
610      return !p.closed && p.windowName() === name;
611    });
612
613    //A bit of error control is always good
614    if (Array.isArray(filteredPages) && filteredPages.length >= 1) {
615      pageByWindowName = filteredPages[0];
616    } else {
617      pageByWindowName = null;
618    }
619
620    if (pageByWindowName !== null && typeof pageByWindowName != "undefined") {
621      handle = pageByWindowName.handle;
622    }
623
624    return this.serverSendResponse(handle, serverResponse);
625  };
626
627  /**
628   * Returns all the window handles of opened windows
629   * @param serverResponse
630   * @return {*}
631   */
632  Browser.prototype.window_handles = function (serverResponse) {
633    var handles, filteredPages;
634
635    filteredPages = this.pages.filter(function (p) {
636      return !p.closed;
637    });
638
639    if (filteredPages.length > 0) {
640      handles = filteredPages.map(function (p) {
641        return p.handle;
642      });
643      if (handles.length === 0) {
644        handles = null;
645      }
646    } else {
647      handles = null;
648    }
649
650    return this.serverSendResponse(handles, serverResponse);
651  };
652
653  /**
654   *  Tries to switch to a window given by the handle id
655   * @param serverResponse
656   * @param handle
657   * @return {*}
658   */
659  Browser.prototype.switch_to_window = function (serverResponse, handle) {
660    var page;
661    var self = this;
662
663    page = this.getPageByHandle(handle);
664    if (page === null || typeof page == "undefined") {
665      throw new Poltergeist.NoSuchWindowError;
666    }
667
668    if (page !== this.currentPage) {
669      return page.waitState('default', function () {
670        self.currentPage = page;
671        return self.serverSendResponse(true, serverResponse);
672      });
673    }
674
675    return this.serverSendResponse(true, serverResponse);
676  };
677
678  /**
679   * Opens a new window where we can do stuff
680   * @param serverResponse
681   * @return {*}
682   */
683  Browser.prototype.open_new_window = function (serverResponse) {
684    return this.execute(serverResponse, 'window.open()');
685  };
686
687  /**
688   * Closes the window given by handle name if possible
689   * @param serverResponse
690   * @param handle
691   * @return {*}
692   */
693  Browser.prototype.close_window = function (serverResponse, handle) {
694    var page;
695
696    page = this.getPageByHandle(handle);
697    if (page === null || typeof  page == "undefined") {
698      //TODO: should we throw error since we actually could not find the window?
699      return this.serverSendResponse(false, serverResponse);
700    }
701
702    //TODO: we have to add some control here to actually asses that the release has been done
703    page.release();
704    return this.serverSendResponse(true, serverResponse);
705  };
706
707  /**
708   * Generic mouse event on an element
709   * @param serverResponse
710   * @param page_id
711   * @param id
712   * @param name
713   * @return {number}
714   */
715  Browser.prototype.mouse_event = function (serverResponse, page_id, id, name) {
716    var node;
717    var self = this;
718    node = this.node(page_id, id);
719    this.currentPage.state = 'mouse_event';
720    this.last_mouse_event = node.mouseEvent(name);
721    return setTimeout(function () {
722      if (self.currentPage.state === 'mouse_event') {
723        self.currentPage.state = 'default';
724        return self.serverSendResponse({
725          position: self.last_mouse_event
726        }, serverResponse);
727      } else {
728        return self.currentPage.waitState('default', function () {
729          return self.serverSendResponse({
730            position: self.last_mouse_event
731          }, serverResponse);
732        });
733      }
734    }, 5);
735  };
736
737  /**
738   * Simple click on the element
739   * @param serverResponse
740   * @param page_id
741   * @param id
742   * @return {*}
743   */
744  Browser.prototype.click = function (serverResponse, page_id, id) {
745    return this.mouse_event(serverResponse, page_id, id, 'click');
746  };
747
748  /**
749   * Right click on the element
750   * @param serverResponse
751   * @param page_id
752   * @param id
753   * @return {*}
754   */
755  Browser.prototype.right_click = function (serverResponse, page_id, id) {
756    return this.mouse_event(serverResponse, page_id, id, 'rightclick');
757  };
758
759  /**
760   *  Double click on the element given by page and id
761   * @param serverResponse
762   * @param page_id
763   * @param id
764   * @return {*}
765   */
766  Browser.prototype.double_click = function (serverResponse, page_id, id) {
767    return this.mouse_event(serverResponse, page_id, id, 'doubleclick');
768  };
769
770  /**
771   * Executes a mousemove event on the page and given element
772   * @param serverResponse
773   * @param page_id
774   * @param id
775   * @return {*}
776   */
777  Browser.prototype.hover = function (serverResponse, page_id, id) {
778    return this.mouse_event(serverResponse, page_id, id, 'mousemove');
779  };
780
781  /**
782   * Triggers a mouse click event on the given coordinates
783   * @param serverResponse
784   * @param x
785   * @param y
786   * @return {*}
787   */
788  Browser.prototype.click_coordinates = function (serverResponse, x, y) {
789    var response;
790
791    this.currentPage.sendEvent('click', x, y);
792    response = {
793      click: {
794        x: x,
795        y: y
796      }
797    };
798
799    return this.serverSendResponse(response, serverResponse);
800  };
801
802  /**
803   *  Drags one element into another, useful for nice javascript thingies
804   * @param serverResponse
805   * @param page_id
806   * @param id
807   * @param other_id
808   * @return {*}
809   */
810  Browser.prototype.drag = function (serverResponse, page_id, id, other_id) {
811    this.node(page_id, id).dragTo(this.node(page_id, other_id));
812    return this.serverSendResponse(true, serverResponse);
813  };
814
815  /**
816   * Triggers an event on the given page and element
817   * @param serverResponse
818   * @param page_id
819   * @param id
820   * @param event
821   * @return {*}
822   */
823  Browser.prototype.trigger = function (serverResponse, page_id, id, event) {
824    this.node(page_id, id).trigger(event);
825    return this.serverSendResponse(event, serverResponse);
826  };
827
828  /**
829   * Checks if two elements are equal on a dom level
830   * @param serverResponse
831   * @param page_id
832   * @param id
833   * @param other_id
834   * @return {*}
835   */
836  Browser.prototype.equals = function (serverResponse, page_id, id, other_id) {
837    return this.serverSendResponse(this.node(page_id, id).isEqual(this.node(page_id, other_id)), serverResponse);
838  };
839
840  /**
841   * Resets the current page to a clean slate
842   * @param serverResponse
843   * @return {*}
844   */
845  Browser.prototype.reset = function (serverResponse) {
846    this.resetPage();
847    return this.serverSendResponse(true, serverResponse);
848  };
849
850  /**
851   * Scrolls to a position given by the left, top coordinates
852   * @param serverResponse
853   * @param left
854   * @param top
855   * @return {*}
856   */
857  Browser.prototype.scroll_to = function (serverResponse, left, top) {
858    this.currentPage.setScrollPosition({
859      left: left,
860      top: top
861    });
862    return this.serverSendResponse(true, serverResponse);
863  };
864
865  /**
866   * Sends keys to an element simulating as closest as possible what a user would do
867   * when typing
868   * @param serverResponse
869   * @param page_id
870   * @param id
871   * @param keys
872   * @return {*}
873   */
874  Browser.prototype.send_keys = function (serverResponse, page_id, id, keys) {
875    var key, sequence, target, _i, _len;
876    target = this.node(page_id, id);
877    if (!target.containsSelection()) {
878      target.mouseEvent('click');
879    }
880    for (_i = 0, _len = keys.length; _i < _len; _i++) {
881      sequence = keys[_i];
882      key = sequence.key != null ? this.currentPage.keyCode(sequence.key) : sequence;
883      this.currentPage.sendEvent('keypress', key);
884    }
885    return this.serverSendResponse(true, serverResponse);
886  };
887
888  /**
889   * Sends a native phantomjs key event to element
890   * @param serverResponse
891   * @param page_id
892   * @param id
893   * @param keyEvent
894   * @param key
895   * @param modifier
896   */
897  Browser.prototype.key_event = function (serverResponse, page_id, id, keyEvent, key, modifier) {
898    var keyEventModifierMap;
899    var keyEventModifier;
900    var target;
901
902    keyEventModifierMap = {
903      'none': 0x0,
904      'shift': 0x02000000,
905      'ctrl': 0x04000000,
906      'alt': 0x08000000,
907      'meta': 0x10000000
908    };
909    keyEventModifier = keyEventModifierMap[modifier];
910
911    target = this.node(page_id, id);
912    if (!target.containsSelection()) {
913      target.mouseEvent('click');
914    }
915    target.page.sendEvent(keyEvent, key, null, null, keyEventModifier);
916
917    return this.serverSendResponse(true, serverResponse);
918  };
919
920  /**
921   *  Sends the rendered page in a base64 encoding
922   * @param serverResponse
923   * @param format
924   * @param full
925   * @param selector
926   * @return {*}
927   */
928  Browser.prototype.render_base64 = function (serverResponse, format, full, selector) {
929    var encoded_image;
930    if (selector == null) {
931      selector = null;
932    }
933    this.set_clip_rect(full, selector);
934    encoded_image = this.currentPage.renderBase64(format);
935    return this.serverSendResponse(encoded_image, serverResponse);
936  };
937
938  /**
939   * Renders the current page entirely or a given selection
940   * @param serverResponse
941   * @param path
942   * @param full
943   * @param selector
944   * @return {*}
945   */
946  Browser.prototype.render = function (serverResponse, path, full, selector) {
947    var dimensions;
948    if (selector == null) {
949      selector = null;
950    }
951    dimensions = this.set_clip_rect(full, selector);
952    this.currentPage.setScrollPosition({
953      left: 0,
954      top: 0
955    });
956    this.currentPage.render(path);
957    this.currentPage.setScrollPosition({
958      left: dimensions.left,
959      top: dimensions.top
960    });
961    return this.serverSendResponse(true, serverResponse);
962  };
963
964
965  /**
966   * Sets the paper size, useful when printing to PDF
967   * @param serverResponse
968   * @param size
969   * @return {*}
970   */
971  Browser.prototype.set_paper_size = function (serverResponse, size) {
972    this.currentPage.setPaperSize(size);
973    return this.serverSendResponse(true, serverResponse);
974  };
975
976  /**
977   *  Sets the zoom factor on the current page
978   * @param serverResponse
979   * @param zoom_factor
980   * @return {*}
981   */
982  Browser.prototype.set_zoom_factor = function (serverResponse, zoom_factor) {
983    this.currentPage.setZoomFactor(zoom_factor);
984    return this.serverSendResponse(true, serverResponse);
985  };
986
987  /**
988   * Resizes the browser viewport, useful when testing mobile stuff
989   * @param serverResponse
990   * @param width
991   * @param height
992   * @return {*}
993   */
994  Browser.prototype.resize = function (serverResponse, width, height) {
995    this.currentPage.setViewportSize({
996      width: width,
997      height: height
998    });
999    return this.serverSendResponse(true, serverResponse);
1000  };
1001
1002  /**
1003   * Gets the browser viewport size
1004   * Because PhantomJS is headless (nothing is shown)
1005   * viewportSize effectively simulates the size of the window like in a traditional browser.
1006   * @param serverResponse
1007   * @param handle
1008   * @return {*}
1009   */
1010  Browser.prototype.window_size = function (serverResponse, handle) {
1011    //TODO: add support for window handles
1012    return this.serverSendResponse(this.currentPage.viewportSize(), serverResponse);
1013  };
1014
1015  /**
1016   * Returns the network traffic that the current page has generated
1017   * @param serverResponse
1018   * @return {*}
1019   */
1020  Browser.prototype.network_traffic = function (serverResponse) {
1021    return this.serverSendResponse(this.currentPage.networkTraffic(), serverResponse);
1022  };
1023
1024  /**
1025   * Clears the accumulated network_traffic in the current page
1026   * @param serverResponse
1027   * @return {*}
1028   */
1029  Browser.prototype.clear_network_traffic = function (serverResponse) {
1030    this.currentPage.clearNetworkTraffic();
1031    return this.serverSendResponse(true, serverResponse);
1032  };
1033
1034  /**
1035   * Gets the headers of the current page
1036   * @param serverResponse
1037   * @return {*}
1038   */
1039  Browser.prototype.get_headers = function (serverResponse) {
1040    return this.serverSendResponse(this.currentPage.getCustomHeaders(), serverResponse);
1041  };
1042
1043  /**
1044   * Set headers in the browser
1045   * @param serverResponse
1046   * @param headers
1047   * @return {*}
1048   */
1049  Browser.prototype.set_headers = function (serverResponse, headers) {
1050    if (headers['User-Agent']) {
1051      this.currentPage.setUserAgent(headers['User-Agent']);
1052    }
1053    this.currentPage.setCustomHeaders(headers);
1054    return this.serverSendResponse(true, serverResponse);
1055  };
1056
1057  /**
1058   * Given an array of headers, adds them to the page
1059   * @param serverResponse
1060   * @param headers
1061   * @return {*}
1062   */
1063  Browser.prototype.add_headers = function (serverResponse, headers) {
1064    var allHeaders, name, value;
1065    allHeaders = this.currentPage.getCustomHeaders();
1066    for (name in headers) {
1067      if (headers.hasOwnProperty(name)) {
1068        value = headers[name];
1069        allHeaders[name] = value;
1070      }
1071    }
1072    return this.set_headers(serverResponse, allHeaders);
1073  };
1074
1075  /**
1076   * Adds a header to the page temporary or permanently
1077   * @param serverResponse
1078   * @param header
1079   * @param permanent
1080   * @return {*}
1081   */
1082  Browser.prototype.add_header = function (serverResponse, header, permanent) {
1083    if (!permanent) {
1084      this.currentPage.addTempHeader(header);
1085    }
1086    return this.add_headers(serverResponse, header);
1087  };
1088
1089
1090  /**
1091   * Sends back the client the response headers sent from the browser when making
1092   * the page request
1093   * @param serverResponse
1094   * @return {*}
1095   */
1096  Browser.prototype.response_headers = function (serverResponse) {
1097    return this.serverSendResponse(this.currentPage.responseHeaders(), serverResponse);
1098  };
1099
1100  /**
1101   * Returns the cookies of the current page being browsed
1102   * @param serverResponse
1103   * @return {*}
1104   */
1105  Browser.prototype.cookies = function (serverResponse) {
1106    return this.serverSendResponse(this.currentPage.cookies(), serverResponse);
1107  };
1108
1109  /**
1110   * Sets a cookie in the browser, the format of the cookies has to be the format it says
1111   * on phantomjs documentation and as such you can set it in other domains, not on the
1112   * current page
1113   * @param serverResponse
1114   * @param cookie
1115   * @return {*}
1116   */
1117  Browser.prototype.set_cookie = function (serverResponse, cookie) {
1118    return this.serverSendResponse(phantom.addCookie(cookie), serverResponse);
1119  };
1120
1121  /**
1122   * Remove a cookie set on the current page
1123   * @param serverResponse
1124   * @param name
1125   * @return {*}
1126   */
1127  Browser.prototype.remove_cookie = function (serverResponse, name) {
1128    //TODO: add error control to check if the cookie was properly deleted
1129    this.currentPage.deleteCookie(name);
1130    phantom.deleteCookie(name);
1131    return this.serverSendResponse(true, serverResponse);
1132  };
1133
1134  /**
1135   * Clear the cookies in the browser
1136   * @param serverResponse
1137   * @return {*}
1138   */
1139  Browser.prototype.clear_cookies = function (serverResponse) {
1140    phantom.clearCookies();
1141    return this.serverSendResponse(true, serverResponse);
1142  };
1143
1144  /**
1145   * Enables / Disables the cookies on the browser
1146   * @param serverResponse
1147   * @param flag
1148   * @return {*}
1149   */
1150  Browser.prototype.cookies_enabled = function (serverResponse, flag) {
1151    phantom.cookiesEnabled = flag;
1152    return this.serverSendResponse(true, serverResponse);
1153  };
1154
1155  /**
1156   * US19: DONE
1157   * Sets a basic authentication credential to access a page
1158   * THIS SHOULD BE USED BEFORE accessing a page
1159   * @param serverResponse
1160   * @param user
1161   * @param password
1162   * @return {*}
1163   */
1164  Browser.prototype.set_http_auth = function (serverResponse, user, password) {
1165    this.currentPage.setHttpAuth(user, password);
1166    return this.serverSendResponse(true, serverResponse);
1167  };
1168
1169  /**
1170   * Sets the flag whether to fail on javascript errors or not.
1171   * @param serverResponse
1172   * @param value
1173   * @return {*}
1174   */
1175  Browser.prototype.set_js_errors = function (serverResponse, value) {
1176    this.js_errors = value;
1177    return this.serverSendResponse(true, serverResponse);
1178  };
1179
1180  /**
1181   * Sets the debug mode to boolean value
1182   * @param serverResponse
1183   * @param value
1184   * @return {*}
1185   */
1186  Browser.prototype.set_debug = function (serverResponse, value) {
1187    this._debug = value;
1188    return this.serverSendResponse(true, serverResponse);
1189  };
1190
1191  /**
1192   * Goes back in the history when possible
1193   * @param serverResponse
1194   * @return {*}
1195   */
1196  Browser.prototype.go_back = function (serverResponse) {
1197    var self = this;
1198    if (this.currentPage.canGoBack()) {
1199      this.currentPage.state = 'loading';
1200      this.currentPage.goBack();
1201      return this.currentPage.waitState('default', function () {
1202        return self.serverSendResponse(true, serverResponse);
1203      });
1204    } else {
1205      return this.serverSendResponse(false, serverResponse);
1206    }
1207  };
1208
1209  /**
1210   * Reloads the page if possible
1211   * @return {*}
1212   */
1213  Browser.prototype.reload = function (serverResponse) {
1214    var self = this;
1215    this.currentPage.state = 'loading';
1216    this.currentPage.reload();
1217    return this.currentPage.waitState('default', function () {
1218      return self.serverSendResponse(true, serverResponse);
1219    });
1220  };
1221
1222  /**
1223   * Goes forward in the browser history if possible
1224   * @param serverResponse
1225   * @return {*}
1226   */
1227  Browser.prototype.go_forward = function (serverResponse) {
1228    var self = this;
1229    if (this.currentPage.canGoForward()) {
1230      this.currentPage.state = 'loading';
1231      this.currentPage.goForward();
1232      return this.currentPage.waitState('default', function () {
1233        return self.serverSendResponse(true, serverResponse);
1234      });
1235    } else {
1236      return this.serverSendResponse(false, serverResponse);
1237    }
1238  };
1239
1240  /**
1241   *  Sets the urlBlacklist for the given urls as parameters
1242   * @return {boolean}
1243   */
1244  Browser.prototype.set_url_blacklist = function (serverResponse, blackList) {
1245    this.currentPage.urlBlacklist = Array.prototype.slice.call(blackList);
1246    return this.serverSendResponse(true, serverResponse);
1247  };
1248
1249  /**
1250   * Runs a browser command and returns the response back to the client
1251   * when the command has finished the execution
1252   * @param command
1253   * @param serverResponse
1254   * @return {*}
1255   */
1256  Browser.prototype.serverRunCommand = function (command, serverResponse) {
1257    var commandData;
1258    var commandArgs;
1259    var commandName;
1260
1261    commandName = command.name;
1262    commandArgs = command.args;
1263    this.currentPage.state = 'default';
1264    commandData = [serverResponse].concat(commandArgs);
1265
1266    if (typeof this[commandName] !== "function") {
1267      //We can not run such command
1268      throw new Poltergeist.Error();
1269    }
1270
1271    return this[commandName].apply(this, commandData);
1272  };
1273
1274  /**
1275   * Sends a response back to the client who made the request
1276   * @param response
1277   * @param serverResponse
1278   * @return {*}
1279   */
1280  Browser.prototype.serverSendResponse = function (response, serverResponse) {
1281    var errors;
1282    errors = this.currentPage.errors;
1283    this.currentPage.clearErrors();
1284    if (errors.length > 0 && this.js_errors) {
1285      return this.owner.serverSendError(new Poltergeist.JavascriptError(errors), serverResponse);
1286    } else {
1287      return this.owner.serverSendResponse(response, serverResponse);
1288    }
1289  };
1290
1291  return Browser;
1292
1293})();
1294
Full Screen