You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

220 lines
7.6 KiB

8 years ago
8 years ago
  1. # -*- coding: utf-8 -*-
  2. from odoo.tests.common import TransactionCase
  3. from odoo.tools.config import config
  4. from odoo.exceptions import ValidationError
  5. import logging
  6. _logger = logging.getLogger(__name__)
  7. try:
  8. from cryptography.fernet import Fernet
  9. except ImportError as err:
  10. _logger.debug(err)
  11. class TestKeychain(TransactionCase):
  12. def setUp(self):
  13. super(TestKeychain, self).setUp()
  14. self.keychain = self.env['keychain.account']
  15. config['keychain_key'] = Fernet.generate_key()
  16. self.old_running_env = config.get('running_env', '')
  17. config['running_env'] = None
  18. def _init_data(self):
  19. return {
  20. "c": True,
  21. "a": "b",
  22. "d": "",
  23. }
  24. def _validate_data(self, data):
  25. return 'c' in data
  26. keychain_clss = self.keychain.__class__
  27. keychain_clss._keychain_test_init_data = _init_data
  28. keychain_clss._keychain_test_validate_data = _validate_data
  29. self.keychain._fields['namespace'].selection.append(
  30. ('keychain_test', 'test')
  31. )
  32. def tearDown(self):
  33. config['running_env'] = self.old_running_env
  34. return super(TestKeychain, self).tearDown()
  35. def _create_account(self):
  36. vals = {
  37. "name": "test",
  38. "namespace": "keychain_test",
  39. "login": "test",
  40. "technical_name": "keychain.test"
  41. }
  42. return self.keychain.create(vals)
  43. def test_password(self):
  44. """It should encrypt passwords."""
  45. account = self._create_account()
  46. passwords = ('', '12345', 'djkqfljfqm', u""""'(§è!ç""")
  47. for password in passwords:
  48. account.clear_password = password
  49. account._inverse_set_password()
  50. self.assertTrue(account.clear_password != account.password)
  51. self.assertEqual(account.get_password(), password)
  52. def test_wrong_key(self):
  53. """It should raise an exception when encoded key != decoded."""
  54. account = self._create_account()
  55. password = 'urieapocq'
  56. account.clear_password = password
  57. account._inverse_set_password()
  58. config['keychain_key'] = Fernet.generate_key()
  59. try:
  60. account.get_password()
  61. self.assertTrue(False, 'It should not work with another key')
  62. except Warning as err:
  63. self.assertTrue(True, 'It should raise a Warning')
  64. self.assertTrue(
  65. 'has been encrypted with a diff' in str(err),
  66. 'It should display the right msg')
  67. else:
  68. self.assertTrue(False, 'It should raise a Warning')
  69. def test_no_key(self):
  70. """It should raise an exception when no key is set."""
  71. account = self._create_account()
  72. del config.options['keychain_key']
  73. with self.assertRaises(Warning) as err:
  74. account.clear_password = 'aiuepr'
  75. account._inverse_set_password()
  76. self.assertTrue(False, 'It should not work without key')
  77. self.assertTrue(
  78. 'Use a key similar to' in str(err.exception),
  79. 'It should display the right msg')
  80. def test_badly_formatted_key(self):
  81. """It should raise an exception when key is not acceptable format."""
  82. account = self._create_account()
  83. config['keychain_key'] = ""
  84. with self.assertRaises(Warning):
  85. account.clear_password = 'aiuepr'
  86. account._inverse_set_password()
  87. self.assertTrue(False, 'It should not work missing formated key')
  88. self.assertTrue(True, 'It shoud raise a ValueError')
  89. def test_retrieve_env(self):
  90. """Retrieve env should always return False at the end"""
  91. config['running_env'] = False
  92. self.assertListEqual(self.keychain._retrieve_env(), [False])
  93. config['running_env'] = 'dev'
  94. self.assertListEqual(self.keychain._retrieve_env(), ['dev', False])
  95. config['running_env'] = 'prod'
  96. self.assertListEqual(self.keychain._retrieve_env(), ['prod', False])
  97. def test_multienv(self):
  98. """Encrypt with dev, decrypt with dev."""
  99. account = self._create_account()
  100. config['keychain_key_dev'] = Fernet.generate_key()
  101. config['keychain_key_prod'] = Fernet.generate_key()
  102. config['running_env'] = 'dev'
  103. account.clear_password = 'abc'
  104. account._inverse_set_password()
  105. self.assertEqual(
  106. account.get_password(),
  107. 'abc', 'Should work with dev')
  108. config['running_env'] = 'prod'
  109. with self.assertRaises(Warning):
  110. self.assertEqual(
  111. account.get_password(),
  112. 'abc', 'Should not work with prod key')
  113. def test_multienv_blank(self):
  114. """Encrypt with blank, decrypt for all."""
  115. account = self._create_account()
  116. config['keychain_key'] = Fernet.generate_key()
  117. config['keychain_key_dev'] = Fernet.generate_key()
  118. config['keychain_key_prod'] = Fernet.generate_key()
  119. config['running_env'] = ''
  120. account.clear_password = 'abc'
  121. account._inverse_set_password()
  122. self.assertEqual(
  123. account.get_password(),
  124. 'abc', 'Should work with dev')
  125. config['running_env'] = 'prod'
  126. self.assertEqual(
  127. account.get_password(),
  128. 'abc', 'Should work with prod')
  129. def test_multienv_force(self):
  130. """Set the env on the record"""
  131. account = self._create_account()
  132. account.environment = 'prod'
  133. config['keychain_key'] = Fernet.generate_key()
  134. config['keychain_key_dev'] = Fernet.generate_key()
  135. config['keychain_key_prod'] = Fernet.generate_key()
  136. config['running_env'] = ''
  137. account.clear_password = 'abc'
  138. account._inverse_set_password()
  139. with self.assertRaises(Warning):
  140. self.assertEqual(
  141. account.get_password(),
  142. 'abc', 'Should not work with dev')
  143. config['running_env'] = 'prod'
  144. self.assertEqual(
  145. account.get_password(),
  146. 'abc', 'Should work with prod')
  147. def test_wrong_json(self):
  148. """It should raise an exception when data is not valid json."""
  149. account = self._create_account()
  150. wrong_jsons = ("{'hi':'o'}", "{'oq", '[>}')
  151. for json in wrong_jsons:
  152. with self.assertRaises(ValidationError) as err:
  153. account.write({"data": json})
  154. self.assertTrue(
  155. False,
  156. 'Should not validate baddly formatted json')
  157. self.assertTrue(
  158. 'Data should be a valid JSON' in str(err.exception),
  159. 'It should raise a ValidationError')
  160. def test_invalid_json(self):
  161. """It should raise an exception when data don't pass _validate_data."""
  162. account = self._create_account()
  163. invalid_jsons = ('{}', '{"hi": 1}')
  164. for json in invalid_jsons:
  165. with self.assertRaises(ValidationError) as err:
  166. account.write({"data": json})
  167. self.assertTrue(
  168. 'Data not valid' in str(err.exception),
  169. 'It should raise a ValidationError')
  170. def test_valid_json(self):
  171. """It should work with valid data."""
  172. account = self._create_account()
  173. valid_jsons = ('{"c": true}', '{"c": 1}', '{"a": "o", "c": "b"}')
  174. for json in valid_jsons:
  175. try:
  176. account.write({"data": json})
  177. self.assertTrue(True, 'Should validate json')
  178. except:
  179. self.assertTrue(False, 'It should validate a good json')