test_mod_random.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: Rupesh Tare <rupesht@saltstack.com>
  4. """
  5. # Import Python Libs
  6. from __future__ import absolute_import, print_function, unicode_literals
  7. # Import Salt Libs
  8. import salt.modules.mod_random as mod_random
  9. import salt.utils.pycrypto
  10. from salt.exceptions import SaltInvocationError
  11. # Import 3rd-party libs
  12. from salt.ext import six
  13. # Import Salt Testing Libs
  14. from tests.support.mixins import LoaderModuleMockMixin
  15. from tests.support.mock import patch
  16. from tests.support.unit import TestCase, skipIf
  17. def _test_hashlib():
  18. try:
  19. import hashlib
  20. except ImportError:
  21. return False
  22. if six.PY2:
  23. algorithms_attr_name = "algorithms"
  24. else:
  25. algorithms_attr_name = "algorithms_guaranteed"
  26. if not hasattr(hashlib, algorithms_attr_name):
  27. return False
  28. else:
  29. return True
  30. SUPPORTED_HASHLIB = _test_hashlib()
  31. @skipIf(not SUPPORTED_HASHLIB, "Hashlib does not contain needed functionality")
  32. class ModrandomTestCase(TestCase, LoaderModuleMockMixin):
  33. """
  34. Test cases for salt.modules.mod_random
  35. """
  36. def setup_loader_modules(self):
  37. return {mod_random: {}}
  38. def test_hash(self):
  39. """
  40. Test for Encodes a value with the specified encoder.
  41. """
  42. self.assertEqual(mod_random.hash("value")[0:4], "ec2c")
  43. self.assertRaises(SaltInvocationError, mod_random.hash, "value", "algorithm")
  44. def test_str_encode(self):
  45. """
  46. Test for The value to be encoded.
  47. """
  48. self.assertRaises(SaltInvocationError, mod_random.str_encode, "None", "abc")
  49. self.assertRaises(SaltInvocationError, mod_random.str_encode, None)
  50. if six.PY2:
  51. self.assertEqual(mod_random.str_encode("A"), "QQ==\n")
  52. else:
  53. # We're using the base64 module which does not include the trailing new line
  54. self.assertEqual(mod_random.str_encode("A"), "QQ==")
  55. def test_get_str(self):
  56. """
  57. Test for Returns a random string of the specified length.
  58. """
  59. with patch.object(salt.utils.pycrypto, "secure_password", return_value="A"):
  60. self.assertEqual(mod_random.get_str(), "A")
  61. def test_shadow_hash(self):
  62. """
  63. Test for Generates a salted hash suitable for /etc/shadow.
  64. """
  65. with patch.object(salt.utils.pycrypto, "gen_hash", return_value="A"):
  66. self.assertEqual(mod_random.shadow_hash(), "A")