db_tests.py 16 KB

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