db_tests.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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, SQLiteDatabaseNewForm
  23. from pwman.util import config
  24. from pwman.util.config import get_pass_conf
  25. from pwman.util.generator import leetlist
  26. from pwman.util.crypto_engine import CryptoEngine
  27. from pwman import default_config, set_xsel
  28. from pwman.ui import get_ui_platform
  29. from pwman.ui.tools import CMDLoop, CliMenuItem
  30. from pwman import (parser_options, get_conf_options, get_conf, set_umask)
  31. from pwman.data.database import __DB_FORMAT__
  32. import sys
  33. import unittest
  34. if sys.version_info.major > 2:
  35. from io import StringIO
  36. else:
  37. from StringIO import StringIO
  38. import os
  39. import os.path
  40. dummyfile = """
  41. [Encryption]
  42. [Readline]
  43. [Global]
  44. xsel = /usr/bin/xsel
  45. colors = yes
  46. umask = 0100
  47. cls_timeout = 5
  48. [Database]
  49. """
  50. def node_factory(username, password, url, notes, tags=None):
  51. node = NewNode()
  52. node.username = username
  53. node.password = password
  54. node.url = url
  55. node.notes = notes
  56. tags = [TagNew(tn) for tn in tags]
  57. node.tags = tags
  58. return node
  59. _saveconfig = False
  60. PwmanCliNew, OSX = get_ui_platform(sys.platform)
  61. from .test_tools import (SetupTester, DummyCallback2,
  62. DummyCallback3, DummyCallback4)
  63. testdb = os.path.join(os.path.dirname(__file__), "test.pwman.db")
  64. class DBTests(unittest.TestCase):
  65. """test everything related to db"""
  66. def setUp(self):
  67. "test that the right db instance was created"
  68. dbver = __DB_FORMAT__
  69. self.dbtype = 'SQLite'
  70. self.db = factory.create(self.dbtype, dbver, testdb)
  71. self.tester = SetupTester(dbver, testdb)
  72. self.tester.create()
  73. def test_1_db_created(self):
  74. "test that the right db instance was created"
  75. self.assertIn(self.dbtype, self.db.__class__.__name__)
  76. def test_2_db_opened(self):
  77. "db was successfuly opened"
  78. # it will have a file name associated
  79. self.assertTrue(hasattr(self.db, '_filename'))
  80. def test_3_create_node(self):
  81. "test that a node can be successfuly created"
  82. # this method does not test do_new
  83. # which is a UI method, rather we test
  84. # _db.addnodes
  85. username = u'tester'
  86. password = u'Password'
  87. url = u'example.org'
  88. notes = u'some notes'
  89. node = NewNode()
  90. node.username = username
  91. node.password = password
  92. node.url = url
  93. node.notes = notes
  94. # node = NewNode(username, password, url, notes)
  95. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  96. node.tags = tags
  97. self.db.open()
  98. self.db.addnodes([node])
  99. idx_created = node._id
  100. new_node = self.db.getnodes([idx_created])[0]
  101. for key, attr in {'password': password, 'username': username,
  102. 'url': url, 'notes': notes}.items():
  103. self.assertEqual(attr, getattr(new_node, key).decode())
  104. self.db.close()
  105. def test_4_tags(self):
  106. enc = CryptoEngine.get()
  107. got_tags = self.tester.cli._tags(enc)
  108. self.assertEqual(2, len(got_tags))
  109. def test_5_change_pass(self):
  110. enc = CryptoEngine.get()
  111. enc.callback = DummyCallback2()
  112. self.tester.cli._db.changepassword()
  113. @unittest.skip("This is broken as long as changepassword isn't working.")
  114. def test_6_db_change_pass(self):
  115. "fuck yeah, we change the password and the new dummy works"
  116. enc = CryptoEngine.get()
  117. enc.callback = DummyCallback3()
  118. self.tester.cli._db.changepassword()
  119. self.tester.cli.do_forget('')
  120. enc.callback = DummyCallback4()
  121. # TODO: this is broken!
  122. self.tester.cli.do_ls('')
  123. def test_7_db_list_tags(self):
  124. # tags are return as ecrypted strings
  125. tags = self.tester.cli._db.listtags()
  126. self.assertEqual(2, len(tags))
  127. self.tester.cli.do_filter('testing1')
  128. tags = self.tester.cli._db.listtags()
  129. self.assertEqual(2, len(tags))
  130. self.tester.cli.do_ls('')
  131. def test_8_db_remove_node(self):
  132. node = self.tester.cli._db.getnodes([1])
  133. self.tester.cli._db.removenodes(node)
  134. # create the removed node again
  135. node = NewNode()
  136. node.username = 'tester'
  137. node.password = 'Password'
  138. node.url = 'example.org'
  139. node.notes = 'some notes'
  140. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  141. node.tags = tags
  142. self.db.open()
  143. self.db.addnodes([node])
  144. def test_9_sqlite_init(self):
  145. db = SQLiteDatabaseNewForm("test")
  146. self.assertEqual("test", db._filename)
  147. #class TestDBFalseConfig(unittest.TestCase):
  148. #
  149. # def setUp(self):
  150. # # filename = default_config['Database'].pop('filename')
  151. # self.fname1 = default_config['Database'].pop('filename')
  152. # self.fname = config._conf['Database'].pop('filename')
  153. #
  154. # @unittest.skip("Legacy test. Database and file should always be given")
  155. # def test_db_missing_conf_parameter(self):
  156. # self.assertRaises(DatabaseException, factory.create,
  157. # 'SQLite', __DB_FORMAT__)
  158. #
  159. # def test_get_ui_platform(self):
  160. # uiclass, osx = get_ui_platform('windows')
  161. # self.assertFalse(osx)
  162. # self.assertEqual(uiclass.__name__, PwmanCliWinNew.__name__)
  163. # uiclass, osx = get_ui_platform('darwin')
  164. # self.assertTrue(osx)
  165. # self.assertEqual(uiclass.__name__, PwmanCliMacNew.__name__)
  166. # del(uiclass)
  167. # del(osx)
  168. #
  169. # def tearDown(self):
  170. # config.set_value('Database', 'filename', self.fname)
  171. # default_config['Database']['filename'] = self.fname1
  172. # config._conf['Database']['filename'] = self.fname
  173. class CLITests(unittest.TestCase):
  174. """
  175. test command line functionallity
  176. """
  177. def setUp(self):
  178. "test that the right db instance was created"
  179. self.dbtype = 'SQLite'
  180. self.db = factory.create(self.dbtype, __DB_FORMAT__, testdb)
  181. self.tester = SetupTester(__DB_FORMAT__, testdb)
  182. self.tester.create()
  183. def test_input(self):
  184. name = self.tester.cli.get_username(reader=lambda: u'alice')
  185. self.assertEqual(name, u'alice')
  186. def test_password(self):
  187. password = self.tester.cli.get_password(None,
  188. reader=lambda x: u'hatman')
  189. self.assertEqual(password, u'hatman')
  190. def test_random_password(self):
  191. password = self.tester.cli.get_password(None, length=7)
  192. self.assertEqual(len(password), 7)
  193. def test_random_leet_password(self):
  194. password = self.tester.cli.get_password(None, leetify=True, length=7)
  195. l_num = 0
  196. for v in leetlist.values():
  197. if v in password:
  198. l_num += 1
  199. # sometime despite all efforts, randomness dictates that no
  200. # leetifying happens ...
  201. self.assertTrue(l_num >= 0)
  202. def test_leet_password(self):
  203. password = self.tester.cli.get_password(None, leetify=True,
  204. reader=lambda x: u'HAtman')
  205. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  206. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  207. def test_get_url(self):
  208. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  209. self.assertEqual(url, u'example.com')
  210. def test_get_notes(self):
  211. notes = self.tester.cli.get_notes(reader=lambda:
  212. u'test 123\n test 456')
  213. self.assertEqual(notes, u'test 123\n test 456')
  214. def test_get_tags(self):
  215. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  216. for t in tags:
  217. self.assertIsInstance(t, TagNew)
  218. for t, n in zip(tags, u'looking glass'.split()):
  219. self.assertEqual(t.name.strip().decode(), n)
  220. # creating all the components of the node does
  221. # the node is still not added !
  222. def test_add_new_entry(self):
  223. # node = NewNode('alice', 'dough!', 'example.com',
  224. # 'lorem impsum')
  225. node = NewNode()
  226. node.username = b'alice'
  227. node.password = b'dough!'
  228. node.url = b'example.com'
  229. node.notes = b'somenotes'
  230. node.tags = b'lorem ipsum'
  231. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  232. node.tags = tags
  233. self.tester.cli._db.addnodes([node])
  234. self.tester.cli._db._cur.execute(
  235. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  236. rows = self.tester.cli._db._cur.fetchall()
  237. # by now the db should have 2 new nodes
  238. # the first one was added by test_create_node in DBTests
  239. # the second was added just now.
  240. # This will pass only when running all the tests then ...
  241. self.assertEqual(len(rows), 2)
  242. node = NewNode()
  243. node.username = b'alice'
  244. node.password = b'dough!'
  245. node.url = b'example.com'
  246. node.notes = b'somenotes'
  247. node.tags = b'lorem ipsum'
  248. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  249. node.tags = tags
  250. self.tester.cli._db.addnodes([node])
  251. def test_get_ids(self):
  252. # used by do_cp or do_open,
  253. # this spits many time could not understand your input
  254. self.assertEqual([1], self.tester.cli.get_ids('1'))
  255. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  256. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  257. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  258. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  259. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  260. def test_edit(self):
  261. node = self.tester.cli._db.getnodes([2])[0]
  262. menu = CMDLoop()
  263. menu.add(CliMenuItem("Username", self.tester.cli.get_username,
  264. node.username,
  265. node.username))
  266. menu.add(CliMenuItem("Password", self.tester.cli.get_password,
  267. node.password,
  268. node.password))
  269. menu.add(CliMenuItem("Url", self.tester.cli.get_url,
  270. node.url,
  271. node.url))
  272. menunotes = CliMenuItem("Notes",
  273. self.tester.cli.get_notes(reader=lambda:
  274. u'bla bla'),
  275. node.notes,
  276. node.notes)
  277. menu.add(menunotes)
  278. menu.add(CliMenuItem("Tags", self.tester.cli.get_tags,
  279. node.tags,
  280. node.tags))
  281. dummy_stdin = StringIO('4\n\nX')
  282. class dummy_stdin(object):
  283. def __init__(self):
  284. self.idx = -1
  285. self.ans = ['4', 'some fucking notes', 'X']
  286. def __call__(self, msg):
  287. self.idx += 1
  288. return self.ans[self.idx]
  289. dstin = dummy_stdin()
  290. menu.run(node, reader=dstin)
  291. self.tester.cli._db.editnode(2, node)
  292. def test_get_pass_conf(self):
  293. numerics, leet, s_chars = get_pass_conf(self.tester.cli.config)
  294. self.assertFalse(numerics)
  295. self.assertFalse(leet)
  296. self.assertFalse(s_chars)
  297. def test_do_tags(self):
  298. self.tester.cli.do_filter('bank')
  299. def test_do_forget(self):
  300. self.tester.cli.do_forget('')
  301. def test_do_auth(self):
  302. crypto = CryptoEngine.get()
  303. rv = crypto.authenticate('12345')
  304. self.assertTrue(rv)
  305. self.assertFalse(crypto.authenticate('WRONG'))
  306. def test_do_clear(self):
  307. self.tester.cli.do_clear('')
  308. def test_do_exit(self):
  309. self.assertTrue(self.tester.cli.do_exit(''))
  310. class FactoryTest(unittest.TestCase):
  311. def test_factory_check_db_ver(self):
  312. self.assertEquals(factory.check_db_version('SQLite', testdb), 0.5)
  313. def test_factory_check_db_file(self):
  314. factory.create('SQLite', version='0.3', filename='baz.db')
  315. self.assertEquals(factory.check_db_version('SQLite', 'baz.db'), 0.3)
  316. os.unlink('baz.db')
  317. def test_factory_create(self):
  318. db = factory.create('SQLite', filename='foo.db')
  319. db._open()
  320. self.assertTrue(os.path.exists('foo.db'))
  321. db.close()
  322. os.unlink('foo.db')
  323. self.assertIsInstance(db, SQLiteDatabaseNewForm)
  324. self.assertRaises(DatabaseException, factory.create, 'UNKNOWN')
  325. #class ConfigTest(unittest.TestCase):
  326. #
  327. # def setUp(self):
  328. # "test that the right db instance was created"
  329. # dbver = 0.4
  330. # self.dbtype = config.get_value("Database", "type")
  331. # self.db = factory.create(self.dbtype, dbver, testdb)
  332. # self.tester = SetupTester(dbver, testdb)
  333. # self.tester.create()
  334. # self.orig_config = config._conf.copy()
  335. # self.orig_config['Encryption'] = {'algorithm': 'AES'}
  336. #
  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. #
  345. # def test_config_write_with_none(self):
  346. # _filename = os.path.join(os.path.dirname(__file__),
  347. # 'testing_config')
  348. # config._file = _filename
  349. # config.save()
  350. # self.assertTrue(os.path.exists(_filename))
  351. # os.remove(_filename)
  352. # def test_write_no_permission(self):
  353. # # this test will pass if you run as root ...
  354. # # assuming you are not doing something like that
  355. # self.assertRaises(config.ConfigException, config.save,
  356. # '/root/test_config')
  357. # def test_add_default(self):
  358. # config.add_defaults({'Section1': {'name': 'value'}})
  359. # self.assertIn('Section1', config._defaults)
  360. # config._defaults.pop('Section1')
  361. # def test_get_conf(self):
  362. # cnf = config.get_conf()
  363. # cnf_keys = cnf.keys()
  364. # self.assertTrue('Encryption' in cnf_keys)
  365. # self.assertTrue('Readline' in cnf_keys)
  366. # self.assertTrue('Global' in cnf_keys)
  367. # self.assertTrue('Database' in cnf_keys)
  368. # def test_load_conf(self):
  369. # self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  370. # # Everything should be ok
  371. # config.save('TestConfig.ini')
  372. # config.load('TestConfig.ini')
  373. # let's corrupt the file
  374. # cfg = open('TestConfig.ini', 'w')
  375. # cfg.write('Corruption')
  376. # cfg.close()
  377. # self.assertRaises(config.ConfigException, config.load,
  378. # 'TestConfig.ini')
  379. # os.remove('TestConfig.ini')
  380. # def test_all_config(self):
  381. # sys.argv = ['pwman3']
  382. # default_config['Database'] = {'type': '',
  383. # 'filename': ''}
  384. # _save_conf = config._conf.copy()
  385. # config._conf = {}
  386. # with open('dummy.conf', 'w') as dummy:
  387. # dummy.write(dummyfile)
  388. # sys.argv = ['pwman3', '-d', '', '-c', 'dummy.conf']
  389. # p2 = parser_options()
  390. # args = p2.parse_args()
  391. # self.assertRaises(Exception, get_conf_options, args, False)
  392. # config._conf = _save_conf.copy()
  393. # os.unlink('dummy.conf')
  394. # def test_set_xsel(self):
  395. # set_xsel(config, False)
  396. # set_xsel(config, True)
  397. # if sys.platform == 'linux2':
  398. # self.assertEqual(None, config._conf['Global']['xsel'])
  399. # def test_get_conf_file(self):
  400. # Args = namedtuple('args', 'cfile')
  401. # args = Args(cfile='nosuchfile')
  402. # setting the default
  403. # in case the user specifies cfile as command line option
  404. # and that file does not exist!
  405. # foo = config._conf.copy()
  406. # get_conf_file(args)
  407. # args.cfile does not exist, hence the config values
  408. # should be the same as in the defaults
  409. # config.set_config(foo)
  410. # def test_get_conf_options(self):
  411. # Args = namedtuple('args', 'cfile, dbase, algo')
  412. # args = Args(cfile='nosuchfile', dbase='dummy.db', algo='AES')
  413. # self.assertRaises(Exception, get_conf_options, (args, 'False'))
  414. # config._defaults['Database']['type'] = 'SQLite'
  415. # # config._conf['Database']['type'] = 'SQLite'
  416. # xsel, dbtype = get_conf_options(args, 'True')
  417. # self.assertEqual(dbtype, 'SQLite')
  418. # def test_set_conf(self):
  419. # set_conf_f = getattr(config, 'set_conf')
  420. # private_conf = getattr(config, '_conf')
  421. # set_conf_f({'Config': 'OK'})
  422. # self.assertDictEqual({'Config': 'OK'}, config._conf)
  423. # config._conf = private_conf
  424. # def test_umask(self):
  425. # config._defaults = {'Global': {}}
  426. # self.assertRaises(config.ConfigException, set_umask, config)
  427. # def tearDown(self):
  428. # config._conf = self.orig_config.copy()
  429. if __name__ == '__main__':
  430. # make sure we use local pwman
  431. sys.path.insert(0, os.getcwd())
  432. # check if old DB exists, if so remove it.
  433. # excuted only once when invoked upon import or
  434. # upon run
  435. SetupTester().clean()
  436. unittest.main(verbosity=1, failfast=True)