test_username_available.py 2.5 KB

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