db_tests.py 15 KB

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