db_tests.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. from pwman.util.callback import Callback
  2. from pwman.util.generator import leetlist
  3. import os
  4. import os.path
  5. import sys
  6. class DummyCallback(Callback):
  7. def getinput(self, question):
  8. return '12345'
  9. def getsecret(self, question):
  10. return '12345'
  11. class DummyCallback2(Callback):
  12. def getinput(self, question):
  13. return 'newsecret'
  14. def getsecret(self, question):
  15. return 'newsecret'
  16. if 'darwin' in sys.platform: # pragma: no cover
  17. from pwman.ui.mac import PwmanCliMac as PwmanCliOld
  18. from pwman.ui.mac import PwmanCliMacNew as PwmanCliNew
  19. OSX = True
  20. elif 'win' in sys.platform: # pragma: no cover
  21. from pwman.ui.cli import PwmanCli
  22. from pwman.ui.win import PwmanCliWinNew as PwmanCliNew
  23. OSX = False
  24. else:
  25. from pwman.ui.cli import PwmanCliOld
  26. from pwman.ui.cli import PwmanCliNew
  27. OSX = False
  28. import pwman.util.config as config
  29. import pwman.data.factory
  30. from pwman.data.nodes import NewNode
  31. from pwman.data.tags import Tag, TagNew
  32. from pwman.util.crypto import CryptoEngine, CryptoBadKeyException
  33. from pwman import which, default_config
  34. from pwman.ui.cli import get_pass_conf
  35. import unittest
  36. _saveconfig = False
  37. default_config['Database'] = {'type': 'SQLite',
  38. 'filename':
  39. os.path.join(os.path.dirname(__file__),
  40. "test.pwman.db")
  41. }
  42. class SetupTester(object):
  43. def __init__(self):
  44. config.set_defaults(default_config)
  45. if not OSX:
  46. self.xselpath = which("xsel")
  47. config.set_value("Global", "xsel", self.xselpath)
  48. else:
  49. self.xselpath = "xsel"
  50. def clean(self):
  51. if os.path.exists(config.get_value('Database', 'filename')):
  52. os.remove(config.get_value('Database', 'filename'))
  53. if os.path.exists(os.path.join(os.path.dirname(__file__),
  54. 'testing_config')):
  55. os.remove(os.path.join(os.path.dirname(__file__),
  56. 'testing_config'))
  57. def create(self):
  58. dbver = 0.4
  59. dbtype = config.get_value("Database", "type")
  60. db = pwman.data.factory.create(dbtype, dbver)
  61. self.cli = PwmanCliNew(db, self.xselpath, DummyCallback)
  62. class DBTests(unittest.TestCase):
  63. """test everything related to db"""
  64. def setUp(self):
  65. "test that the right db instance was created"
  66. dbver = 0.4
  67. self.dbtype = config.get_value("Database", "type")
  68. self.db = pwman.data.factory.create(self.dbtype, dbver)
  69. self.tester = SetupTester()
  70. self.tester.create()
  71. def test_db_created(self):
  72. "test that the right db instance was created"
  73. # self.db = pwman.data.factory.create(dbtype, dbver)
  74. self.assertIn(self.dbtype, self.db.__class__.__name__)
  75. def test_db_opened(self):
  76. "db was successfuly opened"
  77. # it will have a file name associated
  78. self.assertTrue(hasattr(self.db, '_filename'))
  79. def test_create_node(self):
  80. "test that a node can be successfuly created"
  81. # this method does not test do_new
  82. # which is a UI method, rather we test
  83. # _db.addnodes
  84. username = 'tester'
  85. password = 'Password'
  86. url = 'example.org'
  87. notes = 'some notes'
  88. node = NewNode(username, password, url, notes)
  89. tags = [Tag(tn) for tn in ['testing1', 'testing2']]
  90. node.tags = tags
  91. self.db.open()
  92. self.db.addnodes([node])
  93. idx_created = node._id
  94. new_node = self.db.getnodes([idx_created])[0]
  95. for key, attr in {'password': password, 'username': username,
  96. 'url': url, 'notes': notes}.iteritems():
  97. self.assertEquals(attr, getattr(new_node, key))
  98. self.db.close()
  99. def test_tags(self):
  100. enc = CryptoEngine.get()
  101. got_tags = self.tester.cli._tags(enc)
  102. self.assertEqual(2, len(got_tags))
  103. def test_change_pass(self):
  104. self.tester.cli.callback = DummyCallback2
  105. self.assertRaises(CryptoBadKeyException,
  106. self.tester.cli._db.changepassword)
  107. class CLITests(unittest.TestCase):
  108. """
  109. test command line functionallity
  110. """
  111. def setUp(self):
  112. "test that the right db instance was created"
  113. dbver = 0.4
  114. self.dbtype = config.get_value("Database", "type")
  115. self.db = pwman.data.factory.create(self.dbtype, dbver)
  116. self.tester = SetupTester()
  117. self.tester.create()
  118. def test_input(self):
  119. name = self.tester.cli.get_username(reader=lambda: u'alice')
  120. self.assertEqual(name, u'alice')
  121. def test_password(self):
  122. password = self.tester.cli.get_password(None,
  123. reader=lambda x: u'hatman')
  124. self.assertEqual(password, u'hatman')
  125. def test_random_password(self):
  126. password = self.tester.cli.get_password(None, length=7)
  127. self.assertEqual(len(password), 7)
  128. def test_random_leet_password(self):
  129. password = self.tester.cli.get_password(None, leetify=True, length=7)
  130. l_num = 0
  131. for v in leetlist.values():
  132. if v in password:
  133. l_num += 1
  134. self.assertTrue(l_num > 0)
  135. def test_leet_password(self):
  136. password = self.tester.cli.get_password(None, leetify=True,
  137. reader=lambda x: u'HAtman')
  138. print password
  139. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  140. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  141. def test_get_url(self):
  142. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  143. self.assertEqual(url, u'example.com')
  144. def test_get_notes(self):
  145. notes = self.tester.cli.get_notes(reader=lambda:
  146. u'test 123\n test 456')
  147. self.assertEqual(notes, u'test 123\n test 456')
  148. def test_get_tags(self):
  149. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  150. for t in tags:
  151. self.assertIsInstance(t, TagNew)
  152. for t, n in zip(tags, 'looking glass'.split()):
  153. self.assertEqual(t.name.strip(), n)
  154. # creating all the components of the node does
  155. # the node is still not added !
  156. def test_add_new_entry(self):
  157. node = NewNode('alice', 'dough!', 'example.com',
  158. 'lorem impsum')
  159. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  160. node.tags = tags
  161. self.tester.cli._db.addnodes([node])
  162. self.tester.cli._db._cur.execute(
  163. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  164. rows = self.tester.cli._db._cur.fetchall()
  165. # by now the db should have 2 new nodes
  166. # the first one was added by test_create_node in DBTests
  167. # the second was added just now.
  168. # This will pass only when running all the tests than ...
  169. self.assertEqual(len(rows), 2)
  170. def test_get_ids(self):
  171. #used by do_cp or do_open,
  172. # this spits many time could not understand your input
  173. self.assertEqual([1], self.tester.cli.get_ids('1'))
  174. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  175. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  176. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  177. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  178. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  179. def test_get_pass_conf(self):
  180. numerics, leet, s_chars = get_pass_conf()
  181. self.assertFalse(numerics)
  182. self.assertFalse(leet)
  183. self.assertFalse(s_chars)
  184. def test_do_exit(self):
  185. self.assertTrue(self.tester.cli.do_exit(''))
  186. class ConfigTest(unittest.TestCase):
  187. def setUp(self):
  188. "test that the right db instance was created"
  189. dbver = 0.4
  190. self.dbtype = config.get_value("Database", "type")
  191. self.db = pwman.data.factory.create(self.dbtype, dbver)
  192. self.tester = SetupTester()
  193. self.tester.create()
  194. def test_config_write(self):
  195. config.save(os.path.join(os.path.dirname(__file__), 'testing_config'))
  196. def test_config_write_with_none(self):
  197. config._file = os.path.join(os.path.dirname(__file__),
  198. 'testing_config')
  199. config.save()
  200. def test_write_no_permission(self):
  201. # this test will pass if you run as root ...
  202. # assuming you are not doing something like that
  203. self.assertRaises(config.ConfigException, config.save,
  204. '/root/test_config')
  205. def test_add_default(self):
  206. config.add_defaults({'Section1': {'name': 'value'}})
  207. self.assertIn('Section1', config._defaults)
  208. def test_get_conf(self):
  209. cnf = config.get_conf()
  210. cnf_keys = cnf.keys()
  211. self.assertTrue('Encryption' in cnf_keys)
  212. self.assertTrue('Readline' in cnf_keys)
  213. self.assertTrue('Global' in cnf_keys)
  214. self.assertTrue('Database' in cnf_keys)
  215. def test_load_conf(self):
  216. self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  217. # Everything should be ok
  218. config.save('TestConfig.ini')
  219. config.load('TestConfig.ini')
  220. # let's corrupt the file
  221. cfg = open('TestConfig.ini', 'w')
  222. cfg.write('Corruption')
  223. cfg.close()
  224. self.assertRaises(config.ConfigException, config.load,
  225. 'TestConfig.ini')
  226. os.remove('TestConfig.ini')