suman j
suman j

Reputation: 6980

python bottle integration tests

I have a rest api hosted using bottle web framework. I would like to run integration tests for my api. As part of the test, I would need to start a local instance of the bottle server. But run api in bottle framework blocks the execution thread. How do I create integration tests with a local instance of the server? I want to start the server during setUp and stop it after running all my tests. Is this possible with bottle web framework?

Upvotes: 1

Views: 425

Answers (1)

suman j
suman j

Reputation: 6980

I was able to do it using multi threading. If there is a better solution, I will consider it.

def setUp(self):
        from thread import start_new_thread
        start_new_thread(start_bottle,(),{})


def my_test():
   #Run the tests here which make the http call to the resources hosted using above bottle server instance

UPDATE

class TestBottleServer(object):
    """
    Starts a local instance of bottle container to run the tests against.
    """
    is_running = False

    def __init__(self, app=None, host="localhost", port=3534, debug=False, reloader=False, server="tornado"):
        self.app = app
        self.host = host
        self.port = port
        self.debug = debug
        self.reloader = reloader
        self.server = server

    def ensured_bottle_started(self):
        if TestBottleServer.is_running is False:
            start_new_thread(self.__start_bottle__, (), {})
            #Sleep is required for forked thread to initialise the app
            TestBottleServer.is_running = True
            time.sleep(1)

    def __start_bottle__(self):
        run(
            app=self.app,
            host=self.host,
            port=self.port,
            debug=self.debug,
            reloader=self.reloader,
            server=self.server)

    @staticmethod
    def restart():
        TestBottleServer.is_running = False
        TestBottleServer.ensured_bottle_started()


TEST_BOTTLE_SERVER = TestBottleServer()

Upvotes: 1

Related Questions