db_tests.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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.generator import leetlist
  25. from pwman.util.crypto import CryptoEngine, CryptoBadKeyException
  26. from pwman import default_config, set_xsel
  27. from pwman.ui import get_ui_platform
  28. from pwman.ui.base import get_pass_conf
  29. from pwman.ui.tools import CMDLoop, CliMenuItem
  30. from pwman import (parser_options, get_conf_options, get_conf_file)
  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 unittest
  36. import StringIO
  37. import os
  38. import os.path
  39. import sys
  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. # TODO: fix hard coded db versions! 0.4 should be replaced with
  60. # from pwman.data.database import __DB_FORMAT__
  61. _saveconfig = False
  62. PwmanCliNew, OSX = get_ui_platform(sys.platform)
  63. from test_tools import (SetupTester, DummyCallback2,
  64. DummyCallback3, DummyCallback4)
  65. class DBTests(unittest.TestCase):
  66. """test everything related to db"""
  67. def setUp(self):
  68. "test that the right db instance was created"
  69. dbver = __DB_FORMAT__
  70. self.dbtype = config.get_value("Database", "type")
  71. self.db = factory.create(self.dbtype, dbver)
  72. self.tester = SetupTester(dbver)
  73. self.tester.create()
  74. def test_db_created(self):
  75. "test that the right db instance was created"
  76. self.assertIn(self.dbtype, self.db.__class__.__name__)
  77. def test_db_opened(self):
  78. "db was successfuly opened"
  79. # it will have a file name associated
  80. self.assertTrue(hasattr(self.db, '_filename'))
  81. def test_create_node(self):
  82. "test that a node can be successfuly created"
  83. # this method does not test do_new
  84. # which is a UI method, rather we test
  85. # _db.addnodes
  86. username = 'tester'
  87. password = 'Password'
  88. url = 'example.org'
  89. notes = 'some notes'
  90. #node = NewNode(username, password, url, 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}.iteritems():
  105. self.assertEquals(attr, getattr(new_node, key))
  106. self.db.close()
  107. def test_tags(self):
  108. enc = CryptoEngine.get()
  109. got_tags = self.tester.cli._tags(enc)
  110. self.assertEqual(2, len(got_tags))
  111. def test_change_pass(self):
  112. enc = CryptoEngine.get()
  113. enc._callback = DummyCallback2()
  114. self.assertRaises(CryptoBadKeyException,
  115. self.tester.cli._db.changepassword)
  116. def test_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. self.tester.cli.do_ls('')
  124. def test_db_list_tags(self):
  125. # tags are return as ecrypted strings
  126. tags = self.tester.cli._db.listtags()
  127. self.assertEqual(2, len(tags))
  128. self.tester.cli.do_filter('testing1')
  129. tags = self.tester.cli._db.listtags()
  130. self.assertEqual(2, len(tags))
  131. self.tester.cli.do_ls('')
  132. def test_db_remove_node(self):
  133. node = self.tester.cli._db.getnodes([1])
  134. self.tester.cli._db.removenodes(node)
  135. # create the removed node again
  136. node = NewNode()
  137. node.username = 'tester'
  138. node.password = 'Password'
  139. node.url = 'example.org'
  140. node.notes = 'some notes'
  141. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  142. node.tags = tags
  143. self.db.open()
  144. self.db.addnodes([node])
  145. def test_sqlite_init(self):
  146. db = SQLiteDatabaseNewForm("test")
  147. self.assertEquals("test", db._filename)
  148. class TestDBFalseConfig(unittest.TestCase):
  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. def test_db_missing_conf_parameter(self):
  154. self.assertRaises(DatabaseException, factory.create,
  155. 'SQLite', __DB_FORMAT__)
  156. def test_get_ui_platform(self):
  157. uiclass, osx = get_ui_platform('windows')
  158. self.assertFalse(osx)
  159. self.assertEqual(uiclass.__name__, PwmanCliWinNew.__name__)
  160. uiclass, osx = get_ui_platform('darwin')
  161. self.assertTrue(osx)
  162. self.assertEqual(uiclass.__name__, PwmanCliMacNew.__name__)
  163. del(uiclass)
  164. del(osx)
  165. def tearDown(self):
  166. config.set_value('Database', 'filename', self.fname)
  167. default_config['Database']['filename'] = self.fname1
  168. config._conf['Database']['filename'] = self.fname
  169. class CLITests(unittest.TestCase):
  170. """
  171. test command line functionallity
  172. """
  173. def setUp(self):
  174. "test that the right db instance was created"
  175. self.dbtype = config.get_value("Database", "type")
  176. self.db = factory.create(self.dbtype, __DB_FORMAT__)
  177. self.tester = SetupTester(__DB_FORMAT__)
  178. self.tester.create()
  179. def test_input(self):
  180. name = self.tester.cli.get_username(reader=lambda: u'alice')
  181. self.assertEqual(name, u'alice')
  182. def test_password(self):
  183. password = self.tester.cli.get_password(None,
  184. reader=lambda x: u'hatman')
  185. self.assertEqual(password, u'hatman')
  186. def test_random_password(self):
  187. password = self.tester.cli.get_password(None, length=7)
  188. self.assertEqual(len(password), 7)
  189. def test_random_leet_password(self):
  190. password = self.tester.cli.get_password(None, leetify=True, length=7)
  191. l_num = 0
  192. for v in leetlist.values():
  193. if v in password:
  194. l_num += 1
  195. # sometime despite all efforts, randomness dictates that no
  196. # leetifying happens ...
  197. self.assertTrue(l_num >= 0)
  198. def test_leet_password(self):
  199. password = self.tester.cli.get_password(None, leetify=True,
  200. reader=lambda x: u'HAtman')
  201. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  202. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  203. def test_get_url(self):
  204. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  205. self.assertEqual(url, u'example.com')
  206. def test_get_notes(self):
  207. notes = self.tester.cli.get_notes(reader=lambda:
  208. u'test 123\n test 456')
  209. self.assertEqual(notes, u'test 123\n test 456')
  210. def test_get_tags(self):
  211. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  212. for t in tags:
  213. self.assertIsInstance(t, TagNew)
  214. for t, n in zip(tags, 'looking glass'.split()):
  215. self.assertEqual(t.name.strip(), n)
  216. # creating all the components of the node does
  217. # the node is still not added !
  218. def test_add_new_entry(self):
  219. # node = NewNode('alice', 'dough!', 'example.com',
  220. # 'lorem impsum')
  221. node = NewNode()
  222. node.username = 'alice'
  223. node.password = 'dough!'
  224. node.url = 'example.com'
  225. node.notes = 'somenotes'
  226. node.tags = 'lorem ipsum'
  227. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  228. node.tags = tags
  229. self.tester.cli._db.addnodes([node])
  230. self.tester.cli._db._cur.execute(
  231. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  232. rows = self.tester.cli._db._cur.fetchall()
  233. # by now the db should have 2 new nodes
  234. # the first one was added by test_create_node in DBTests
  235. # the second was added just now.
  236. # This will pass only when running all the tests then ...
  237. self.assertEqual(len(rows), 2)
  238. node = NewNode()
  239. node.username = 'alice'
  240. node.password = 'dough!'
  241. node.url = 'example.com'
  242. node.notes = 'somenotes'
  243. node.tags = 'lorem ipsum'
  244. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  245. node.tags = tags
  246. self.tester.cli._db.addnodes([node])
  247. def test_get_ids(self):
  248. # used by do_cp or do_open,
  249. # this spits many time could not understand your input
  250. self.assertEqual([1], self.tester.cli.get_ids('1'))
  251. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  252. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  253. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  254. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  255. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  256. def test_edit(self):
  257. node = self.tester.cli._db.getnodes([2])[0]
  258. menu = CMDLoop()
  259. menu.add(CliMenuItem("Username", self.tester.cli.get_username,
  260. node.username,
  261. node.username))
  262. menu.add(CliMenuItem("Password", self.tester.cli.get_password,
  263. node.password,
  264. node.password))
  265. menu.add(CliMenuItem("Url", self.tester.cli.get_url,
  266. node.url,
  267. node.url))
  268. menunotes = CliMenuItem("Notes",
  269. self.tester.cli.get_notes(reader=lambda:
  270. u'bla bla'),
  271. node.notes,
  272. node.notes)
  273. menu.add(menunotes)
  274. menu.add(CliMenuItem("Tags", self.tester.cli.get_tags,
  275. node.tags,
  276. node.tags))
  277. dummy_stdin = StringIO.StringIO('4\n\nX')
  278. self.assertTrue(len(dummy_stdin.readlines()))
  279. dummy_stdin.seek(0)
  280. sys.stdin = dummy_stdin
  281. menu.run(node)
  282. self.tester.cli._db.editnode(2, node)
  283. sys.stdin = sys.__stdin__
  284. def test_get_pass_conf(self):
  285. numerics, leet, s_chars = get_pass_conf()
  286. self.assertFalse(numerics)
  287. self.assertFalse(leet)
  288. self.assertFalse(s_chars)
  289. def test_do_tags(self):
  290. self.tester.cli.do_filter('bank')
  291. def test_do_forget(self):
  292. self.tester.cli.do_forget('')
  293. def test_do_auth(self):
  294. crypto = CryptoEngine.get()
  295. crypto.auth('12345')
  296. def test_do_clear(self):
  297. self.tester.cli.do_clear('')
  298. def test_do_exit(self):
  299. self.assertTrue(self.tester.cli.do_exit(''))
  300. class FactoryTest(unittest.TestCase):
  301. def test_factory_check_db_ver(self):
  302. self.assertEquals(factory.check_db_version('SQLite'), 0.5)
  303. class ConfigTest(unittest.TestCase):
  304. def setUp(self):
  305. "test that the right db instance was created"
  306. dbver = 0.4
  307. self.dbtype = config.get_value("Database", "type")
  308. self.db = factory.create(self.dbtype, dbver)
  309. self.tester = SetupTester(dbver)
  310. self.tester.create()
  311. def test_config_write(self):
  312. _filename = os.path.join(os.path.dirname(__file__),
  313. 'testing_config')
  314. config._file = _filename
  315. config.save(_filename)
  316. self.assertTrue(_filename)
  317. os.remove(_filename)
  318. def test_config_write_with_none(self):
  319. _filename = os.path.join(os.path.dirname(__file__),
  320. 'testing_config')
  321. config._file = _filename
  322. config.save()
  323. self.assertTrue(os.path.exists(_filename))
  324. os.remove(_filename)
  325. def test_write_no_permission(self):
  326. # this test will pass if you run as root ...
  327. # assuming you are not doing something like that
  328. self.assertRaises(config.ConfigException, config.save,
  329. '/root/test_config')
  330. def test_add_default(self):
  331. config.add_defaults({'Section1': {'name': 'value'}})
  332. self.assertIn('Section1', config._defaults)
  333. def test_get_conf(self):
  334. cnf = config.get_conf()
  335. cnf_keys = cnf.keys()
  336. self.assertTrue('Encryption' in cnf_keys)
  337. self.assertTrue('Readline' in cnf_keys)
  338. self.assertTrue('Global' in cnf_keys)
  339. self.assertTrue('Database' in cnf_keys)
  340. def test_load_conf(self):
  341. self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  342. # Everything should be ok
  343. config.save('TestConfig.ini')
  344. config.load('TestConfig.ini')
  345. # let's corrupt the file
  346. cfg = open('TestConfig.ini', 'w')
  347. cfg.write('Corruption')
  348. cfg.close()
  349. self.assertRaises(config.ConfigException, config.load,
  350. 'TestConfig.ini')
  351. os.remove('TestConfig.ini')
  352. def test_all_config(self):
  353. sys.argv = ['pwman3']
  354. default_config['Database'] = {'type': '',
  355. 'filename': ''}
  356. _save_conf = config._conf.copy()
  357. config._conf = {}
  358. with open('dummy.conf', 'w') as dummy:
  359. dummy.write(dummyfile)
  360. sys.argv = ['pwman3', '-d', '', '-c', 'dummy.conf']
  361. p2 = parser_options()
  362. args = p2.parse_args()
  363. self.assertRaises(Exception, get_conf_options, args, False)
  364. config._conf = _save_conf.copy()
  365. os.unlink('dummy.conf')
  366. def test_set_xsel(self):
  367. set_xsel(config, False)
  368. set_xsel(config, True)
  369. if sys.platform == 'linux2':
  370. self.assertEqual(None, config._conf['Global']['xsel'])
  371. def test_get_conf_file(self):
  372. Args = namedtuple('args', 'cfile')
  373. args = Args(cfile='nosuchfile')
  374. # setting the default
  375. # in case the user specifies cfile as command line option
  376. # and that file does not exist!
  377. get_conf_file(args)
  378. # args.cfile does not exist, hence the config values
  379. # should be the same as in the defaults
  380. # Fix this issue, see comment LN155 in config.py