utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.gunittest.utils
  3. @brief GRASS Python testing framework utilities (general and test-specific)
  4. Copyright (C) 2014 by the GRASS Development Team
  5. This program is free software under the GNU General Public
  6. License (>=v2). Read the file COPYING that comes with GRASS GIS
  7. for details.
  8. @author Vaclav Petras
  9. """
  10. import os
  11. import sys
  12. import shutil
  13. import errno
  14. def ensure_dir(directory):
  15. """Create all directories in the given path if needed."""
  16. if not os.path.exists(directory):
  17. os.makedirs(directory)
  18. def silent_rmtree(filename):
  19. """Remove the file but do nothing if file does not exist."""
  20. try:
  21. shutil.rmtree(filename)
  22. except OSError as e:
  23. # errno.ENOENT is "No such file or directory"
  24. # re-raise if a different error occured
  25. if e.errno != errno.ENOENT:
  26. raise
  27. def do_doctest_gettext_workaround():
  28. """Setups environment for doing a doctest with gettext usage.
  29. When using gettext with dynamically defined underscore function
  30. (``_("For translation")``), doctest does not work properly. One option is
  31. to use `import as` instead of dynamically defined underscore function but
  32. this would require change all modules which are used by tested module.
  33. This should be considered for the future. The second option is to define
  34. dummy underscore function and one other function which creates the right
  35. environment to satisfy all. This is done by this function.
  36. """
  37. def new_displayhook(string):
  38. """A replacement for default `sys.displayhook`"""
  39. if string is not None:
  40. sys.stdout.write("%r\n" % (string,))
  41. def new_translator(string):
  42. """A fake gettext underscore function."""
  43. return string
  44. sys.displayhook = new_displayhook
  45. import __builtin__
  46. __builtin__._ = new_translator