db_tests.py 13 KB

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