db_tests.py 14 KB

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