简体   繁体   中英

Mocking “sleep”

I am writing an application that would asynchronously trigger some events. The test looks like this: set everything up, sleep for sometime, check that event has triggered.

However because of that waiting the test takes quite a time to run - I'm waiting for about 10 seconds on every test. I feel that my tests are slow - there are other places where I can speed them up, but this sleeping seems the most obvious place to speed it up.

What would be the correct way to eliminate that sleep? Is there some way to cheat datetime or something like that?

The application is a tornado-based web app and async events are triggered with IOLoop, so I don't have a way to directly trigger it myself.

Edit: more details.

The test is a kind of integration test, where I am willing to mock the 3rd party code, but don't want to directly trigger my own code.

The test is to verify that a certain message is sent using websocket and is processed correctly in the browser. Message is sent after a certain timeout which is started at the moment the client connects to the websocket handler. The timeout value is taken as a difference between datetime.now() at the moment of connection and a value in database. The value is artificially set to be datetime.now() - 5 seconds before using selenium to request the page. Since loading the page requires some time and could be a bit random on different machines I don't think reducing the 5 seconds time gap would be wise. Loading the page after timeout will produce a different result (no websocket message should be sent).

So the problem is to somehow force tornado's IOLoop to send the message at any moment after the websocket is connected - if that happened in 0.5 seconds after setting the database value, 4.5 seconds left to wait and I want to try and eliminate that delay.

Two obvious places to mock are IOLoop itself and datetime.now(). the question is now which one I should monkey-patch and how.

I you want to mock sleep then you must not use it directly in your application's code. I would create a class method like System.sleep() and use this in your application. System.sleep() can be mocked then.

Use the built in tornado testing tools . Each test gets it's own IOLoop, and you use self.stop and self.wait to get results from it, eg (from the docs):

    client = AsyncHTTPClient(self.io_loop)
    # call self.stop on fetch completion
    client.fetch("http://www.tornadoweb.org/", self.stop)
    response = self.wait()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM