db_tests.py 16 KB

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