utils.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. import os
  4. import re
  5. import sys
  6. from functools import wraps
  7. class inject(object):
  8. def __init__(self, **kwargs):
  9. self.kwargs = kwargs
  10. def __call__(self, fn):
  11. @wraps(fn)
  12. def wrapped(*args, **kwargs):
  13. old_trace = sys.gettrace()
  14. def trace_fn(frame, event, arg):
  15. # define a new trace_fn each time, since it needs to
  16. # call the *current* trace_fn if they're in debug mode
  17. frame.f_locals.update(self.kwargs)
  18. if old_trace:
  19. return old_trace(frame, event, arg)
  20. else:
  21. return None
  22. sys.settrace(trace_fn)
  23. try:
  24. retval = fn(*args, **kwargs)
  25. finally:
  26. sys.settrace(old_trace)
  27. return retval
  28. return wrapped
  29. def into(self, fn, *args, **kwargs):
  30. return self(fn)(*args, **kwargs)
  31. def not_allowed_in_prod(func):
  32. @wraps(func)
  33. def wrapper(*args, **kwargs):
  34. if re.match(os.environ['MY_ENV'], 'production'):
  35. raise RuntimeError('cannot import mock views in production env')
  36. return func(*args, **kwargs)
  37. return wrapper