db_tests.py 15 KB

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