Source

CherryPy / cherrypy / test / test_states.py

  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
477
478
479
480
481
482
483
484
485
486
487
488
489
import httplib
from httplib import BadStatusLine

import os
import sys
import threading
import time

from cherrypy.test import test
test.prefer_parent_path()

import cherrypy
engine = cherrypy.engine
thisdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
PID_file_path = os.path.join(thisdir, 'pid_for_test_daemonize')


class Root:
    def index(self):
        return "Hello World"
    index.exposed = True
    
    def ctrlc(self):
        raise KeyboardInterrupt()
    ctrlc.exposed = True
    
    def graceful(self):
        engine.graceful()
        return "app was (gracefully) restarted succesfully"
    graceful.exposed = True
    
    def block_explicit(self):
        while True:
            if cherrypy.response.timed_out:
                cherrypy.response.timed_out = False
                return "broken!"
            time.sleep(0.01)
    block_explicit.exposed = True
    
    def block_implicit(self):
        time.sleep(0.5)
        return "response.timeout = %s" % cherrypy.response.timeout
    block_implicit.exposed = True

cherrypy.tree.mount(Root())
cherrypy.config.update({
    'environment': 'test_suite',
    'engine.deadlock_poll_freq': 0.1,
    })

class Dependency:
    
    def __init__(self, bus):
        self.bus = bus
        self.running = False
        self.startcount = 0
        self.gracecount = 0
        self.threads = {}
    
    def subscribe(self):
        self.bus.subscribe('start', self.start)
        self.bus.subscribe('stop', self.stop)
        self.bus.subscribe('graceful', self.graceful)
        self.bus.subscribe('start_thread', self.startthread)
        self.bus.subscribe('stop_thread', self.stopthread)
    
    def start(self):
        self.running = True
        self.startcount += 1
    
    def stop(self):
        self.running = False
    
    def graceful(self):
        self.gracecount += 1
    
    def startthread(self, thread_id):
        self.threads[thread_id] = None
    
    def stopthread(self, thread_id):
        del self.threads[thread_id]

db_connection = Dependency(engine)
db_connection.subscribe()


from cherrypy.test import helper

