test_models.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright 2022 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import unittest as stdlib_unittest
  15. from pydantic import BaseModel, ValidationError
  16. from typing_extensions import Literal
  17. from synapse.rest.client.models import EmailRequestTokenBody
  18. class ThreepidMediumEnumTestCase(stdlib_unittest.TestCase):
  19. class Model(BaseModel):
  20. medium: Literal["email", "msisdn"]
  21. def test_accepts_valid_medium_string(self) -> None:
  22. """Sanity check that Pydantic behaves sensibly with an enum-of-str
  23. This is arguably more of a test of a class that inherits from str and Enum
  24. simultaneously.
  25. """
  26. model = self.Model.parse_obj({"medium": "email"})
  27. self.assertEqual(model.medium, "email")
  28. def test_rejects_invalid_medium_value(self) -> None:
  29. with self.assertRaises(ValidationError):
  30. self.Model.parse_obj({"medium": "interpretive_dance"})
  31. def test_rejects_invalid_medium_type(self) -> None:
  32. with self.assertRaises(ValidationError):
  33. self.Model.parse_obj({"medium": 123})
  34. class EmailRequestTokenBodyTestCase(stdlib_unittest.TestCase):
  35. base_request = {
  36. "client_secret": "hunter2",
  37. "email": "alice@wonderland.com",
  38. "send_attempt": 1,
  39. }
  40. def test_token_required_if_id_server_provided(self) -> None:
  41. with self.assertRaises(ValidationError):
  42. EmailRequestTokenBody.parse_obj(
  43. {
  44. **self.base_request,
  45. "id_server": "identity.wonderland.com",
  46. }
  47. )
  48. with self.assertRaises(ValidationError):
  49. EmailRequestTokenBody.parse_obj(
  50. {
  51. **self.base_request,
  52. "id_server": "identity.wonderland.com",
  53. "id_access_token": None,
  54. }
  55. )
  56. def test_token_typechecked_when_id_server_provided(self) -> None:
  57. with self.assertRaises(ValidationError):
  58. EmailRequestTokenBody.parse_obj(
  59. {
  60. **self.base_request,
  61. "id_server": "identity.wonderland.com",
  62. "id_access_token": 1337,
  63. }
  64. )