You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

  1. from datetime import timedelta as td
  2. from django.test.utils import override_settings
  3. from django.utils.timezone import now
  4. from hc.api.models import TokenBucket
  5. from hc.test import BaseTestCase
  6. # This is sha1("[email protected]" + "test-secred")
  7. ALICE_HASH = "d60db3b2343e713a4de3e92d4eb417e4f05f06ab"
  8. @override_settings(SECRET_KEY="test-secret")
  9. class TokenBucketTestCase(BaseTestCase):
  10. def test_it_works(self):
  11. r = TokenBucket.authorize_login_email("[email protected]")
  12. self.assertTrue(r)
  13. obj = TokenBucket.objects.get()
  14. self.assertEqual(obj.tokens, 0.95)
  15. self.assertEqual(obj.value, "em-" + ALICE_HASH)
  16. def test_it_handles_insufficient_tokens(self):
  17. TokenBucket.objects.create(value="em-" + ALICE_HASH, tokens=0.04)
  18. r = TokenBucket.authorize_login_email("[email protected]")
  19. self.assertFalse(r)
  20. def test_it_tops_up(self):
  21. obj = TokenBucket(value="em-" + ALICE_HASH)
  22. obj.tokens = 0
  23. obj.updated = now() - td(minutes=30)
  24. obj.save()
  25. r = TokenBucket.authorize_login_email("[email protected]")
  26. self.assertTrue(r)
  27. obj.refresh_from_db()
  28. self.assertAlmostEqual(obj.tokens, 0.45, places=5)
  29. def test_it_normalizes_email(self):
  30. emails = ("[email protected]", "[email protected]")
  31. for email in emails:
  32. TokenBucket.authorize_login_email(email)
  33. self.assertEqual(TokenBucket.objects.count(), 1)