class ServerStateTests(helper.CPWebCase):
    
    def test_0_NormalStateFlow(self):
        if not self.server_class:
            # Without having called "engine.start()", we should
            # get a 503 Service Unavailable response.
            self.getPage("/")
            self.assertStatus(503)
        
        # And our db_connection should not be running
        self.assertEqual(db_connection.running, False)
        self.assertEqual(db_connection.startcount, 0)
        self.assertEqual(len(db_connection.threads), 0)
        
        # Test server start
        cherrypy.server.quickstart(self.server_class)
        engine.start()
        self.assertEqual(engine.state, engine.states.STARTED)
        
        if self.server_class:
            host = cherrypy.server.socket_host
            port = cherrypy.server.socket_port
            self.assertRaises(IOError, cherrypy._cpserver.check_port, host, port)
        
        # The db_connection should be running now
        self.assertEqual(db_connection.running, True)
        self.assertEqual(db_connection.startcount, 1)
        self.assertEqual(len(db_connection.threads), 0)
        
        self.getPage("/")
        self.assertBody("Hello World")
        self.assertEqual(len(db_connection.threads), 1)
        
        # Test engine stop. This will also stop the HTTP server.
        engine.stop()
        self.assertEqual(engine.state, engine.states.STOPPED)
        
        # Verify that our custom stop function was called
        self.assertEqual(db_connection.running, False)
        self.assertEqual(len(db_connection.threads), 0)
        
        if not self.server_class:
            # Once the engine has stopped, we should get a 503
            # error again. (If we were running an HTTP server,
            # then the connection should not even be processed).
            self.getPage("/")
            self.assertStatus(503)
        
        # Block the main thread now and verify that stop() works.
        def stoptest():
            self.getPage("/")
            self.assertBody("Hello World")
            engine.stop()
        cherrypy.server.start()
        engine.start_with_callback(stoptest)
        engine.block()
        self.assertEqual(engine.state, engine.states.STOPPED)
    
    def test_1_Restart(self):
        cherrypy.server.start()
        engine.start()
        
        # The db_connection should be running now
        self.assertEqual(db_connection.running, True)
        grace = db_connection.gracecount
        
        self.getPage("/")
        self.assertBody("Hello World")
        self.assertEqual(len(db_connection.threads), 1)
        
        # Test server restart from this thread
        engine.graceful()
        self.assertEqual(engine.state, engine.states.STARTED)
        self.getPage("/")
        self.assertBody("Hello World")
        self.assertEqual(db_connection.running, True)
        self.assertEqual(db_connection.gracecount, grace + 1)
        self.assertEqual(len(db_connection.threads), 1)
        
        # Test server restart from inside a page handler
        self.getPage("/graceful")
        self.assertEqual(engine.state, engine.states.STARTED)
        self.assertBody("app was (gracefully) restarted succesfully")
        self.assertEqual(db_connection.running, True)
        self.assertEqual(db_connection.gracecount, grace + 2)
        # Since we are requesting synchronously, is only one thread used?
        # Note that the "/graceful" request has been flushed.
        self.assertEqual(len(db_connection.threads), 0)
        
        engine.stop()
        self.assertEqual(engine.state, engine.states.STOPPED)
        self.assertEqual(db_connection.running, False)
        self.assertEqual(len(db_connection.threads), 0)
    
    def test_2_KeyboardInterrupt(self):
        if self.server_class:
            
            # Raise a keyboard interrupt in the HTTP server's main thread.
            # We must start the server in this, the main thread
            engine.start()
            cherrypy.server.start()
            
            self.persistent = True
            try:
                # Make the first request and assert there's no "Connection: close".
                self.getPage("/")
                self.assertStatus('200 OK')
                self.assertBody("Hello World")
                self.assertNoHeader("Connection")
                
                cherrypy.server.httpserver.interrupt = KeyboardInterrupt
                engine.block()
                
                self.assertEqual(db_connection.running, False)
                self.assertEqual(len(db_connection.threads), 0)
                self.assertEqual(engine.state, engine.states.STOPPED)
            finally:
                self.persistent = False
            
            # Raise a keyboard interrupt in a page handler; on multithreaded
            # servers, this should occur in one of the worker threads.
            # This should raise a BadStatusLine error, since the worker
            # thread will just die without writing a response.
            engine.start()
            cherrypy.server.start()
            
            try:
                self.getPage("/ctrlc")
            except BadStatusLine:
                pass
            else:
                print self.body
                self.fail("AssertionError: BadStatusLine not raised")
            
            engine.block()
            self.assertEqual(db_connection.running, False)
            self.assertEqual(len(db_connection.threads), 0)
    
    def test_3_Deadlocks(self):
        cherrypy.config.update({'response.timeout': 0.2})
        
        engine.start()
        cherrypy.server.start()
        try:
            self.assertNotEqual(cherrypy.timeout_monitor.thread, None)
            
            # Request a "normal" page.
            self.assertEqual(cherrypy.timeout_monitor.servings, [])
            self.getPage("/")
            self.assertBody("Hello World")
            # request.close is called async.
            while cherrypy.timeout_monitor.servings:
                print ".",
                time.sleep(0.01)
            
            # Request a page that explicitly checks itself for deadlock.
            # The deadlock_timeout should be 2 secs.
            self.getPage("/block_explicit")
            self.assertBody("broken!")
            
            # Request a page that implicitly breaks deadlock.
            # If we deadlock, we want to touch as little code as possible,
            # so we won't even call handle_error, just bail ASAP.
            self.getPage("/block_implicit")
            self.assertStatus(500)
            self.assertInBody("raise cherrypy.TimeoutError()")
        finally:
            engine.stop()
    
    def test_4_Autoreload(self):
        if not self.server_class:
            print "skipped (no server) ",
            return
        
        # Start the demo script in a new process
        demoscript = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                  "test_states_demo.py")
        host = cherrypy.server.socket_host
        port = cherrypy.server.socket_port
        cherrypy._cpserver.wait_for_free_port(host, port)
        
        args = [sys.executable, demoscript, host, str(port)]
        if self.scheme == "https":
            args.append('-ssl')
        pid = os.spawnl(os.P_NOWAIT, sys.executable, *args)
        cherrypy._cpserver.wait_for_occupied_port(host, port)
        
        try:
            self.getPage("/start")
            start = float(self.body)
            
            # Give the autoreloader time to cache the file time.
            time.sleep(2)
            
            # Touch the file
            os.utime(demoscript, None)
            
            # Give the autoreloader time to re-exec the process
            time.sleep(2)
            cherrypy._cpserver.wait_for_occupied_port(host, port)
            
            self.getPage("/pid")
            pid = int(self.body)
            
            self.getPage("/start")
            self.assert_(float(self.body) > start)
        finally:
            # Shut down the spawned process
            self.getPage("/stop")
        
        try:
            try:
                # Mac, UNIX
                print os.wait()
            except AttributeError:
                # Windows
                print os.waitpid(pid, 0)
        except OSError, x:
            if x.args != (10, 'No child processes'):
                raise
    
    def test_5_Start_Error(self):
        if not self.server_class:
            print "skipped (no server) ",
            return
        
        # Start the demo script in a new process
        demoscript = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                  "test_states_demo.py")
        host = cherrypy.server.socket_host
        port = cherrypy.server.socket_port
        
        # If a process errors during start, it should stop the engine
        # and exit with a non-zero exit code.
        args = [sys.executable, demoscript, host, str(port), '-starterror']
        if self.scheme == "https":
            args.append('-ssl')
        exit_code = os.spawnl(os.P_WAIT, sys.executable, *args)
        if exit_code == 0:
            self.fail("Process failed to return nonzero exit code.")


