test_username_available.py 2.3 KB

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