test_username_available.py 2.7 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 http import HTTPStatus
  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(username: str) -> bool:
  32. if username == "allowed":
  33. return True
  34. raise SynapseError(
  35. HTTPStatus.BAD_REQUEST,
  36. "User ID already taken.",
  37. errcode=Codes.USER_IN_USE,
  38. )
  39. handler = self.hs.get_registration_handler()
  40. handler.check_username = check_username
  41. def test_username_available(self) -> None:
  42. """
  43. The endpoint should return a HTTPStatus.OK response if the username does not exist
  44. """
  45. url = "%s?username=%s" % (self.url, "allowed")
  46. channel = self.make_request("GET", url, access_token=self.admin_user_tok)
  47. self.assertEqual(HTTPStatus.OK, channel.code, msg=channel.json_body)
  48. self.assertTrue(channel.json_body["available"])
  49. def test_username_unavailable(self) -> None:
  50. """
  51. The endpoint should return a HTTPStatus.OK response if the username does not exist
  52. """
  53. url = "%s?username=%s" % (self.url, "disallowed")
  54. channel = self.make_request("GET", url, access_token=self.admin_user_tok)
  55. self.assertEqual(
  56. HTTPStatus.BAD_REQUEST,
  57. channel.code,
  58. msg=channel.json_body,
  59. )
  60. self.assertEqual(channel.json_body["errcode"], "M_USER_IN_USE")
  61. self.assertEqual(channel.json_body["error"], "User ID already taken.")