test_utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from grass.gunittest.case import TestCase
  4. from grass.gunittest.main import test
  5. from grass.script import utils
  6. def change_environ(**envs):
  7. NOT_FOUND = 'Not found!'
  8. original_envs = {k: os.environ.get(k, NOT_FOUND) for k in envs.keys()}
  9. def work_with_env(func):
  10. def wrap_func(*args, **kwargs):
  11. # modify the environment variables
  12. for k, v in envs.items():
  13. os.environ[k] = v
  14. # execute
  15. func(*args, **kwargs)
  16. # restore the environment variables
  17. for k, v in envs.items():
  18. oval = original_envs[k]
  19. if oval == NOT_FOUND:
  20. os.environ.pop(k)
  21. else:
  22. os.environ[k] = oval
  23. return wrap_func
  24. return work_with_env
  25. class TestEncode(TestCase):
  26. """Tests function `encode` that convert value to bytes."""
  27. def test_bytes(self):
  28. self.assertEqual(b'text', utils.encode(b'text'))
  29. def test_unicode(self):
  30. self.assertEqual(b'text', utils.encode(u'text'))
  31. @change_environ(LC_ALL='C')
  32. def test_bytes_LC_ALL_C(self):
  33. self.assertEqual(b'text', utils.encode(b'text'))
  34. @change_environ(LC_ALL='C')
  35. def test_unicode_LC_ALL_C(self):
  36. self.assertEqual(b'text', utils.encode(u'text'))
  37. class TestDecode(TestCase):
  38. """Tests function `encode` that convert value to unicode."""
  39. def test_bytes(self):
  40. self.assertEqual(u'text', utils.decode(b'text'))
  41. def test_unicode(self):
  42. self.assertEqual(u'text', utils.decode(u'text'))
  43. @change_environ(LC_ALL='C')
  44. def test_bytes_LC_ALL_C(self):
  45. self.assertEqual(u'text', utils.decode(b'text'))
  46. @change_environ(LC_ALL='C')
  47. def test_unicode_LC_ALL_C(self):
  48. self.assertEqual(u'text', utils.decode(u'text'))
  49. if __name__ == '__main__':
  50. test()