db_tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.config import get_pass_conf
  24. from pwman.util.generator import leetlist
  25. from pwman.util.crypto_engine import CryptoEngine
  26. from pwman.ui import get_ui_platform
  27. from pwman.ui.tools import CMDLoop, CliMenuItem
  28. # from pwman import (parser_options, get_conf_options, get_conf, set_umask)
  29. from pwman.data.database import __DB_FORMAT__
  30. import sys
  31. import unittest
  32. if sys.version_info.major > 2:
  33. from io import StringIO
  34. else:
  35. from StringIO import StringIO
  36. import os
  37. import os.path
  38. dummyfile = """
  39. [Encryption]
  40. [Readline]
  41. [Global]
  42. xsel = /usr/bin/xsel
  43. colors = yes
  44. umask = 0100
  45. cls_timeout = 5
  46. [Database]
  47. """
  48. def node_factory(username, password, url, notes, tags=None):
  49. node = NewNode()
  50. node.username = username
  51. node.password = password
  52. node.url = url
  53. node.notes = notes
  54. tags = [TagNew(tn) for tn in tags]
  55. node.tags = tags
  56. return node
  57. _saveconfig = False
  58. PwmanCliNew, OSX = get_ui_platform(sys.platform)
  59. from .test_tools import (SetupTester, DummyCallback2,
  60. DummyCallback3, DummyCallback4)
  61. testdb = os.path.join(os.path.dirname(__file__), "test.pwman.db")
  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 = 'SQLite'
  68. self.db = factory.create(self.dbtype, dbver, testdb)
  69. self.tester = SetupTester(dbver, testdb)
  70. self.tester.create()
  71. def test_1_db_created(self):
  72. "test that the right db instance was created"
  73. self.assertIn(self.dbtype, self.db.__class__.__name__)
  74. def test_2_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_3_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 = u'tester'
  84. password = u'Password'
  85. url = u'example.org'
  86. notes = u'some notes'
  87. node = NewNode()
  88. node.username = username
  89. node.password = password
  90. node.url = url
  91. node.notes = notes
  92. # node = NewNode(username, password, url, notes)
  93. tags = [TagNew(tn) for tn in ['testing1', 'testing2']]
  94. node.tags = tags
  95. self.db.open()
  96. self.db.addnodes([node])
  97. idx_created = node._id
  98. new_node = self.db.getnodes([idx_created])[0]
  99. for key, attr in {'password': password, 'username': username,
  100. 'url': url, 'notes': notes}.items():
  101. self.assertEqual(attr, getattr(new_node, key).decode())
  102. self.db.close()
  103. def test_4_tags(self):
  104. enc = CryptoEngine.get()
  105. got_tags = self.tester.cli._tags(enc)
  106. self.assertEqual(2, len(got_tags))
  107. def test_5_change_pass(self):
  108. enc = CryptoEngine.get()
  109. enc.callback = DummyCallback2()
  110. self.tester.cli._db.changepassword()
  111. @unittest.skip("This is broken as long as changepassword isn't working.")
  112. def test_6_db_change_pass(self):
  113. "fuck yeah, we change the password and the new dummy works"
  114. enc = CryptoEngine.get()
  115. enc.callback = DummyCallback3()
  116. self.tester.cli._db.changepassword()
  117. self.tester.cli.do_forget('')
  118. enc.callback = DummyCallback4()
  119. # TODO: this is broken!
  120. self.tester.cli.do_ls('')
  121. def test_7_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_8_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_9_sqlite_init(self):
  143. db = SQLiteDatabaseNewForm("test")
  144. self.assertEqual("test", db._filename)
  145. class CLITests(unittest.TestCase):
  146. """
  147. test command line functionallity
  148. """
  149. def setUp(self):
  150. "test that the right db instance was created"
  151. self.dbtype = 'SQLite'
  152. self.db = factory.create(self.dbtype, __DB_FORMAT__, testdb)
  153. self.tester = SetupTester(__DB_FORMAT__, testdb)
  154. self.tester.create()
  155. def test_input(self):
  156. name = self.tester.cli.get_username(reader=lambda: u'alice')
  157. self.assertEqual(name, u'alice')
  158. def test_password(self):
  159. password = self.tester.cli.get_password(None,
  160. reader=lambda x: u'hatman')
  161. self.assertEqual(password, u'hatman')
  162. def test_random_password(self):
  163. password = self.tester.cli.get_password(None, length=7)
  164. self.assertEqual(len(password), 7)
  165. def test_random_leet_password(self):
  166. password = self.tester.cli.get_password(None, leetify=True, length=7)
  167. l_num = 0
  168. for v in leetlist.values():
  169. if v in password:
  170. l_num += 1
  171. # sometime despite all efforts, randomness dictates that no
  172. # leetifying happens ...
  173. self.assertTrue(l_num >= 0)
  174. def test_leet_password(self):
  175. password = self.tester.cli.get_password(None, leetify=True,
  176. reader=lambda x: u'HAtman')
  177. # python3 compatability
  178. if sys.version_info.major < 3:
  179. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  180. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  181. else:
  182. self.assertRegex(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  183. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  184. def test_get_url(self):
  185. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  186. self.assertEqual(url, u'example.com')
  187. def test_get_notes(self):
  188. notes = self.tester.cli.get_notes(reader=lambda:
  189. u'test 123\n test 456')
  190. self.assertEqual(notes, u'test 123\n test 456')
  191. def test_get_tags(self):
  192. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  193. for t in tags:
  194. self.assertIsInstance(t, TagNew)
  195. for t, n in zip(tags, u'looking glass'.split()):
  196. self.assertEqual(t.name.strip().decode(), n)
  197. # creating all the components of the node does
  198. # the node is still not added !
  199. def test_add_new_entry(self):
  200. # node = NewNode('alice', 'dough!', 'example.com',
  201. # 'lorem impsum')
  202. node = NewNode()
  203. node.username = b'alice'
  204. node.password = b'dough!'
  205. node.url = b'example.com'
  206. node.notes = b'somenotes'
  207. node.tags = b'lorem ipsum'
  208. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  209. node.tags = tags
  210. self.tester.cli._db.addnodes([node])
  211. self.tester.cli._db._cur.execute(
  212. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  213. rows = self.tester.cli._db._cur.fetchall()
  214. # by now the db should have 2 new nodes
  215. # the first one was added by test_create_node in DBTests
  216. # the second was added just now.
  217. # This will pass only when running all the tests then ...
  218. self.assertEqual(len(rows), 2)
  219. node = NewNode()
  220. node.username = b'alice'
  221. node.password = b'dough!'
  222. node.url = b'example.com'
  223. node.notes = b'somenotes'
  224. node.tags = b'lorem ipsum'
  225. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  226. node.tags = tags
  227. self.tester.cli._db.addnodes([node])
  228. def test_get_ids(self):
  229. # used by do_cp or do_open,
  230. # this spits many time could not understand your input
  231. self.assertEqual([1], self.tester.cli.get_ids('1'))
  232. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  233. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  234. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  235. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  236. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  237. def test_edit(self):
  238. node = self.tester.cli._db.getnodes([2])[0]
  239. menu = CMDLoop()
  240. menu.add(CliMenuItem("Username", self.tester.cli.get_username,
  241. node.username,
  242. node.username))
  243. menu.add(CliMenuItem("Password", self.tester.cli.get_password,
  244. node.password,
  245. node.password))
  246. menu.add(CliMenuItem("Url", self.tester.cli.get_url,
  247. node.url,
  248. node.url))
  249. menunotes = CliMenuItem("Notes",
  250. self.tester.cli.get_notes(reader=lambda:
  251. u'bla bla'),
  252. node.notes,
  253. node.notes)
  254. menu.add(menunotes)
  255. menu.add(CliMenuItem("Tags", self.tester.cli.get_tags,
  256. node.tags,
  257. node.tags))
  258. dummy_stdin = StringIO('4\n\nX')
  259. class dummy_stdin(object):
  260. def __init__(self):
  261. self.idx = -1
  262. self.ans = ['4', 'some fucking notes', 'X']
  263. def __call__(self, msg):
  264. self.idx += 1
  265. return self.ans[self.idx]
  266. dstin = dummy_stdin()
  267. menu.run(node, reader=dstin)
  268. self.tester.cli._db.editnode(2, node)
  269. def test_get_pass_conf(self):
  270. numerics, leet, s_chars = get_pass_conf(self.tester.cli.config)
  271. self.assertFalse(numerics)
  272. self.assertFalse(leet)
  273. self.assertFalse(s_chars)
  274. def test_do_tags(self):
  275. self.tester.cli.do_filter('bank')
  276. def test_do_forget(self):
  277. self.tester.cli.do_forget('')
  278. def test_do_auth(self):
  279. crypto = CryptoEngine.get()
  280. rv = crypto.authenticate('12345')
  281. self.assertTrue(rv)
  282. self.assertFalse(crypto.authenticate('WRONG'))
  283. def test_do_clear(self):
  284. self.tester.cli.do_clear('')
  285. def test_do_exit(self):
  286. self.assertTrue(self.tester.cli.do_exit(''))
  287. class FactoryTest(unittest.TestCase):
  288. def test_factory_check_db_ver(self):
  289. self.assertEqual(factory.check_db_version('SQLite', testdb), 0.5)
  290. def test_factory_check_db_file(self):
  291. factory.create('SQLite', version='0.3', filename='baz.db')
  292. self.assertEqual(factory.check_db_version('SQLite', 'baz.db'), 0.3)
  293. os.unlink('baz.db')
  294. def test_factory_create(self):
  295. db = factory.create('SQLite', filename='foo.db')
  296. db._open()
  297. self.assertTrue(os.path.exists('foo.db'))
  298. db.close()
  299. os.unlink('foo.db')
  300. self.assertIsInstance(db, SQLiteDatabaseNewForm)
  301. self.assertRaises(DatabaseException, factory.create, 'UNKNOWN')
  302. if __name__ == '__main__':
  303. # make sure we use local pwman
  304. sys.path.insert(0, os.getcwd())
  305. # check if old DB exists, if so remove it.
  306. # excuted only once when invoked upon import or
  307. # upon run
  308. SetupTester().clean()
  309. unittest.main(verbosity=1, failfast=True)