db_tests.py 12 KB

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