db_tests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. self.assertRegexpMatches(password, ("(H|h)?(A|a|4)?(T|t|\+)?(m|M|\|"
  178. "\/\|)?(A|a|4)?(N|n|\|\\|)?"))
  179. def test_get_url(self):
  180. url = self.tester.cli.get_url(reader=lambda: u'example.com')
  181. self.assertEqual(url, u'example.com')
  182. def test_get_notes(self):
  183. notes = self.tester.cli.get_notes(reader=lambda:
  184. u'test 123\n test 456')
  185. self.assertEqual(notes, u'test 123\n test 456')
  186. def test_get_tags(self):
  187. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  188. for t in tags:
  189. self.assertIsInstance(t, TagNew)
  190. for t, n in zip(tags, u'looking glass'.split()):
  191. self.assertEqual(t.name.strip().decode(), n)
  192. # creating all the components of the node does
  193. # the node is still not added !
  194. def test_add_new_entry(self):
  195. # node = NewNode('alice', 'dough!', 'example.com',
  196. # 'lorem impsum')
  197. node = NewNode()
  198. node.username = b'alice'
  199. node.password = b'dough!'
  200. node.url = b'example.com'
  201. node.notes = b'somenotes'
  202. node.tags = b'lorem ipsum'
  203. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  204. node.tags = tags
  205. self.tester.cli._db.addnodes([node])
  206. self.tester.cli._db._cur.execute(
  207. "SELECT ID FROM NODES ORDER BY ID ASC", [])
  208. rows = self.tester.cli._db._cur.fetchall()
  209. # by now the db should have 2 new nodes
  210. # the first one was added by test_create_node in DBTests
  211. # the second was added just now.
  212. # This will pass only when running all the tests then ...
  213. self.assertEqual(len(rows), 2)
  214. node = NewNode()
  215. node.username = b'alice'
  216. node.password = b'dough!'
  217. node.url = b'example.com'
  218. node.notes = b'somenotes'
  219. node.tags = b'lorem ipsum'
  220. tags = self.tester.cli.get_tags(reader=lambda: u'looking glass')
  221. node.tags = tags
  222. self.tester.cli._db.addnodes([node])
  223. def test_get_ids(self):
  224. # used by do_cp or do_open,
  225. # this spits many time could not understand your input
  226. self.assertEqual([1], self.tester.cli.get_ids('1'))
  227. self.assertListEqual([1, 2, 3, 4, 5], self.tester.cli.get_ids('1-5'))
  228. self.assertListEqual([], self.tester.cli.get_ids('5-1'))
  229. self.assertListEqual([], self.tester.cli.get_ids('5x-1'))
  230. self.assertListEqual([], self.tester.cli.get_ids('5x'))
  231. self.assertListEqual([], self.tester.cli.get_ids('5\\'))
  232. def test_edit(self):
  233. node = self.tester.cli._db.getnodes([2])[0]
  234. menu = CMDLoop()
  235. menu.add(CliMenuItem("Username", self.tester.cli.get_username,
  236. node.username,
  237. node.username))
  238. menu.add(CliMenuItem("Password", self.tester.cli.get_password,
  239. node.password,
  240. node.password))
  241. menu.add(CliMenuItem("Url", self.tester.cli.get_url,
  242. node.url,
  243. node.url))
  244. menunotes = CliMenuItem("Notes",
  245. self.tester.cli.get_notes(reader=lambda:
  246. u'bla bla'),
  247. node.notes,
  248. node.notes)
  249. menu.add(menunotes)
  250. menu.add(CliMenuItem("Tags", self.tester.cli.get_tags,
  251. node.tags,
  252. node.tags))
  253. dummy_stdin = StringIO('4\n\nX')
  254. class dummy_stdin(object):
  255. def __init__(self):
  256. self.idx = -1
  257. self.ans = ['4', 'some fucking notes', 'X']
  258. def __call__(self, msg):
  259. self.idx += 1
  260. return self.ans[self.idx]
  261. dstin = dummy_stdin()
  262. menu.run(node, reader=dstin)
  263. self.tester.cli._db.editnode(2, node)
  264. def test_get_pass_conf(self):
  265. numerics, leet, s_chars = get_pass_conf(self.tester.cli.config)
  266. self.assertFalse(numerics)
  267. self.assertFalse(leet)
  268. self.assertFalse(s_chars)
  269. def test_do_tags(self):
  270. self.tester.cli.do_filter('bank')
  271. def test_do_forget(self):
  272. self.tester.cli.do_forget('')
  273. def test_do_auth(self):
  274. crypto = CryptoEngine.get()
  275. rv = crypto.authenticate('12345')
  276. self.assertTrue(rv)
  277. self.assertFalse(crypto.authenticate('WRONG'))
  278. def test_do_clear(self):
  279. self.tester.cli.do_clear('')
  280. def test_do_exit(self):
  281. self.assertTrue(self.tester.cli.do_exit(''))
  282. class FactoryTest(unittest.TestCase):
  283. def test_factory_check_db_ver(self):
  284. self.assertEqual(factory.check_db_version('SQLite', testdb), 0.5)
  285. def test_factory_check_db_file(self):
  286. factory.create('SQLite', version='0.3', filename='baz.db')
  287. self.assertEqual(factory.check_db_version('SQLite', 'baz.db'), 0.3)
  288. os.unlink('baz.db')
  289. def test_factory_create(self):
  290. db = factory.create('SQLite', filename='foo.db')
  291. db._open()
  292. self.assertTrue(os.path.exists('foo.db'))
  293. db.close()
  294. os.unlink('foo.db')
  295. self.assertIsInstance(db, SQLiteDatabaseNewForm)
  296. self.assertRaises(DatabaseException, factory.create, 'UNKNOWN')
  297. if __name__ == '__main__':
  298. # make sure we use local pwman
  299. sys.path.insert(0, os.getcwd())
  300. # check if old DB exists, if so remove it.
  301. # excuted only once when invoked upon import or
  302. # upon run
  303. SetupTester().clean()
  304. unittest.main(verbosity=1, failfast=True)