db_tests.py 18 KB

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