test_tap.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. from twisted.cred import credentials, error
  4. from twisted.words import tap
  5. from twisted.trial import unittest
  6. class WordsTapTests(unittest.TestCase):
  7. """
  8. Ensures that the twisted.words.tap API works.
  9. """
  10. PASSWD_TEXT = "admin:admin\njoe:foo\n"
  11. admin = credentials.UsernamePassword('admin', 'admin')
  12. joeWrong = credentials.UsernamePassword('joe', 'bar')
  13. def setUp(self):
  14. """
  15. Create a file with two users.
  16. """
  17. self.filename = self.mktemp()
  18. self.file = open(self.filename, 'w')
  19. self.file.write(self.PASSWD_TEXT)
  20. self.file.flush()
  21. def tearDown(self):
  22. """
  23. Close the dummy user database.
  24. """
  25. self.file.close()
  26. def test_hostname(self):
  27. """
  28. Tests that the --hostname parameter gets passed to Options.
  29. """
  30. opt = tap.Options()
  31. opt.parseOptions(['--hostname', 'myhost'])
  32. self.assertEqual(opt['hostname'], 'myhost')
  33. def test_passwd(self):
  34. """
  35. Tests the --passwd command for backwards-compatibility.
  36. """
  37. opt = tap.Options()
  38. opt.parseOptions(['--passwd', self.file.name])
  39. self._loginTest(opt)
  40. def test_auth(self):
  41. """
  42. Tests that the --auth command generates a checker.
  43. """
  44. opt = tap.Options()
  45. opt.parseOptions(['--auth', 'file:'+self.file.name])
  46. self._loginTest(opt)
  47. def _loginTest(self, opt):
  48. """
  49. This method executes both positive and negative authentication
  50. tests against whatever credentials checker has been stored in
  51. the Options class.
  52. @param opt: An instance of L{tap.Options}.
  53. """
  54. self.assertEqual(len(opt['credCheckers']), 1)
  55. checker = opt['credCheckers'][0]
  56. self.assertFailure(checker.requestAvatarId(self.joeWrong),
  57. error.UnauthorizedLogin)
  58. def _gotAvatar(username):
  59. self.assertEqual(username, self.admin.username)
  60. return checker.requestAvatarId(self.admin).addCallback(_gotAvatar)