Last active
August 13, 2019 05:14
-
-
Save hildensia/c9ae39ed7c1c06ac3cd3 to your computer and use it in GitHub Desktop.
Fail a unittest after X seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import signal | |
| import unittest | |
| from time import sleep | |
| class TimeoutException(Exception): | |
| pass | |
| def signal_handler(signum, frame): | |
| raise TimeoutException | |
| class FailAfter(object): | |
| def __init__(self, seconds): | |
| self.seconds = seconds | |
| def __call__(self, f): | |
| def timed_f(*args, **kwargs): | |
| res = None | |
| signal.signal(signal.SIGALRM, signal_handler) | |
| signal.alarm(self.seconds) | |
| try: | |
| res = f(*args, **kwargs) | |
| except TimeoutException: | |
| args[0].fail() | |
| signal.alarm(0) | |
| return res | |
| return timed_f | |
| class Test(unittest.TestCase): | |
| @FailAfter(seconds=10) | |
| def test_something(self): | |
| while True: | |
| sleep(1) | |
| print("bla") | |
| @FailAfter(2) | |
| def test_something_fast(self): | |
| self.assertTrue(1==1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment