db_tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 import CryptoEngine, CryptoBadKeyException
  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_db_created(self):
  76. "test that the right db instance was created"
  77. self.assertIn(self.dbtype, self.db.__class__.__name__)
  78. def test_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_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 = 'tester'
  88. password = 'Password'
  89. url = 'example.org'
  90. notes = 'some notes'
  91. # node = NewNode(username, password, url, notes)
  92. node = NewNode()
  93. node.username = username
  94. node.password = password
  95. node.url = url
  96. node.notes = notes
  97. # node = NewNode(username, password, url, notes)
  98. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  99. node.tags = tags
  100. self.db.open()
  101. self.db.addnodes([node])
  102. idx_created = node._id
  103. new_node = self.db.getnodes([idx_created])[0]
  104. for key, attr in {'password': password, 'username': username,
  105. 'url': url, 'notes': notes}.iteritems():
  106. self.assertEquals(attr, getattr(new_node, key))
  107. self.db.close()
  108. def test_tags(self):
  109. enc = CryptoEngine.get()
  110. got_tags = self.tester.cli._tags(enc)
  111. self.assertEqual(2, len(got_tags))
  112. def test_change_pass(self):
  113. enc = CryptoEngine.get()
  114. enc._callback = DummyCallback2()
  115. self.assertRaises(CryptoBadKeyException,
  116. self.tester.cli._db.changepassword)
  117. def test_db_change_pass(self):
  118. "fuck yeah, we change the password and the new dummy works"
  119. enc = CryptoEngine.get()
  120. enc._callback = DummyCallback3()
  121. self.tester.cli._db.changepassword()
  122. self.tester.cli.do_forget('')
  123. enc._callback = DummyCallback4()
  124. self.tester.cli.do_ls('')
  125. def test_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_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_sqlite_init(self):
  147. db = SQLiteDatabaseNewForm("test")
  148. self.assertEquals("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, 'looking glass'.split()):
  216. self.assertEqual(t.name.strip(), 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 = 'alice'
  224. node.password = 'dough!'
  225. node.url = 'example.com'
  226. node.notes = 'somenotes'
  227. node.tags = '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 = 'alice'
  241. node.password = 'dough!'
  242. node.url = 'example.com'
  243. node.notes = 'somenotes'
  244. node.tags = '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.StringIO('4\n\nX')
  279. self.assertTrue(len(dummy_stdin.readlines()))
  280. dummy_stdin.seek(0)
  281. sys.stdin = dummy_stdin
  282. menu.run(node)
  283. self.tester.cli._db.editnode(2, node)
  284. sys.stdin = sys.__stdin__
  285. def test_get_pass_conf(self):
  286. numerics, leet, s_chars = get_pass_conf()
  287. self.assertFalse(numerics)
  288. self.assertFalse(leet)
  289. self.assertFalse(s_chars)
  290. def test_do_tags(self):
  291. self.tester.cli.do_filter('bank')
  292. def test_do_forget(self):
  293. self.tester.cli.do_forget('')
  294. def test_do_auth(self):
  295. crypto = CryptoEngine.get()
  296. crypto.auth('12345')
  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. os.unlink('foo.db')
  317. self.assertIsInstance(db, SQLiteDatabaseNewForm)
  318. self.assertRaises(DatabaseException, factory.create, 'UNKNOWN')
  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. self.orig_config = config._conf.copy()
  328. self.orig_config['Encryption'] = {'algorithm': 'AES'}
  329. def test_config_write(self):
  330. _filename = os.path.join(os.path.dirname(__file__),
  331. 'testing_config')
  332. config._file = _filename
  333. config.save(_filename)
  334. self.assertTrue(_filename)
  335. os.remove(_filename)
  336. def test_config_write_with_none(self):
  337. _filename = os.path.join(os.path.dirname(__file__),
  338. 'testing_config')
  339. config._file = _filename
  340. config.save()
  341. self.assertTrue(os.path.exists(_filename))
  342. os.remove(_filename)
  343. def test_write_no_permission(self):
  344. # this test will pass if you run as root ...
  345. # assuming you are not doing something like that
  346. self.assertRaises(config.ConfigException, config.save,
  347. '/root/test_config')
  348. def test_add_default(self):
  349. config.add_defaults({'Section1': {'name': 'value'}})
  350. self.assertIn('Section1', config._defaults)
  351. config._defaults.pop('Section1')
  352. def test_get_conf(self):
  353. cnf = config.get_conf()
  354. cnf_keys = cnf.keys()
  355. self.assertTrue('Encryption' in cnf_keys)
  356. self.assertTrue('Readline' in cnf_keys)
  357. self.assertTrue('Global' in cnf_keys)
  358. self.assertTrue('Database' in cnf_keys)
  359. def test_load_conf(self):
  360. self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  361. # Everything should be ok
  362. config.save('TestConfig.ini')
  363. config.load('TestConfig.ini')
  364. # let's corrupt the file
  365. cfg = open('TestConfig.ini', 'w')
  366. cfg.write('Corruption')
  367. cfg.close()
  368. self.assertRaises(config.ConfigException, config.load,
  369. 'TestConfig.ini')
  370. os.remove('TestConfig.ini')
  371. def test_all_config(self):
  372. sys.argv = ['pwman3']
  373. default_config['Database'] = {'type': '',
  374. 'filename': ''}
  375. _save_conf = config._conf.copy()
  376. config._conf = {}
  377. with open('dummy.conf', 'w') as dummy:
  378. dummy.write(dummyfile)
  379. sys.argv = ['pwman3', '-d', '', '-c', 'dummy.conf']
  380. p2 = parser_options()
  381. args = p2.parse_args()
  382. self.assertRaises(Exception, get_conf_options, args, False)
  383. config._conf = _save_conf.copy()
  384. os.unlink('dummy.conf')
  385. def test_set_xsel(self):
  386. set_xsel(config, False)
  387. set_xsel(config, True)
  388. if sys.platform == 'linux2':
  389. self.assertEqual(None, config._conf['Global']['xsel'])
  390. def test_get_conf_file(self):
  391. Args = namedtuple('args', 'cfile')
  392. args = Args(cfile='nosuchfile')
  393. # setting the default
  394. # in case the user specifies cfile as command line option
  395. # and that file does not exist!
  396. foo = config._conf.copy()
  397. get_conf_file(args)
  398. # args.cfile does not exist, hence the config values
  399. # should be the same as in the defaults
  400. config.set_config(foo)
  401. def test_get_conf_options(self):
  402. Args = namedtuple('args', 'cfile, dbase, algo')
  403. args = Args(cfile='nosuchfile', dbase='dummy.db', algo='AES')
  404. self.assertRaises(Exception, get_conf_options, (args, 'False'))
  405. config._defaults['Database']['type'] = 'SQLite'
  406. # config._conf['Database']['type'] = 'SQLite'
  407. xsel, dbtype = get_conf_options(args, 'True')
  408. self.assertEqual(dbtype, 'SQLite')
  409. def test_set_conf(self):
  410. set_conf_f = getattr(config, 'set_conf')
  411. private_conf = getattr(config, '_conf')
  412. set_conf_f({'Config': 'OK'})
  413. self.assertDictEqual({'Config': 'OK'}, config._conf)
  414. config._conf = private_conf
  415. def test_umask(self):
  416. config._defaults = {'Global': {}}
  417. self.assertRaises(config.ConfigException, set_umask, config)
  418. def tearDown(self):
  419. config._conf = self.orig_config.copy()