سؤال

I want to use monkey patching to change all statements such as time.sleep(5) to myServer.sleep(5). How can I realize it? Thank you very much!

import test
import subprocess
import ast
import os
import time
import sys

if __name__ == "__main__":

    def insomniac(duration):
        pass  # don't sleep

    _original_sleep = time.sleep
    time.sleep = insomniac

    def dont_write(stuff):
        pass  # don't write

    _original_write = sys.stdout.write
    sys.stdout.write = dont_write

    execfile("test.py")

    exit(0)
هل كانت مفيدة؟

المحلول

If your focus is on testing, i.e. you want to ensure that a callable in some external library out of your control is called in a specific way, there are testing libraries that can help you with this, such as mock. It can be pretty involving to set all those things up correctly so when I do coding I typically try to structure my code in a way that minimizes the usage of mocks.

Take a look at the documentation for mock if you really want to get your toes wet towards this direction. While at this, you probably should formalize your testing techniques to make use of unitttest. If you are lost, Writing unit tests in Python: How do I start?.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top