db_tests.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. from pwman.ui.mac import PwmanCliMacNew
  33. from pwman.ui.win import PwmanCliWinNew
  34. import unittest
  35. import StringIO
  36. import os
  37. import os.path
  38. import sys
  39. dummyfile = """
  40. [Encryption]
  41. [Readline]
  42. [Global]
  43. xsel = /usr/bin/xsel
  44. colors = yes
  45. umask = 0100
  46. cls_timeout = 5
  47. [Database]
  48. """
  49. def node_factory(username, password, url, notes, tags=None):
  50. node = NewNode()
  51. node.username = username
  52. node.password = password
  53. node.url = url
  54. node.notes = notes
  55. tags = [TagNew(tn) for tn in tags]
  56. node.tags = tags
  57. return node
  58. # TODO: fix hard coded db versions! 0.4 should be replaced with
  59. # from pwman.data.database import __DB_FORMAT__
  60. _saveconfig = False
  61. PwmanCliNew, OSX = get_ui_platform(sys.platform)
  62. from test_tools import (SetupTester, DummyCallback2,
  63. DummyCallback3, DummyCallback4)
  64. class DBTests(unittest.TestCase):
  65. """test everything related to db"""
  66. def setUp(self):
  67. "test that the right db instance was created"
  68. dbver = __DB_FORMAT__
  69. self.dbtype = config.get_value("Database", "type")
  70. self.db = factory.create(self.dbtype, dbver)
  71. self.tester = SetupTester(dbver)
  72. self.tester.create()
  73. def test_db_created(self):
  74. "test that the right db instance was created"
  75. self.assertIn(self.dbtype, self.db.__class__.__name__)
  76. def test_db_opened(self):
  77. "db was successfuly opened"
  78. # it will have a file name associated
  79. self.assertTrue(hasattr(self.db, '_filename'))
  80. def test_create_node(self):
  81. "test that a node can be successfuly created"
  82. # this method does not test do_new
  83. # which is a UI method, rather we test
  84. # _db.addnodes
  85. username = 'tester'
  86. password = 'Password'
  87. url = 'example.org'
  88. notes = 'some notes'
  89. #node = NewNode(username, password, url, notes)
  90. node = NewNode()
  91. node.username = username
  92. node.password = password
  93. node.url = url
  94. node.notes = notes
  95. #node = NewNode(username, password, url, notes)
  96. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  97. node.tags = tags
  98. self.db.open()
  99. self.db.addnodes([node])
  100. idx_created = node._id
  101. new_node = self.db.getnodes([idx_created])[0]
  102. for key, attr in {'password': password, 'username': username,
  103. 'url': url, 'notes': notes}.iteritems():
  104. self.assertEquals(attr, getattr(new_node, key))
  105. self.db.close()
  106. def test_tags(self):
  107. enc = CryptoEngine.get()
  108. got_tags = self.tester.cli._tags(enc)
  109. self.assertEqual(2, len(got_tags))
  110. def test_change_pass(self):
  111. enc = CryptoEngine.get()
  112. enc._callback = DummyCallback2()
  113. self.assertRaises(CryptoBadKeyException,
  114. self.tester.cli._db.changepassword)
  115. def test_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_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_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_sqlite_init(self):
  145. db = SQLiteDatabaseNewForm("test")
  146. self.assertEquals("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. crypto.auth('12345')
  295. def test_do_clear(self):
  296. self.tester.cli.do_clear('')
  297. def test_do_exit(self):
  298. self.assertTrue(self.tester.cli.do_exit(''))
  299. class FactoryTest(unittest.TestCase):
  300. def test_factory_check_db_ver(self):
  301. self.assertEquals(factory.check_db_version('SQLite'), 0.5)
  302. class ConfigTest(unittest.TestCase):
  303. def setUp(self):
  304. "test that the right db instance was created"
  305. dbver = 0.4
  306. self.dbtype = config.get_value("Database", "type")
  307. self.db = factory.create(self.dbtype, dbver)
  308. self.tester = SetupTester(dbver)
  309. self.tester.create()
  310. def test_config_write(self):
  311. _filename = os.path.join(os.path.dirname(__file__),
  312. 'testing_config')
  313. config._file = _filename
  314. config.save(_filename)
  315. self.assertTrue(_filename)
  316. os.remove(_filename)
  317. def test_config_write_with_none(self):
  318. _filename = os.path.join(os.path.dirname(__file__),
  319. 'testing_config')
  320. config._file = _filename
  321. config.save()
  322. self.assertTrue(os.path.exists(_filename))
  323. os.remove(_filename)
  324. def test_write_no_permission(self):
  325. # this test will pass if you run as root ...
  326. # assuming you are not doing something like that
  327. self.assertRaises(config.ConfigException, config.save,
  328. '/root/test_config')
  329. def test_add_default(self):
  330. config.add_defaults({'Section1': {'name': 'value'}})
  331. self.assertIn('Section1', config._defaults)
  332. def test_get_conf(self):
  333. cnf = config.get_conf()
  334. cnf_keys = cnf.keys()
  335. self.assertTrue('Encryption' in cnf_keys)
  336. self.assertTrue('Readline' in cnf_keys)
  337. self.assertTrue('Global' in cnf_keys)
  338. self.assertTrue('Database' in cnf_keys)
  339. def test_load_conf(self):
  340. self.assertRaises(config.ConfigException, config.load, 'NoSuchFile')
  341. # Everything should be ok
  342. config.save('TestConfig.ini')
  343. config.load('TestConfig.ini')
  344. # let's corrupt the file
  345. cfg = open('TestConfig.ini', 'w')
  346. cfg.write('Corruption')
  347. cfg.close()
  348. self.assertRaises(config.ConfigException, config.load,
  349. 'TestConfig.ini')
  350. os.remove('TestConfig.ini')
  351. def test_all_config(self):
  352. sys.argv = ['pwman3']
  353. default_config['Database'] = {'type': '',
  354. 'filename': ''}
  355. _save_conf = config._conf.copy()
  356. config._conf = {}
  357. with open('dummy.conf', 'w') as dummy:
  358. dummy.write(dummyfile)
  359. sys.argv = ['pwman3', '-d', '', '-c', 'dummy.conf']
  360. p2 = parser_options()
  361. args = p2.parse_args()
  362. self.assertRaises(Exception, get_conf_options, args, False)
  363. config._conf = _save_conf.copy()
  364. os.unlink('dummy.conf')
  365. def test_set_xsel(self):
  366. set_xsel(config, False)
  367. set_xsel(config, True)
  368. if sys.platform == 'linux2':
  369. self.assertEqual(None, config._conf['Global']['xsel'])