db_tests.py 18 KB

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