test_timed.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from datetime import datetime
  2. from datetime import timedelta
  3. from functools import partial
  4. import pytest
  5. from freezegun import freeze_time
  6. from .test_serializer import TestSerializer
  7. from .test_signer import TestSigner
  8. from itsdangerous import Signer
  9. from itsdangerous.exc import BadTimeSignature
  10. from itsdangerous.exc import SignatureExpired
  11. from itsdangerous.timed import TimedSerializer
  12. from itsdangerous.timed import TimestampSigner
  13. class FreezeMixin(object):
  14. @pytest.fixture()
  15. def ts(self):
  16. return datetime(2011, 6, 24, 0, 9, 5)
  17. @pytest.fixture(autouse=True)
  18. def freeze(self, ts):
  19. with freeze_time(ts) as ft:
  20. yield ft
  21. class TestTimestampSigner(FreezeMixin, TestSigner):
  22. @pytest.fixture()
  23. def signer_factory(self):
  24. return partial(TimestampSigner, secret_key="secret-key")
  25. def test_max_age(self, signer, ts, freeze):
  26. signed = signer.sign("value")
  27. freeze.tick()
  28. assert signer.unsign(signed, max_age=10) == b"value"
  29. freeze.tick(timedelta(seconds=10))
  30. with pytest.raises(SignatureExpired) as exc_info:
  31. signer.unsign(signed, max_age=10)
  32. assert exc_info.value.date_signed == ts
  33. def test_return_timestamp(self, signer, ts):
  34. signed = signer.sign("value")
  35. assert signer.unsign(signed, return_timestamp=True) == (b"value", ts)
  36. def test_timestamp_missing(self, signer):
  37. other = Signer("secret-key")
  38. signed = other.sign("value")
  39. with pytest.raises(BadTimeSignature) as exc_info:
  40. signer.unsign(signed)
  41. assert "missing" in str(exc_info.value)
  42. def test_malformed_timestamp(self, signer):
  43. other = Signer("secret-key")
  44. signed = other.sign(b"value.____________")
  45. with pytest.raises(BadTimeSignature) as exc_info:
  46. signer.unsign(signed)
  47. assert "Malformed" in str(exc_info.value)
  48. class TestTimedSerializer(FreezeMixin, TestSerializer):
  49. @pytest.fixture()
  50. def serializer_factory(self):
  51. return partial(TimedSerializer, secret_key="secret_key")
  52. def test_max_age(self, serializer, value, ts, freeze):
  53. signed = serializer.dumps(value)
  54. freeze.tick()
  55. assert serializer.loads(signed, max_age=10) == value
  56. freeze.tick(timedelta(seconds=10))
  57. with pytest.raises(SignatureExpired) as exc_info:
  58. serializer.loads(signed, max_age=10)
  59. assert exc_info.value.date_signed == ts
  60. assert serializer.load_payload(exc_info.value.payload) == value
  61. def test_return_payload(self, serializer, value, ts):
  62. signed = serializer.dumps(value)
  63. assert serializer.loads(signed, return_timestamp=True) == (value, ts)