test_token.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import pytest
  2. from pydantic import ValidationError
  3. from clean_python import Tenant
  4. from clean_python import User
  5. from clean_python.oauth2 import Token
  6. @pytest.fixture
  7. def claims():
  8. return {"sub": "abc123", "scope": "a b", "username": "foo"}
  9. @pytest.fixture
  10. def claims_multitenant():
  11. return {
  12. "sub": "abc123",
  13. "scope": "a b",
  14. "username": "foo",
  15. "tenant": 1,
  16. "tenant_name": "bar",
  17. }
  18. def test_init(claims):
  19. Token(claims=claims)
  20. def test_init_multitenant(claims_multitenant):
  21. Token(claims=claims_multitenant)
  22. @pytest.mark.parametrize(
  23. "claims",
  24. [
  25. {"scope": "", "username": "foo"},
  26. {"sub": "abc123", "username": "foo"},
  27. {"sub": "abc123", "scope": ""},
  28. {"sub": "abc123", "scope": "", "username": "foo", "tenant": 1},
  29. ],
  30. )
  31. def test_init_err(claims):
  32. with pytest.raises(ValidationError):
  33. Token(claims=claims)
  34. def test_user(claims):
  35. actual = Token(claims=claims).user
  36. assert actual == User(id="abc123", name="foo")
  37. def test_scope(claims):
  38. actual = Token(claims=claims).scope
  39. assert actual == frozenset({"a", "b"})
  40. def test_tenant(claims_multitenant):
  41. actual = Token(claims=claims_multitenant).tenant
  42. assert actual == Tenant(id=1, name="bar")
  43. def test_no_tenant(claims):
  44. actual = Token(claims=claims).tenant
  45. assert actual is None
  46. @pytest.fixture
  47. def claims_client_credentials():
  48. return {
  49. "sub": "abc123",
  50. "scope": "a b",
  51. "client_id": "foo",
  52. }
  53. def test_user_client_credentials(claims_client_credentials):
  54. actual = Token(claims=claims_client_credentials).user
  55. assert actual == User(id="abc123", name="foo")