3

I have socketserver set up to run some unittests, and it's outputting its log to the console.

Is there a way to disable this?

Here's roughly the code I'm running:

class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True


class ScraperExampleTest(unittest.TestCase):
    def setUp(self):
        # Due to requests not supporting the 'file' scheme, we are forced to run
        # our own server. See: https://github.com/kennethreitz/requests/issues/847
        Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
        httpd = TestServer(('', PORT), Handler)
        httpd_thread = threading.Thread(target=httpd.serve_forever)
        httpd_thread.setDaemon(True)
        httpd_thread.start()
mlissner
  • 17,359
  • 18
  • 106
  • 169

2 Answers2

12

The printout doesn't originate from the TCPServer but from the SimpleHTTPRequestHandler, or more precisely it's parent: BaseHTTPRequestHandler. You can change the behaviour by creating your own handler and overloading:

def log_message(self, format, *args)

Something like this should work:

class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True 
    logging = False

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def log_message(self, format, *args):
        if self.server.logging:
            SimpleHTTPServer.SimpleHTTPRequestHandler.log_message(self, format, *args)
jamt
  • 181
  • 1
  • 5
1

A common trick to avoid console output in Python is to redirect it. sys.stdout can be replaced by any open [for writing] text file.

import sys
f = open("myLog.txt", "w")
sto = sys.stdout
sys.stdout = f
#...

#... when done with tests

# restablish the orignal console output
sys.stdout = sto
fclose(f)
mjv
  • 73,152
  • 14
  • 113
  • 156
  • I don't love this, but I tried it out by adding `sys.stdout = open('/dev/null', 'w')` to the setUp method. Didn't change the output at all. – mlissner May 11 '13 at 21:58
  • Could it be that the output sent to the console effectively comes from writes to stderr rather than stdout? Try redirecting stderr as well. – mjv May 12 '13 at 03:21
  • Redirecting stderr works, but it's so much of a hack that I can't endorse it. If the tests fail, I'll get no output. That's worse than too much output during success. – mlissner May 17 '13 at 19:09