db_tests.py 15 KB

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