class DaemonizeTests(helper.CPWebCase):
    
    def test_1_Daemonize(self):
        if not self.server_class:
            print "skipped (no server) ",
            return
        if os.name not in ['posix']: 
            print "skipped (not on posix) ",
            return
        
        # Start the demo script in a new process
        demoscript = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                  "test_states_demo.py")
        host = cherrypy.server.socket_host
        port = cherrypy.server.socket_port
        cherrypy._cpserver.wait_for_free_port(host, port)
        
        args = [sys.executable, demoscript, host, str(port), '-daemonize']
        if self.scheme == "https":
            args.append('-ssl')
        # Spawn the process and wait, when this returns, the original process
        # is finished.  If it daemonized properly, we should still be able
        # to access pages.
        exit_code = os.spawnl(os.P_WAIT, sys.executable, *args)
        cherrypy._cpserver.wait_for_occupied_port(host, port)
        
        # Give the server some time to start up
        time.sleep(2)
        
        # Get the PID from the file.
        pid = int(open(PID_file_path).read())
        try:
            # Just get the pid of the daemonization process.
            self.getPage("/pid")
            self.assertStatus(200)
            page_pid = int(self.body)
            self.assertEqual(page_pid, pid)
        finally:
            # Shut down the spawned process
            self.getPage("/stop")
        
        try:
            print os.waitpid(pid, 0)
        except OSError, x:
            if x.args != (10, 'No child processes'):
                raise
        
        # Wait until here to test the exit code because we want to ensure
        # that we wait for the daemon to finish running before we fail.
        if exit_code != 0:
            self.fail("Daemonized process failed to exit cleanly")
    
    def test_2_Start_Error_With_Daemonize(self):
        if not self.server_class:
            print "skipped (no server) ",
            return
        if os.name not in ['posix']: 
            print "skipped (not on posix) ",
            return
        
        # Start the demo script in a new process
        demoscript = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                  "test_states_demo.py")
        host = cherrypy.server.socket_host
        port = cherrypy.server.socket_port
        
        # If a process errors during start, it should stop the engine
        # and exit with a non-zero exit code, even if we daemonize soon
        # thereafter.
        args = [sys.executable, demoscript, host, str(port), '-starterror', '-daemonize']
        if self.scheme == "https":
            args.append('-ssl')
        exit_code = os.spawnl(os.P_WAIT, sys.executable, *args)
        if exit_code == 0:
            self.fail("Process failed to return nonzero exit code.")
        time.sleep(2) # Wait for the daemonized process to exit.


def run(server, conf):
    helper.setConfig(conf)
    ServerStateTests.server_class = server
    DaemonizeTests.server_class = server
    suite = helper.CPTestLoader.loadTestsFromTestCase(ServerStateTests)
    daemon_suite = helper.CPTestLoader.loadTestsFromTestCase(DaemonizeTests)
    try:
        try:
            import pyconquer
        except ImportError:
            helper.CPTestRunner.run(suite)
            helper.CPTestRunner.run(daemon_suite)
        else:
            tr = pyconquer.Logger("cherrypy")
            tr.out = open(os.path.join(os.path.dirname(__file__), "state.log"), "wb")
            try:
                tr.start()
                helper.CPTestRunner.run(suite)
                helper.CPTestRunner.run(daemon_suite)
            finally:
                tr.stop()
                tr.out.close()
    finally:
        engine.stop()


def run_all(host, port, ssl=False):
    conf = {'server.socket_host': host,
            'server.socket_port': port,
            'server.thread_pool': 10,
            'environment': "test_suite",
            }
    
    if host:
        DaemonizeTests.HOST = ServerStateTests.HOST = host
    
    if port:
        DaemonizeTests.PORT = ServerStateTests.PORT = port
    
    if ssl:
        localDir = os.path.dirname(__file__)
        serverpem = os.path.join(os.getcwd(), localDir, 'test.pem')
        conf['server.ssl_certificate'] = serverpem
        conf['server.ssl_private_key'] = serverpem
        DaemonizeTests.scheme = ServerStateTests.scheme = "https"
        DaemonizeTests.HTTP_CONN = ServerStateTests.HTTP_CONN = httplib.HTTPSConnection
    
    def _run(server):
        print
        print "Testing %s on %s:%s..." % (server, host, port)
        run(server, conf)
    _run("cherrypy._cpwsgi.CPWSGIServer")

if __name__ == "__main__":
    import sys
    
    host = '127.0.0.1'
    port = 8000
    ssl = False
    
    argv = sys.argv[1:]
    if argv:
        help_args = [prefix + atom for atom in ("?", "h", "help")
                     for prefix in ("", "-", "--", "\\")]
        
        for arg in argv:
            if arg in help_args:
                print
                print "test_states.py -?                       -> this help page"
                print "test_states.py [-host=h] [-port=p]      -> run the tests on h:p"
                print "test_states.py -ssl [-host=h] [-port=p] -> run the tests using SSL on h:p"
                sys.exit(0)
            
            if arg == "-ssl":
                ssl = True
            elif arg.startswith("-host="):
                host = arg[6:].strip("\"'")
            elif arg.startswith("-port="):
                port = int(arg[6:].strip())
    
    run_all(host, port, ssl)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.