1
0

test_username_available.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # Copyright 2021 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. from typing import Optional
  15. from twisted.test.proto_helpers import MemoryReactor
  16. import synapse.rest.admin
  17. from synapse.api.errors import Codes, SynapseError
  18. from synapse.rest.client import login
  19. from synapse.server import HomeServer
  20. from synapse.util import Clock
  21. from tests import unittest
  22. class UsernameAvailableTestCase(unittest.HomeserverTestCase):
  23. servlets = [
  24. synapse.rest.admin.register_servlets,
  25. login.register_servlets,
  26. ]
  27. url = "/_synapse/admin/v1/username_available"
  28. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  29. self.register_user("admin", "pass", admin=True)
  30. self.admin_user_tok = self.login("admin", "pass")
  31. async def check_username(
  32. localpart: str,
  33. guest_access_token: Optional[str] = None,
  34. assigned_user_id: Optional[str] = None,
  35. inhibit_user_in_use_error: bool = False,
  36. ) -> None:
  37. if localpart == "allowed":
  38. return
  39. raise SynapseError(
  40. 400,
  41. "User ID already taken.",
  42. errcode=Codes.USER_IN_USE,
  43. )
  44. handler = self.hs.get_registration_handler()
  45. handler.check_username = check_username # type: ignore[assignment]
  46. def test_username_available(self) -> None:
  47. """
  48. The endpoint should return a 200 response if the username does not exist
  49. """
  50. url = "%s?username=%s" % (self.url, "allowed")
  51. channel = self.make_request("GET", url, access_token=self.admin_user_tok)
  52. self.assertEqual(200, channel.code, msg=channel.json_body)
  53. self.assertTrue(channel.json_body["available"])
  54. def test_username_unavailable(self) -> None:
  55. """
  56. The endpoint should return a 200 response if the username does not exist
  57. """
  58. url = "%s?username=%s" % (self.url, "disallowed")
  59. channel = self.make_request("GET", url, access_token=self.admin_user_tok)
  60. self.assertEqual(400, channel.code, msg=channel.json_body)
  61. self.assertEqual(channel.json_body["errcode"], "M_USER_IN_USE")
  62. self.assertEqual(channel.json_body["error"], "User ID already taken.")