view lemuriformes/test_server.py @ 15:0d1b8bb1d97b

SQL + data related functionality
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:16:52 -0800
parents
children
line wrap: on
line source

"""
mock server for testing purposes
"""

# see https://realpython.com/blog/python/testing-third-party-apis-with-mock-servers/

# TODO:
# - python3 compatability
# - use multiprocessing as threading does not allow hangin thread deletion
from BaseHTTPServer import HTTPServer
from threading import Thread
from .port import get_free_port


class MockServer(HTTPServer):

    hostname = 'localhost'

    def __init__(self, handler):
        HTTPServer.__init__(self,
                            (self.hostname, get_free_port()),
                            handler)
        self.thread = None

    def base_url(self):
        return 'http://{0}:{1}/'.format(*self.server_address)

    def start_thread(self):
        self.thread = Thread(target=self.serve_forever)
        self.thread.setDaemon(True)
        self.thread.start()

    def stop_thread(self):
        raise NotImplementedError('TODO')

    def __enter__(self):
        self.start_thread()
        return self  # or perhaps `self.thread`?

    def __exit__(self, *args):
        pass   # nothing to do? really?