db_tests.py 15 KB

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