Improve the `synapse.api.auth.Auth` mock used in unit tests. (#13809)

To return the proper type (`Requester`) instead of a `dict`.
babolivier/msc3881_device_id_tmp
Quentin Gliech 2022-09-21 14:40:34 +02:00 committed by GitHub
parent a35842caec
commit e0804ef898
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 26 deletions

1
changelog.d/13809.misc Normal file
View File

@ -0,0 +1 @@
Improve the `synapse.api.auth.Auth` mock used in unit tests.

View File

@ -300,47 +300,31 @@ class HomeserverTestCase(TestCase):
if hasattr(self, "user_id"): if hasattr(self, "user_id"):
if self.hijack_auth: if self.hijack_auth:
assert self.helper.auth_user_id is not None assert self.helper.auth_user_id is not None
token = "some_fake_token"
# We need a valid token ID to satisfy foreign key constraints. # We need a valid token ID to satisfy foreign key constraints.
token_id = self.get_success( token_id = self.get_success(
self.hs.get_datastores().main.add_access_token_to_user( self.hs.get_datastores().main.add_access_token_to_user(
self.helper.auth_user_id, self.helper.auth_user_id,
"some_fake_token", token,
None, None,
None, None,
) )
) )
async def get_user_by_access_token( # This has to be a function and not just a Mock, because
token: Optional[str] = None, allow_guest: bool = False # `self.helper.auth_user_id` is temporarily reassigned in some tests
) -> JsonDict: async def get_requester(*args, **kwargs) -> Requester:
assert self.helper.auth_user_id is not None
return {
"user": UserID.from_string(self.helper.auth_user_id),
"token_id": token_id,
"is_guest": False,
}
async def get_user_by_req(
request: SynapseRequest,
allow_guest: bool = False,
allow_expired: bool = False,
) -> Requester:
assert self.helper.auth_user_id is not None assert self.helper.auth_user_id is not None
return create_requester( return create_requester(
UserID.from_string(self.helper.auth_user_id), user_id=UserID.from_string(self.helper.auth_user_id),
token_id, access_token_id=token_id,
False,
False,
None,
) )
# Type ignore: mypy doesn't like us assigning to methods. # Type ignore: mypy doesn't like us assigning to methods.
self.hs.get_auth().get_user_by_req = get_user_by_req # type: ignore[assignment] self.hs.get_auth().get_user_by_req = get_requester # type: ignore[assignment]
self.hs.get_auth().get_user_by_access_token = get_user_by_access_token # type: ignore[assignment] self.hs.get_auth().get_user_by_access_token = get_requester # type: ignore[assignment]
self.hs.get_auth().get_access_token_from_request = Mock( # type: ignore[assignment] self.hs.get_auth().get_access_token_from_request = Mock(return_value=token) # type: ignore[assignment]
return_value="1234"
)
if self.needs_threadpool: if self.needs_threadpool:
self.reactor.threadpool = ThreadPool() # type: ignore[assignment] self.reactor.threadpool = ThreadPool() # type: ignore[assignment]