common.py 668 B

123456789101112131415161718192021222324
  1. from contextlib import contextmanager
  2. @contextmanager
  3. def monkeypatch(obj, attribute_name, new_value):
  4. """
  5. Like pytest's monkeypatch, but as a value manager.
  6. """
  7. old_value = getattr(obj, attribute_name)
  8. try:
  9. setattr(obj, attribute_name, new_value)
  10. yield
  11. finally:
  12. setattr(obj, attribute_name, old_value)
  13. def indent_block(text, indention=' '):
  14. """This function indents a text block with a default of four spaces."""
  15. temp = ''
  16. while text and text[-1] == '\n':
  17. temp += text[-1]
  18. text = text[:-1]
  19. lines = text.split('\n')
  20. return '\n'.join(map(lambda s: indention + s, lines)) + temp