views:

635

answers:

1

I have a class that I wish to test via SimpleXMLRPCServer in python. The way I have my unit test set up is that I create a new thread, and start SimpleXMLRPCServer in that. Then I run all the test, and finally shut down.

This is my ServerThread:

class ServerThread(Thread):
    running = True
    def run(self):
        self.server = #Creates and starts SimpleXMLRPCServer

        while (self.running):
            self.server.handle_request()

    def stop(self):
        self.running = False
        self.server.server_close()

The problem is, that calling ServerThread.stop(), followed by Thread.stop() and Thread.join() will not cause the thread to stop properly if it's already waiting for a request in handle_request. And since there doesn't seem to be any interrupt or timeout mechanisms here that I can use, I am at a loss for how I can cleanly shut down the server thread.

+1  A: 

Two suggestions.

Suggestion One is to use a separate process instead of a separate thread.

  • Create a stand-alone XMLRPC server program.

  • Start it with subprocess.Popen().

  • Kill it when the test is done. In standard OS's (not Windows) the kill works nicely. In Windows, however, there's no trivial kill function, but there are recipes for this.

The other suggestion is to have a function in your XMLRPC server which causes server self-destruction. You define a function that calls sys.exit() or os.abort() or raises a similar exception that will stop the process.

S.Lott
I'll keep this method in mind for the future. I prefer cross-platform solutions so the shutdown method seems most reasonable. I fixed it by sending a dummy request that will terminate the thread as self.running will be false.
Staale
A subprocess is cross-platform. A subprocess PLUS the self-destruct method works the best.
S.Lott