utils.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. """GRASS Python testing framework utilities (general and test-specific)
  3. Copyright (C) 2014 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS GIS
  6. for details.
  7. :authors: Vaclav Petras
  8. """
  9. import os
  10. import sys
  11. import shutil
  12. import errno
  13. def ensure_dir(directory):
  14. """Create all directories in the given path if needed."""
  15. if not os.path.exists(directory):
  16. os.makedirs(directory)
  17. def silent_rmtree(filename):
  18. """Remove the file but do nothing if file does not exist."""
  19. try:
  20. shutil.rmtree(filename)
  21. except OSError as e:
  22. # errno.ENOENT is "No such file or directory"
  23. # re-raise if a different error occured
  24. if e.errno != errno.ENOENT:
  25. raise
  26. def do_doctest_gettext_workaround():
  27. """Setups environment for doing a doctest with gettext usage.
  28. When using gettext with dynamically defined underscore function
  29. (``_("For translation")``), doctest does not work properly. One option is
  30. to use `import as` instead of dynamically defined underscore function but
  31. this would require change all modules which are used by tested module.
  32. This should be considered for the future. The second option is to define
  33. dummy underscore function and one other function which creates the right
  34. environment to satisfy all. This is done by this function.
  35. """
  36. def new_displayhook(string):
  37. """A replacement for default `sys.displayhook`"""
  38. if string is not None:
  39. sys.stdout.write("%r\n" % (string,))
  40. def new_translator(string):
  41. """A fake gettext underscore function."""
  42. return string
  43. sys.displayhook = new_displayhook
  44. import __builtin__
  45. __builtin__._ = new_translator
  46. _MAX_LENGTH = 80
  47. # taken from unittest.util (Python 2.7) since it is not part of API
  48. # but we need it for the same reason as it is used un unittest's TestCase
  49. def safe_repr(obj, short=False):
  50. try:
  51. result = repr(obj)
  52. except Exception:
  53. result = object.__repr__(obj)
  54. if not short or len(result) < _MAX_LENGTH:
  55. return result
  56. return result[:_MAX_LENGTH] + ' [truncated]...'