db_tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. 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. def test_6_db_change_pass(self):
  116. "fuck yeah, we change the password and the new dummy works"
  117. enc = CryptoEngine.get()
  118. enc.callback = DummyCallback3()
  119. self.tester.cli._db.changepassword()
  120. self.tester.cli.do_forget('')
  121. enc.callback = DummyCallback4()
  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. def setUp(self):
  149. # filename = default_config['Database'].pop('filename')
  150. self.fname1 = default_config['Database'].pop('filename')
  151. self.fname = config._conf['Database'].pop('filename')
  152. def test_db_missing_conf_parameter(self):
  153. self.assertRaises(DatabaseException, factory.create,
  154. 'SQLite', __DB_FORMAT__)
  155. def test_get_ui_platform(self):
  156. uiclass, osx = get_ui_platform('windows')
  157. self.assertFalse(osx)
  158. self.assertEqual(uiclass.__name__, PwmanCliWinNew.__name__)
  159. uiclass, osx = get_ui_platform('darwin')
  160. self.assertTrue(osx)
  161. self.assertEqual(uiclass.__name__, PwmanCliMacNew.__name__)
  162. del(uiclass)
  163. del(osx)
  164. def tearDown(self):
  165. config.set_value('Database', 'filename', self.fname)
  166. default_config['Database']['filename'] = self.fname1
  167. config._conf['Database']['filename'] = self.fname
  168. class CLITests(unittest.TestCase):
  169. """
  170. test command line functionallity
  171. """
  172. def setUp(self):
  173. "test that the right db instance was created"
  174. self.dbtype = config.get_value("Database", "type")
  175. self.db = factory.create(self.dbtype, __DB_FORMAT__)
  176. self.tester = SetupTester(__DB_FORMAT__)
  177. self.tester.create()
  178. def test_input(self):
  179. name = self.tester.cli.get_username(reader=lambda: u'alice')
  180. self.assertEqual(name, u'alice')
  181. def test_password(self):
  182. password = self.tester.cli.get_password(None,
  183. reader=lambda x: u'hatman')
  184. self.assertEqual(password, u'hatman')
  185. def test_random_password(self):
  186. password = self.tester.cli.get_password(None, length=7)
  187. self.assertEqual(len(password), 7)
  188. def test_random_leet_password(self):
  189. password = self.tester.cli.get_password(None, leetify=True, length=7)
  190. l_num = 0
  191. for v in leetlist.values():
  192. if v in password:
  193. l_num += 1
  194. # sometime despite all efforts, randomness dictates that no
  195. # leetifying happens ...
  196. self.assertTrue(l_num >= 0)
  197. def test_leet_password(self):
  198. password = self.tester.cli.get_password(None, leetify=True,
  199. reader=lambda x: u'HAtman')
  200. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  201. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  202. def test_get_url(self):
  203. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  204. self.assertEqual(url, u'example.com')
  205. def test_get_notes(self):
  206. notes = self.tester.cli.get_notes(reader=lambda:
  207. u'test 123\n test 456')
  208. self.assertEqual(notes, u'test 123\n test 456')
  209. def test_get_tags(self):
  210. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  211. for t in tags:
  212. self.assertIsInstance(t, TagNew)
  213. for t, n in zip(tags, 'looking glass'.split()):
  214. self.assertEqual(t.name.strip(), n)
  215. # creating all the components of the node does
  216. # the node is still not added !
  217. def test_add_new_entry(self):
  218. # node = NewNode('alice', 'dough!', 'example.com',
  219. # 'lorem impsum')
  220. node = NewNode()
  221. node.username = 'alice'
  222. node.password = 'dough!'
  223. node.url = 'example.com'
  224. node.notes = 'somenotes'
  225. node.tags = 'lorem ipsum'
  226. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  227. node.tags = tags
  228. self.tester.cli._db.addnodes([node])
  229. self.tester.cli._db._cur.execute(
  230. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  231. rows = self.tester.cli._db._cur.fetchall()
  232. # by now the db should have 2 new nodes
  233. # the first one was added by test_create_node in DBTests
  234. # the second was added just now.
  235. # This will pass only when running all the tests then ...
  236. self.assertEqual(len(rows), 2)
  237. node = NewNode()
  238. node.username = 'alice'
  239. node.password = 'dough!'
  240. node.url = 'example.com'
  241. node.notes = 'somenotes'
  242. node.tags = 'lorem ipsum'
  243. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  244. node.tags = tags
  245. self.tester.cli._db.addnodes([node])
  246. def test_get_ids(self):
  247. # used by do_cp or do_open,
  248. # this spits many time could not understand your input
  249. self.assertEqual([1], self.tester.cli.get_ids('1'))
  250. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  251. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  252. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  253. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  254. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  255. def test_edit(self):
  256. node = self.tester.cli._db.getnodes([2])[0]
  257. menu = CMDLoop()
  258. menu.add(CliMenuItem("Username", self.tester.cli.get_username,
  259. node.username,
  260. node.username))
  261. menu.add(CliMenuItem("Password", self.tester.cli.get_password,
  262. node.password,
  263. node.password))
  264. menu.add(CliMenuItem("Url", self.tester.cli.get_url,
  265. node.url,
  266. node.url))
  267. menunotes = CliMenuItem("Notes",
  268. self.tester.cli.get_notes(reader=lambda:
  269. u'bla bla'),
  270. node.notes,
  271. node.notes)
  272. menu.add(menunotes)
  273. menu.add(CliMenuItem("Tags", self.tester.cli.get_tags,
  274. node.tags,
  275. node.tags))
  276. dummy_stdin = StringIO.StringIO('4\n\nX')
  277. self.assertTrue(len(dummy_stdin.readlines()))
  278. dummy_stdin.seek(0)
  279. sys.stdin = dummy_stdin
  280. menu.run(node)
  281. self.tester.cli._db.editnode(2, node)
  282. sys.stdin = sys.__stdin__
  283. def test_get_pass_conf(self):
  284. numerics, leet, s_chars = get_pass_conf()
  285. self.assertFalse(numerics)
  286. self.assertFalse(leet)
  287. self.assertFalse(s_chars)
  288. def test_do_tags(self):
  289. self.tester.cli.do_filter('bank')
  290. def test_do_forget(self):
  291. self.tester.cli.do_forget('')
  292. def test_do_auth(self):
  293. crypto = CryptoEngine.get()
  294. rv = crypto.authenticate('12345')
  295. self.assertTrue(rv)
  296. self.assertFalse(crypto.authenticate('WRONG'))
  297. def test_do_clear(self):
  298. self.tester.cli.do_clear('')
  299. def test_do_exit(self):
  300. self.assertTrue(self.tester.cli.do_exit(''))
  301. class FakeSqlite(object):
  302. def check_db_version(self):
  303. return ""
  304. class FactoryTest(unittest.TestCase):
  305. def test_factory_check_db_ver(self):
  306. self.assertEquals(factory.check_db_version('SQLite'), 0.5)
  307. def test_factory_check_db_file(self):
  308. orig_sqlite = getattr(factory, 'sqlite')
  309. factory.sqlite = FakeSqlite()
  310. self.assertEquals(factory.check_db_version('SQLite'), 0.3)
  311. factory.sqlite = orig_sqlite
  312. def test_factory_create(self):
  313. db = factory.create('SQLite', filename='foo.db')
  314. db._open()
  315. self.assertTrue(os.path.exists('foo.db'))
  316. db.close()
  317. os.unlink('foo.db')
  318. self.assertIsInstance(db, SQLiteDatabaseNewForm)
  319. self.assertRaises(DatabaseException, factory.create, 'UNKNOWN')
  320. class ConfigTest(unittest.TestCase):
  321. def setUp(self):
  322. "test that the right db instance was created"
  323. dbver = 0.4
  324. self.dbtype = config.get_value("Database", "type")
  325. self.db = factory.create(self.dbtype, dbver)
  326. self.tester = SetupTester(dbver)
  327. self.tester.create()
  328. self.orig_config = config._conf.copy()
  329. self.orig_config['Encryption'] = {'algorithm': 'AES'}
  330. def test_config_write(self):
  331. _filename = os.path.join(os.path.dirname(__file__),
  332. 'testing_config')
  333. config._file = _filename
  334. config.save(_filename)
  335. self.assertTrue(_filename)
  336. os.remove(_filename)
  337. def test_config_write_with_none(self):
  338. _filename = os.path.join(os.path.dirname(__file__),
  339. 'testing_config')
  340. config._file = _filename
  341. config.save()
  342. self.assertTrue(os.path.exists(_filename))
  343. os.remove(_filename)
  344. def test_write_no_permission(self):
  345. # this test will pass if you run as root ...
  346. # assuming you are not doing something like that
  347. self.assertRaises(config.ConfigException, config.save,
  348. '/root/test_config')
  349. def test_add_default(self):
  350. config.add_defaults({'Section1': {'name': 'value'}})
  351. self.assertIn('Section1', config._defaults)
  352. config._defaults.pop('Section1')
  353. def test_get_conf(self):
  354. cnf = config.get_conf()
  355. cnf_keys = cnf.keys()
  356. self.assertTrue('Encryption' in cnf_keys)
  357. self.assertTrue('Readline' in cnf_keys)
  358. self.assertTrue('Global' in cnf_keys)
  359. self.assertTrue('Database' in cnf_keys)
  360. def test_load_conf(self):
  361. self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  362. # Everything should be ok
  363. config.save('TestConfig.ini')
  364. config.load('TestConfig.ini')
  365. # let's corrupt the file
  366. cfg = open('TestConfig.ini', 'w')
  367. cfg.write('Corruption')
  368. cfg.close()
  369. self.assertRaises(config.ConfigException, config.load,
  370. 'TestConfig.ini')
  371. os.remove('TestConfig.ini')
  372. def test_all_config(self):
  373. sys.argv = ['pwman3']
  374. default_config['Database'] = {'type': '',
  375. 'filename': ''}
  376. _save_conf = config._conf.copy()
  377. config._conf = {}
  378. with open('dummy.conf', 'w') as dummy:
  379. dummy.write(dummyfile)
  380. sys.argv = ['pwman3', '-d', '', '-c', 'dummy.conf']
  381. p2 = parser_options()
  382. args = p2.parse_args()
  383. self.assertRaises(Exception, get_conf_options, args, False)
  384. config._conf = _save_conf.copy()
  385. os.unlink('dummy.conf')
  386. def test_set_xsel(self):
  387. set_xsel(config, False)
  388. set_xsel(config, True)
  389. if sys.platform == 'linux2':
  390. self.assertEqual(None, config._conf['Global']['xsel'])
  391. def test_get_conf_file(self):
  392. Args = namedtuple('args', 'cfile')
  393. args = Args(cfile='nosuchfile')
  394. # setting the default
  395. # in case the user specifies cfile as command line option
  396. # and that file does not exist!
  397. foo = config._conf.copy()
  398. get_conf_file(args)
  399. # args.cfile does not exist, hence the config values
  400. # should be the same as in the defaults
  401. config.set_config(foo)
  402. def test_get_conf_options(self):
  403. Args = namedtuple('args', 'cfile, dbase, algo')
  404. args = Args(cfile='nosuchfile', dbase='dummy.db', algo='AES')
  405. self.assertRaises(Exception, get_conf_options, (args, 'False'))
  406. config._defaults['Database']['type'] = 'SQLite'
  407. # config._conf['Database']['type'] = 'SQLite'
  408. xsel, dbtype = get_conf_options(args, 'True')
  409. self.assertEqual(dbtype, 'SQLite')
  410. def test_set_conf(self):
  411. set_conf_f = getattr(config, 'set_conf')
  412. private_conf = getattr(config, '_conf')
  413. set_conf_f({'Config': 'OK'})
  414. self.assertDictEqual({'Config': 'OK'}, config._conf)
  415. config._conf = private_conf
  416. def test_umask(self):
  417. config._defaults = {'Global': {}}
  418. self.assertRaises(config.ConfigException, set_umask, config)
  419. def tearDown(self):
  420. config._conf = self.orig_config.copy()