db_tests.py 11 KB

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