blob: 83c3b4fd0d9124ae0ed1e1116aabf61573e14c78 [file] [log] [blame]
Neal Norwitzb4a2df02003-01-02 14:56:39 +00001#!/usr/bin/env python
2#
Vinay Sajip7dc8ec92004-06-02 10:51:05 +00003# Copyright 2001-2004 by Vinay Sajip. All Rights Reserved.
Neal Norwitzb4a2df02003-01-02 14:56:39 +00004#
5# Permission to use, copy, modify, and distribute this software and its
6# documentation for any purpose and without fee is hereby granted,
7# provided that the above copyright notice appear in all copies and that
8# both that copyright notice and this permission notice appear in
9# supporting documentation, and that the name of Vinay Sajip
10# not be used in advertising or publicity pertaining to distribution
11# of the software without specific, written prior permission.
12# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
13# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
14# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
15# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
16# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
17# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18#
19# This file is part of the Python logging distribution. See
20# http://www.red-dove.com/python_logging.html
21#
22"""Test harness for the logging module. Run all tests.
23
24Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
25"""
26
Guido van Rossum2a1d5162003-01-21 21:05:22 +000027import select
Neal Norwitzb4a2df02003-01-02 14:56:39 +000028import os, sys, string, struct, types, cPickle, cStringIO
Vinay Sajip22b25aa2006-01-16 21:24:38 +000029import socket, tempfile, threading, time
Neal Norwitzb4a2df02003-01-02 14:56:39 +000030import logging, logging.handlers, logging.config
31
Neal Norwitzb4a2df02003-01-02 14:56:39 +000032BANNER = "-- %-10s %-6s ---------------------------------------------------\n"
33
Guido van Rossum376e6362003-04-25 14:22:00 +000034FINISH_UP = "Finish up, it's closing time. Messages should bear numbers 0 through 24."
35
Neal Norwitzb4a2df02003-01-02 14:56:39 +000036#----------------------------------------------------------------------------
37# Log receiver
38#----------------------------------------------------------------------------
39
40TIMEOUT = 10
41
42from SocketServer import ThreadingTCPServer, StreamRequestHandler
43
44class LogRecordStreamHandler(StreamRequestHandler):
45 """
46 Handler for a streaming logging request. It basically logs the record
47 using whatever logging policy is configured locally.
48 """
49
50 def handle(self):
51 """
52 Handle multiple requests - each expected to be a 4-byte length,
53 followed by the LogRecord in pickle format. Logs the record
54 according to whatever policy is configured locally.
55 """
56 while 1:
57 try:
58 chunk = self.connection.recv(4)
59 if len(chunk) < 4:
60 break
61 slen = struct.unpack(">L", chunk)[0]
Neal Norwitzb4a2df02003-01-02 14:56:39 +000062 chunk = self.connection.recv(slen)
63 while len(chunk) < slen:
64 chunk = chunk + self.connection.recv(slen - len(chunk))
65 obj = self.unPickle(chunk)
Raymond Hettinger6f3eaa62003-06-27 21:43:39 +000066 record = logging.makeLogRecord(obj)
Neal Norwitzb4a2df02003-01-02 14:56:39 +000067 self.handleLogRecord(record)
68 except:
69 raise
70
71 def unPickle(self, data):
72 return cPickle.loads(data)
73
74 def handleLogRecord(self, record):
75 logname = "logrecv.tcp." + record.name
Guido van Rossum376e6362003-04-25 14:22:00 +000076 #If the end-of-messages sentinel is seen, tell the server to terminate
77 if record.msg == FINISH_UP:
78 self.server.abort = 1
Neal Norwitzb4a2df02003-01-02 14:56:39 +000079 record.msg = record.msg + " (via " + logname + ")"
80 logger = logging.getLogger(logname)
81 logger.handle(record)
82
Brett Cannonf9addb62003-04-30 05:32:32 +000083# The server sets socketDataProcessed when it's done.
84socketDataProcessed = threading.Event()
Guido van Rossum376e6362003-04-25 14:22:00 +000085
Neal Norwitzb4a2df02003-01-02 14:56:39 +000086class LogRecordSocketReceiver(ThreadingTCPServer):
87 """
88 A simple-minded TCP socket-based logging receiver suitable for test
89 purposes.
90 """
91
92 allow_reuse_address = 1
93
94 def __init__(self, host='localhost',
95 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
96 handler=LogRecordStreamHandler):
97 ThreadingTCPServer.__init__(self, (host, port), handler)
98 self.abort = 0
99 self.timeout = 1
100
Neal Norwitz67dfb6f2006-03-03 21:53:14 +0000101 def _wait_and_process_data(self):
102 rd, wr, ex = select.select([self.socket.fileno()], [], [],
103 self.timeout)
104 if rd:
105 self.handle_request()
106
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000107 def serve_until_stopped(self):
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000108 while not self.abort:
Neal Norwitz67dfb6f2006-03-03 21:53:14 +0000109 self._wait_and_process_data()
110
111 # XXX(nnorwitz): Try to fix timing related test failures.
112 # It's possible self.aborted was set before the final message
113 # was received. By calling _wait_and_process_data(),
114 # it gives us one last chance to read messages.
115 # The test generally only fails on Solaris.
116 self._wait_and_process_data()
Guido van Rossum376e6362003-04-25 14:22:00 +0000117 #notify the main thread that we're about to exit
Brett Cannonf9addb62003-04-30 05:32:32 +0000118 socketDataProcessed.set()
Martin v. Löwisf6848882006-01-29 19:55:18 +0000119 # close the listen socket
120 self.server_close()
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000121
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000122 def process_request(self, request, client_address):
123 #import threading
124 t = threading.Thread(target = self.finish_request,
125 args = (request, client_address))
126 t.start()
127
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000128def runTCP(tcpserver):
129 tcpserver.serve_until_stopped()
130
131#----------------------------------------------------------------------------
132# Test 0
133#----------------------------------------------------------------------------
134
135msgcount = 0
136
137def nextmessage():
138 global msgcount
139 rv = "Message %d" % msgcount
140 msgcount = msgcount + 1
141 return rv
142
143def test0():
144 ERR = logging.getLogger("ERR")
145 ERR.setLevel(logging.ERROR)
146 INF = logging.getLogger("INF")
147 INF.setLevel(logging.INFO)
148 INF_ERR = logging.getLogger("INF.ERR")
149 INF_ERR.setLevel(logging.ERROR)
150 DEB = logging.getLogger("DEB")
151 DEB.setLevel(logging.DEBUG)
152
153 INF_UNDEF = logging.getLogger("INF.UNDEF")
154 INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF")
155 UNDEF = logging.getLogger("UNDEF")
156
157 GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
158 CHILD = logging.getLogger("INF.BADPARENT")
159
160 #These should log
161 ERR.log(logging.FATAL, nextmessage())
162 ERR.error(nextmessage())
163
164 INF.log(logging.FATAL, nextmessage())
165 INF.error(nextmessage())
166 INF.warn(nextmessage())
167 INF.info(nextmessage())
168
169 INF_UNDEF.log(logging.FATAL, nextmessage())
170 INF_UNDEF.error(nextmessage())
171 INF_UNDEF.warn (nextmessage())
172 INF_UNDEF.info (nextmessage())
173
174 INF_ERR.log(logging.FATAL, nextmessage())
175 INF_ERR.error(nextmessage())
176
177 INF_ERR_UNDEF.log(logging.FATAL, nextmessage())
178 INF_ERR_UNDEF.error(nextmessage())
179
180 DEB.log(logging.FATAL, nextmessage())
181 DEB.error(nextmessage())
182 DEB.warn (nextmessage())
183 DEB.info (nextmessage())
184 DEB.debug(nextmessage())
185
186 UNDEF.log(logging.FATAL, nextmessage())
187 UNDEF.error(nextmessage())
188 UNDEF.warn (nextmessage())
189 UNDEF.info (nextmessage())
190
191 GRANDCHILD.log(logging.FATAL, nextmessage())
192 CHILD.log(logging.FATAL, nextmessage())
193
194 #These should not log
195 ERR.warn(nextmessage())
196 ERR.info(nextmessage())
197 ERR.debug(nextmessage())
198
199 INF.debug(nextmessage())
200 INF_UNDEF.debug(nextmessage())
201
202 INF_ERR.warn(nextmessage())
203 INF_ERR.info(nextmessage())
204 INF_ERR.debug(nextmessage())
205 INF_ERR_UNDEF.warn(nextmessage())
206 INF_ERR_UNDEF.info(nextmessage())
207 INF_ERR_UNDEF.debug(nextmessage())
208
Guido van Rossum376e6362003-04-25 14:22:00 +0000209 INF.info(FINISH_UP)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000210
211#----------------------------------------------------------------------------
212# Test 1
213#----------------------------------------------------------------------------
214
215#
216# First, we define our levels. There can be as many as you want - the only
217# limitations are that they should be integers, the lowest should be > 0 and
218# larger values mean less information being logged. If you need specific
219# level values which do not fit into these limitations, you can use a
220# mapping dictionary to convert between your application levels and the
221# logging system.
222#
223SILENT = 10
224TACITURN = 9
225TERSE = 8
226EFFUSIVE = 7
227SOCIABLE = 6
228VERBOSE = 5
229TALKATIVE = 4
230GARRULOUS = 3
231CHATTERBOX = 2
232BORING = 1
233
234LEVEL_RANGE = range(BORING, SILENT + 1)
235
236#
237# Next, we define names for our levels. You don't need to do this - in which
238# case the system will use "Level n" to denote the text for the level.
239#
240my_logging_levels = {
241 SILENT : 'Silent',
242 TACITURN : 'Taciturn',
243 TERSE : 'Terse',
244 EFFUSIVE : 'Effusive',
245 SOCIABLE : 'Sociable',
246 VERBOSE : 'Verbose',
247 TALKATIVE : 'Talkative',
248 GARRULOUS : 'Garrulous',
249 CHATTERBOX : 'Chatterbox',
250 BORING : 'Boring',
251}
252
253#
254# Now, to demonstrate filtering: suppose for some perverse reason we only
255# want to print out all except GARRULOUS messages. Let's create a filter for
256# this purpose...
257#
258class SpecificLevelFilter(logging.Filter):
259 def __init__(self, lvl):
260 self.level = lvl
261
262 def filter(self, record):
263 return self.level != record.levelno
264
265class GarrulousFilter(SpecificLevelFilter):
266 def __init__(self):
267 SpecificLevelFilter.__init__(self, GARRULOUS)
268
269#
270# Now, let's demonstrate filtering at the logger. This time, use a filter
271# which excludes SOCIABLE and TACITURN messages. Note that GARRULOUS events
272# are still excluded.
273#
274class VerySpecificFilter(logging.Filter):
275 def filter(self, record):
276 return record.levelno not in [SOCIABLE, TACITURN]
277
278def message(s):
279 sys.stdout.write("%s\n" % s)
280
281SHOULD1 = "This should only be seen at the '%s' logging level (or lower)"
282
283def test1():
284#
285# Now, tell the logging system to associate names with our levels.
286#
287 for lvl in my_logging_levels.keys():
288 logging.addLevelName(lvl, my_logging_levels[lvl])
289
290#
291# Now, define a test function which logs an event at each of our levels.
292#
293
294 def doLog(log):
295 for lvl in LEVEL_RANGE:
296 log.log(lvl, SHOULD1, logging.getLevelName(lvl))
297
298 log = logging.getLogger("")
299 hdlr = log.handlers[0]
300#
301# Set the logging level to each different value and call the utility
302# function to log events.
303# In the output, you should see that each time round the loop, the number of
304# logging events which are actually output decreases.
305#
306 for lvl in LEVEL_RANGE:
307 message("-- setting logging level to '%s' -----" %
308 logging.getLevelName(lvl))
309 log.setLevel(lvl)
310 doLog(log)
311 #
312 # Now, we demonstrate level filtering at the handler level. Tell the
313 # handler defined above to filter at level 'SOCIABLE', and repeat the
314 # above loop. Compare the output from the two runs.
315 #
316 hdlr.setLevel(SOCIABLE)
317 message("-- Filtering at handler level to SOCIABLE --")
318 for lvl in LEVEL_RANGE:
319 message("-- setting logging level to '%s' -----" %
320 logging.getLevelName(lvl))
321 log.setLevel(lvl)
322 doLog(log)
323
324 hdlr.setLevel(0) #turn off level filtering at the handler
325
326 garr = GarrulousFilter()
327 hdlr.addFilter(garr)
328 message("-- Filtering using GARRULOUS filter --")
329 for lvl in LEVEL_RANGE:
330 message("-- setting logging level to '%s' -----" %
331 logging.getLevelName(lvl))
332 log.setLevel(lvl)
333 doLog(log)
334 spec = VerySpecificFilter()
335 log.addFilter(spec)
336 message("-- Filtering using specific filter for SOCIABLE, TACITURN --")
337 for lvl in LEVEL_RANGE:
338 message("-- setting logging level to '%s' -----" %
339 logging.getLevelName(lvl))
340 log.setLevel(lvl)
341 doLog(log)
342
343 log.removeFilter(spec)
344 hdlr.removeFilter(garr)
345 #Undo the one level which clashes...for regression tests
346 logging.addLevelName(logging.DEBUG, "DEBUG")
347
348#----------------------------------------------------------------------------
349# Test 2
350#----------------------------------------------------------------------------
351
352MSG = "-- logging %d at INFO, messages should be seen every 10 events --"
353def test2():
354 logger = logging.getLogger("")
355 sh = logger.handlers[0]
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000356 sh.close()
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000357 logger.removeHandler(sh)
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000358 mh = logging.handlers.MemoryHandler(10,logging.WARNING, sh)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000359 logger.setLevel(logging.DEBUG)
360 logger.addHandler(mh)
361 message("-- logging at DEBUG, nothing should be seen yet --")
362 logger.debug("Debug message")
363 message("-- logging at INFO, nothing should be seen yet --")
364 logger.info("Info message")
Neal Norwitz6fa635d2003-02-18 14:20:07 +0000365 message("-- logging at WARNING, 3 messages should be seen --")
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000366 logger.warn("Warn message")
367 for i in xrange(102):
368 message(MSG % i)
369 logger.info("Info index = %d", i)
370 mh.close()
371 logger.removeHandler(mh)
372 logger.addHandler(sh)
373
374#----------------------------------------------------------------------------
375# Test 3
376#----------------------------------------------------------------------------
377
378FILTER = "a.b"
379
380def doLog3():
381 logging.getLogger("a").info("Info 1")
382 logging.getLogger("a.b").info("Info 2")
383 logging.getLogger("a.c").info("Info 3")
384 logging.getLogger("a.b.c").info("Info 4")
385 logging.getLogger("a.b.c.d").info("Info 5")
386 logging.getLogger("a.bb.c").info("Info 6")
387 logging.getLogger("b").info("Info 7")
388 logging.getLogger("b.a").info("Info 8")
389 logging.getLogger("c.a.b").info("Info 9")
390 logging.getLogger("a.bb").info("Info 10")
391
392def test3():
393 root = logging.getLogger()
394 root.setLevel(logging.DEBUG)
395 hand = root.handlers[0]
396 message("Unfiltered...")
397 doLog3()
398 message("Filtered with '%s'..." % FILTER)
399 filt = logging.Filter(FILTER)
400 hand.addFilter(filt)
401 doLog3()
402 hand.removeFilter(filt)
403
404#----------------------------------------------------------------------------
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000405# Test 4
406#----------------------------------------------------------------------------
407
Vinay Sajip568482a2006-01-20 18:29:36 +0000408# config0 is a standard configuration.
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000409config0 = """
410[loggers]
411keys=root
412
413[handlers]
414keys=hand1
415
416[formatters]
417keys=form1
418
419[logger_root]
420level=NOTSET
421handlers=hand1
422
423[handler_hand1]
424class=StreamHandler
425level=NOTSET
426formatter=form1
427args=(sys.stdout,)
428
429[formatter_form1]
430format=%(levelname)s:%(name)s:%(message)s
431datefmt=
432"""
433
434# config1 adds a little to the standard configuration.
435config1 = """
436[loggers]
437keys=root,parser
438
439[handlers]
440keys=hand1
441
442[formatters]
443keys=form1
444
445[logger_root]
446level=NOTSET
447handlers=hand1
448
449[logger_parser]
450level=DEBUG
451handlers=hand1
452propagate=1
453qualname=compiler.parser
454
455[handler_hand1]
456class=StreamHandler
457level=NOTSET
458formatter=form1
459args=(sys.stdout,)
460
461[formatter_form1]
462format=%(levelname)s:%(name)s:%(message)s
463datefmt=
464"""
465
466# config2 has a subtle configuration error that should be reported
467config2 = string.replace(config1, "sys.stdout", "sys.stbout")
468
469# config3 has a less subtle configuration error
470config3 = string.replace(
471 config1, "formatter=form1", "formatter=misspelled_name")
472
473def test4():
474 for i in range(4):
475 conf = globals()['config%d' % i]
476 sys.stdout.write('config%d: ' % i)
477 loggerDict = logging.getLogger().manager.loggerDict
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000478 logging._acquireLock()
479 try:
480 saved_handlers = logging._handlers.copy()
481 saved_handler_list = logging._handlerList[:]
482 saved_loggers = loggerDict.copy()
483 finally:
484 logging._releaseLock()
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000485 try:
486 fn = tempfile.mktemp(".ini")
487 f = open(fn, "w")
488 f.write(conf)
489 f.close()
490 try:
491 logging.config.fileConfig(fn)
492 except:
493 t = sys.exc_info()[0]
494 message(str(t))
495 else:
496 message('ok.')
497 os.remove(fn)
498 finally:
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000499 logging._acquireLock()
500 try:
501 logging._handlers.clear()
502 logging._handlers.update(saved_handlers)
503 logging._handlerList = saved_handler_list
504 loggerDict = logging.getLogger().manager.loggerDict
505 loggerDict.clear()
506 loggerDict.update(saved_loggers)
507 finally:
508 logging._releaseLock()
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000509
510#----------------------------------------------------------------------------
Vinay Sajip568482a2006-01-20 18:29:36 +0000511# Test 5
512#----------------------------------------------------------------------------
513
514test5_config = """
515[loggers]
516keys=root
517
518[handlers]
519keys=hand1
520
521[formatters]
522keys=form1
523
524[logger_root]
525level=NOTSET
526handlers=hand1
527
528[handler_hand1]
529class=StreamHandler
530level=NOTSET
531formatter=form1
532args=(sys.stdout,)
533
534[formatter_form1]
535class=test.test_logging.FriendlyFormatter
536format=%(levelname)s:%(name)s:%(message)s
537datefmt=
538"""
539
540class FriendlyFormatter (logging.Formatter):
541 def formatException(self, ei):
542 return "%s... Don't panic!" % str(ei[0])
543
544
545def test5():
546 loggerDict = logging.getLogger().manager.loggerDict
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000547 logging._acquireLock()
548 try:
549 saved_handlers = logging._handlers.copy()
550 saved_handler_list = logging._handlerList[:]
551 saved_loggers = loggerDict.copy()
552 finally:
553 logging._releaseLock()
Vinay Sajip568482a2006-01-20 18:29:36 +0000554 try:
555 fn = tempfile.mktemp(".ini")
556 f = open(fn, "w")
557 f.write(test5_config)
558 f.close()
559 logging.config.fileConfig(fn)
560 try:
561 raise KeyError
562 except KeyError:
563 logging.exception("just testing")
564 os.remove(fn)
565 finally:
Vinay Sajip1eb77a52006-02-09 08:31:00 +0000566 logging._acquireLock()
567 try:
568 logging._handlers.clear()
569 logging._handlers.update(saved_handlers)
570 logging._handlerList = saved_handler_list
571 loggerDict = logging.getLogger().manager.loggerDict
572 loggerDict.clear()
573 loggerDict.update(saved_loggers)
574 finally:
575 logging._releaseLock()
Vinay Sajip568482a2006-01-20 18:29:36 +0000576
577
578#----------------------------------------------------------------------------
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000579# Test Harness
580#----------------------------------------------------------------------------
581def banner(nm, typ):
582 sep = BANNER % (nm, typ)
583 sys.stdout.write(sep)
584 sys.stdout.flush()
585
Tim Peters36f7e932003-07-23 00:05:07 +0000586def test_main_inner():
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000587 rootLogger = logging.getLogger("")
588 rootLogger.setLevel(logging.DEBUG)
589 hdlr = logging.StreamHandler(sys.stdout)
590 fmt = logging.Formatter(logging.BASIC_FORMAT)
591 hdlr.setFormatter(fmt)
592 rootLogger.addHandler(hdlr)
593
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000594 # Find an unused port number
595 port = logging.handlers.DEFAULT_TCP_LOGGING_PORT
596 while port < logging.handlers.DEFAULT_TCP_LOGGING_PORT+100:
597 try:
598 tcpserver = LogRecordSocketReceiver(port=port)
599 except socket.error:
600 port += 1
601 else:
602 break
603 else:
604 raise ImportError, "Could not find unused port"
Tim Peters249c7b02006-01-29 22:50:26 +0000605
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000606
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000607 #Set up a handler such that all events are sent via a socket to the log
608 #receiver (logrecv).
609 #The handler will only be added to the rootLogger for some of the tests
Martin v. Löwis5b1e0032006-01-29 20:10:38 +0000610 shdlr = logging.handlers.SocketHandler('localhost', port)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000611
612 #Configure the logger for logrecv so events do not propagate beyond it.
613 #The sockLogger output is buffered in memory until the end of the test,
614 #and printed at the end.
615 sockOut = cStringIO.StringIO()
616 sockLogger = logging.getLogger("logrecv")
617 sockLogger.setLevel(logging.DEBUG)
618 sockhdlr = logging.StreamHandler(sockOut)
619 sockhdlr.setFormatter(logging.Formatter(
620 "%(name)s -> %(levelname)s: %(message)s"))
621 sockLogger.addHandler(sockhdlr)
622 sockLogger.propagate = 0
623
624 #Set up servers
625 threads = []
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000626 #sys.stdout.write("About to start TCP server...\n")
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000627 threads.append(threading.Thread(target=runTCP, args=(tcpserver,)))
628
629 for thread in threads:
630 thread.start()
631 try:
632 banner("log_test0", "begin")
633
Vinay Sajip6887c922004-08-04 08:29:14 +0000634 rootLogger.addHandler(shdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000635 test0()
Vinay Sajip6887c922004-08-04 08:29:14 +0000636 shdlr.close()
637 rootLogger.removeHandler(shdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000638
639 banner("log_test0", "end")
640
Vinay Sajip568482a2006-01-20 18:29:36 +0000641 for t in range(1,6):
642 banner("log_test%d" % t, "begin")
643 globals()['test%d' % t]()
644 banner("log_test%d" % t, "end")
Vinay Sajip22b25aa2006-01-16 21:24:38 +0000645
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000646 finally:
Guido van Rossum376e6362003-04-25 14:22:00 +0000647 #wait for TCP receiver to terminate
Guido van Rossum376e6362003-04-25 14:22:00 +0000648 socketDataProcessed.wait()
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000649 # ensure the server dies
650 tcpserver.abort = 1
Guido van Rossumecf0f022003-04-26 00:21:31 +0000651 for thread in threads:
Neal Norwitz55cd82f2006-02-05 08:21:08 +0000652 thread.join(2.0)
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000653 banner("logrecv output", "begin")
654 sys.stdout.write(sockOut.getvalue())
655 sockOut.close()
Vinay Sajip6887c922004-08-04 08:29:14 +0000656 sockLogger.removeHandler(sockhdlr)
657 sockhdlr.close()
Guido van Rossum2a1d5162003-01-21 21:05:22 +0000658 banner("logrecv output", "end")
659 sys.stdout.flush()
Vinay Sajip6887c922004-08-04 08:29:14 +0000660 try:
661 hdlr.close()
662 except:
663 pass
664 rootLogger.removeHandler(hdlr)
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000665
Tim Peters36f7e932003-07-23 00:05:07 +0000666def test_main():
667 import locale
668 # Set the locale to the platform-dependent default. I have no idea
669 # why the test does this, but in any case we save the current locale
670 # first so we can restore it at the end.
671 try:
672 original_locale = locale.setlocale(locale.LC_ALL)
673 locale.setlocale(locale.LC_ALL, '')
674 except (ValueError, locale.Error):
675 # this happens on a Solaris box which only supports "C" locale
676 # or a Mac OS X box which supports very little locale stuff at all
677 original_locale = None
678
Tim Peters0cdc3d82005-12-30 20:46:23 +0000679 # Save and restore the original root logger level across the tests.
680 # Otherwise, e.g., if any test using cookielib runs after test_logging,
681 # cookielib's debug-level logger tries to log messages, leading to
682 # confusing:
683 # No handlers could be found for logger "cookielib"
684 # output while the tests are running.
685 root_logger = logging.getLogger("")
686 original_logging_level = root_logger.getEffectiveLevel()
Tim Peters36f7e932003-07-23 00:05:07 +0000687 try:
688 test_main_inner()
689 finally:
Tim Peters9390dd52003-07-23 00:30:11 +0000690 if original_locale is not None:
Tim Peters36f7e932003-07-23 00:05:07 +0000691 locale.setlocale(locale.LC_ALL, original_locale)
Tim Peters0cdc3d82005-12-30 20:46:23 +0000692 root_logger.setLevel(original_logging_level)
Jeremy Hylton096d9862003-07-18 03:19:20 +0000693
Neal Norwitzb4a2df02003-01-02 14:56:39 +0000694if __name__ == "__main__":
695 sys.stdout.write("test_logging\n")
696 test_main()