db_tests.py 13 KB

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