Skip to content

Instantly share code, notes, and snippets.

@GeeWee
Created February 22, 2019 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeeWee/bc5da4f982af4c221aa1d0b8a1a3944e to your computer and use it in GitHub Desktop.
Save GeeWee/bc5da4f982af4c221aa1d0b8a1a3944e to your computer and use it in GitHub Desktop.
def run_concurrently(times, args):
"""
Add this decorator to small pieces of code that you want to test
concurrently to make sure they don't raise exceptions when run at the
same time. E.g., some Django views that do a SELECT and then a subsequent
INSERT might fail when the INSERT assumes that the data has not changed
since the SELECT.
"""
def test_concurrently_decorator(test_func):
def wrapper():
exceptions = []
threads = []
for i in range(times):
def call_test_func(i=i):
try:
test_func(args[i])
except Exception as e:
exceptions.append(e)
raise
threads.append(threading.Thread(target=call_test_func))
for t in threads:
t.start()
for t in threads:
t.join()
if exceptions:
raise Exception('test_concurrently intercepted %s exceptions: %s' % (len(exceptions), exceptions))
return wrapper
return test_concurrently_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment