Remove unnecessary json.dumps from tests (#13303)

This commit is contained in:
Dirk Klimpel 2022-07-17 23:28:45 +02:00 committed by GitHub
parent 5d4028f217
commit efee345b45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 143 additions and 200 deletions

1
changelog.d/13303.misc Normal file
View file

@ -0,0 +1 @@
Remove unnecessary `json.dumps` from tests.

View file

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
import os import os
import re import re
from email.parser import Parser from email.parser import Parser
@ -96,9 +95,7 @@ class PasswordResetTestCase(unittest.HomeserverTestCase):
""" """
body = {"type": "m.login.password", "user": username, "password": password} body = {"type": "m.login.password", "user": username, "password": password}
channel = self.make_request( channel = self.make_request("POST", "/_matrix/client/r0/login", body)
"POST", "/_matrix/client/r0/login", json.dumps(body).encode("utf8")
)
self.assertEqual(channel.code, HTTPStatus.FORBIDDEN, channel.result) self.assertEqual(channel.code, HTTPStatus.FORBIDDEN, channel.result)
def test_basic_password_reset(self) -> None: def test_basic_password_reset(self) -> None:
@ -480,16 +477,14 @@ class DeactivateTestCase(unittest.HomeserverTestCase):
self.assertEqual(memberships[0].room_id, room_id, memberships) self.assertEqual(memberships[0].room_id, room_id, memberships)
def deactivate(self, user_id: str, tok: str) -> None: def deactivate(self, user_id: str, tok: str) -> None:
request_data = json.dumps( request_data = {
{ "auth": {
"auth": { "type": "m.login.password",
"type": "m.login.password", "user": user_id,
"user": user_id, "password": "test",
"password": "test", },
}, "erase": False,
"erase": False, }
}
)
channel = self.make_request( channel = self.make_request(
"POST", "account/deactivate", request_data, access_token=tok "POST", "account/deactivate", request_data, access_token=tok
) )

View file

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
from http import HTTPStatus from http import HTTPStatus
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
@ -97,8 +96,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
# We use deliberately a localpart under the length threshold so # We use deliberately a localpart under the length threshold so
# that we can make sure that the check is done on the whole alias. # that we can make sure that the check is done on the whole alias.
data = {"room_alias_name": random_string(256 - len(self.hs.hostname))} request_data = {"room_alias_name": random_string(256 - len(self.hs.hostname))}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"POST", url, request_data, access_token=self.user_tok "POST", url, request_data, access_token=self.user_tok
) )
@ -110,8 +108,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
# Check with an alias of allowed length. There should already be # Check with an alias of allowed length. There should already be
# a test that ensures it works in test_register.py, but let's be # a test that ensures it works in test_register.py, but let's be
# as cautious as possible here. # as cautious as possible here.
data = {"room_alias_name": random_string(5)} request_data = {"room_alias_name": random_string(5)}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"POST", url, request_data, access_token=self.user_tok "POST", url, request_data, access_token=self.user_tok
) )
@ -144,8 +141,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
# Add an alias for the room, as the appservice # Add an alias for the room, as the appservice
alias = RoomAlias(f"asns-{random_string(5)}", self.hs.hostname).to_string() alias = RoomAlias(f"asns-{random_string(5)}", self.hs.hostname).to_string()
data = {"room_id": self.room_id} request_data = {"room_id": self.room_id}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", "PUT",
@ -193,8 +189,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
self.hs.hostname, self.hs.hostname,
) )
data = {"aliases": [self.random_alias(alias_length)]} request_data = {"aliases": [self.random_alias(alias_length)]}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", url, request_data, access_token=self.user_tok "PUT", url, request_data, access_token=self.user_tok
@ -206,8 +201,7 @@ class DirectoryTestCase(unittest.HomeserverTestCase):
) -> str: ) -> str:
alias = self.random_alias(alias_length) alias = self.random_alias(alias_length)
url = "/_matrix/client/r0/directory/room/%s" % alias url = "/_matrix/client/r0/directory/room/%s" % alias
data = {"room_id": self.room_id} request_data = {"room_id": self.room_id}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", url, request_data, access_token=self.user_tok "PUT", url, request_data, access_token=self.user_tok

View file

@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
from http import HTTPStatus from http import HTTPStatus
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
@ -51,12 +50,11 @@ class IdentityTestCase(unittest.HomeserverTestCase):
self.assertEqual(channel.code, HTTPStatus.OK, channel.result) self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
room_id = channel.json_body["room_id"] room_id = channel.json_body["room_id"]
params = { request_data = {
"id_server": "testis", "id_server": "testis",
"medium": "email", "medium": "email",
"address": "test@example.com", "address": "test@example.com",
} }
request_data = json.dumps(params)
request_url = ("/rooms/%s/invite" % (room_id)).encode("ascii") request_url = ("/rooms/%s/invite" % (room_id)).encode("ascii")
channel = self.make_request( channel = self.make_request(
b"POST", request_url, request_data, access_token=tok b"POST", request_url, request_data, access_token=tok

View file

@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
import time import time
import urllib.parse import urllib.parse
from http import HTTPStatus from http import HTTPStatus
@ -400,7 +399,7 @@ class LoginRestServletTestCase(unittest.HomeserverTestCase):
channel = self.make_request( channel = self.make_request(
"POST", "POST",
"/_matrix/client/v3/login", "/_matrix/client/v3/login",
json.dumps(body).encode("utf8"), body,
custom_headers=None, custom_headers=None,
) )

View file

@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
from http import HTTPStatus from http import HTTPStatus
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
@ -89,7 +88,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_too_short(self) -> None: def test_password_too_short(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "shorty"}) request_data = {"username": "kermit", "password": "shorty"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result) self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
@ -100,7 +99,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_no_digit(self) -> None: def test_password_no_digit(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "longerpassword"}) request_data = {"username": "kermit", "password": "longerpassword"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result) self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
@ -111,7 +110,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_no_symbol(self) -> None: def test_password_no_symbol(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "l0ngerpassword"}) request_data = {"username": "kermit", "password": "l0ngerpassword"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result) self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
@ -122,7 +121,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_no_uppercase(self) -> None: def test_password_no_uppercase(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "l0ngerpassword!"}) request_data = {"username": "kermit", "password": "l0ngerpassword!"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result) self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
@ -133,7 +132,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_no_lowercase(self) -> None: def test_password_no_lowercase(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "L0NGERPASSWORD!"}) request_data = {"username": "kermit", "password": "L0NGERPASSWORD!"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result) self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
@ -144,7 +143,7 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
) )
def test_password_compliant(self) -> None: def test_password_compliant(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "L0ngerpassword!"}) request_data = {"username": "kermit", "password": "L0ngerpassword!"}
channel = self.make_request("POST", self.register_url, request_data) channel = self.make_request("POST", self.register_url, request_data)
# Getting a 401 here means the password has passed validation and the server has # Getting a 401 here means the password has passed validation and the server has
@ -161,16 +160,14 @@ class PasswordPolicyTestCase(unittest.HomeserverTestCase):
user_id = self.register_user("kermit", compliant_password) user_id = self.register_user("kermit", compliant_password)
tok = self.login("kermit", compliant_password) tok = self.login("kermit", compliant_password)
request_data = json.dumps( request_data = {
{ "new_password": not_compliant_password,
"new_password": not_compliant_password, "auth": {
"auth": { "password": compliant_password,
"password": compliant_password, "type": LoginType.PASSWORD,
"type": LoginType.PASSWORD, "user": user_id,
"user": user_id, },
}, }
}
)
channel = self.make_request( channel = self.make_request(
"POST", "POST",
"/_matrix/client/r0/account/password", "/_matrix/client/r0/account/password",

View file

@ -14,7 +14,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import datetime import datetime
import json
import os import os
from typing import Any, Dict, List, Tuple from typing import Any, Dict, List, Tuple
@ -62,9 +61,10 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
) )
self.hs.get_datastores().main.services_cache.append(appservice) self.hs.get_datastores().main.services_cache.append(appservice)
request_data = json.dumps( request_data = {
{"username": "as_user_kermit", "type": APP_SERVICE_REGISTRATION_TYPE} "username": "as_user_kermit",
) "type": APP_SERVICE_REGISTRATION_TYPE,
}
channel = self.make_request( channel = self.make_request(
b"POST", self.url + b"?access_token=i_am_an_app_service", request_data b"POST", self.url + b"?access_token=i_am_an_app_service", request_data
@ -85,7 +85,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
) )
self.hs.get_datastores().main.services_cache.append(appservice) self.hs.get_datastores().main.services_cache.append(appservice)
request_data = json.dumps({"username": "as_user_kermit"}) request_data = {"username": "as_user_kermit"}
channel = self.make_request( channel = self.make_request(
b"POST", self.url + b"?access_token=i_am_an_app_service", request_data b"POST", self.url + b"?access_token=i_am_an_app_service", request_data
@ -95,9 +95,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
def test_POST_appservice_registration_invalid(self) -> None: def test_POST_appservice_registration_invalid(self) -> None:
self.appservice = None # no application service exists self.appservice = None # no application service exists
request_data = json.dumps( request_data = {"username": "kermit", "type": APP_SERVICE_REGISTRATION_TYPE}
{"username": "kermit", "type": APP_SERVICE_REGISTRATION_TYPE}
)
channel = self.make_request( channel = self.make_request(
b"POST", self.url + b"?access_token=i_am_an_app_service", request_data b"POST", self.url + b"?access_token=i_am_an_app_service", request_data
) )
@ -105,14 +103,14 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
def test_POST_bad_password(self) -> None: def test_POST_bad_password(self) -> None:
request_data = json.dumps({"username": "kermit", "password": 666}) request_data = {"username": "kermit", "password": 666}
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
self.assertEqual(channel.result["code"], b"400", channel.result) self.assertEqual(channel.result["code"], b"400", channel.result)
self.assertEqual(channel.json_body["error"], "Invalid password") self.assertEqual(channel.json_body["error"], "Invalid password")
def test_POST_bad_username(self) -> None: def test_POST_bad_username(self) -> None:
request_data = json.dumps({"username": 777, "password": "monkey"}) request_data = {"username": 777, "password": "monkey"}
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
self.assertEqual(channel.result["code"], b"400", channel.result) self.assertEqual(channel.result["code"], b"400", channel.result)
@ -121,13 +119,12 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
def test_POST_user_valid(self) -> None: def test_POST_user_valid(self) -> None:
user_id = "@kermit:test" user_id = "@kermit:test"
device_id = "frogfone" device_id = "frogfone"
params = { request_data = {
"username": "kermit", "username": "kermit",
"password": "monkey", "password": "monkey",
"device_id": device_id, "device_id": device_id,
"auth": {"type": LoginType.DUMMY}, "auth": {"type": LoginType.DUMMY},
} }
request_data = json.dumps(params)
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
det_data = { det_data = {
@ -140,7 +137,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
@override_config({"enable_registration": False}) @override_config({"enable_registration": False})
def test_POST_disabled_registration(self) -> None: def test_POST_disabled_registration(self) -> None:
request_data = json.dumps({"username": "kermit", "password": "monkey"}) request_data = {"username": "kermit", "password": "monkey"}
self.auth_result = (None, {"username": "kermit", "password": "monkey"}, None) self.auth_result = (None, {"username": "kermit", "password": "monkey"}, None)
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
@ -188,13 +185,12 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
@override_config({"rc_registration": {"per_second": 0.17, "burst_count": 5}}) @override_config({"rc_registration": {"per_second": 0.17, "burst_count": 5}})
def test_POST_ratelimiting(self) -> None: def test_POST_ratelimiting(self) -> None:
for i in range(0, 6): for i in range(0, 6):
params = { request_data = {
"username": "kermit" + str(i), "username": "kermit" + str(i),
"password": "monkey", "password": "monkey",
"device_id": "frogfone", "device_id": "frogfone",
"auth": {"type": LoginType.DUMMY}, "auth": {"type": LoginType.DUMMY},
} }
request_data = json.dumps(params)
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
if i == 5: if i == 5:
@ -234,7 +230,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
} }
# Request without auth to get flows and session # Request without auth to get flows and session
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
flows = channel.json_body["flows"] flows = channel.json_body["flows"]
# Synapse adds a dummy stage to differentiate flows where otherwise one # Synapse adds a dummy stage to differentiate flows where otherwise one
@ -251,8 +247,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session, "session": session,
} }
request_data = json.dumps(params) channel = self.make_request(b"POST", self.url, params)
channel = self.make_request(b"POST", self.url, request_data)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
completed = channel.json_body["completed"] completed = channel.json_body["completed"]
self.assertCountEqual([LoginType.REGISTRATION_TOKEN], completed) self.assertCountEqual([LoginType.REGISTRATION_TOKEN], completed)
@ -262,8 +257,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"type": LoginType.DUMMY, "type": LoginType.DUMMY,
"session": session, "session": session,
} }
request_data = json.dumps(params) channel = self.make_request(b"POST", self.url, params)
channel = self.make_request(b"POST", self.url, request_data)
det_data = { det_data = {
"user_id": f"@{username}:{self.hs.hostname}", "user_id": f"@{username}:{self.hs.hostname}",
"home_server": self.hs.hostname, "home_server": self.hs.hostname,
@ -290,7 +284,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"password": "monkey", "password": "monkey",
} }
# Request without auth to get session # Request without auth to get session
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
session = channel.json_body["session"] session = channel.json_body["session"]
# Test with token param missing (invalid) # Test with token param missing (invalid)
@ -298,21 +292,21 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"type": LoginType.REGISTRATION_TOKEN, "type": LoginType.REGISTRATION_TOKEN,
"session": session, "session": session,
} }
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.MISSING_PARAM) self.assertEqual(channel.json_body["errcode"], Codes.MISSING_PARAM)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
# Test with non-string (invalid) # Test with non-string (invalid)
params["auth"]["token"] = 1234 params["auth"]["token"] = 1234
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.INVALID_PARAM) self.assertEqual(channel.json_body["errcode"], Codes.INVALID_PARAM)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
# Test with unknown token (invalid) # Test with unknown token (invalid)
params["auth"]["token"] = "1234" params["auth"]["token"] = "1234"
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED) self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
@ -337,9 +331,9 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
params1: JsonDict = {"username": "bert", "password": "monkey"} params1: JsonDict = {"username": "bert", "password": "monkey"}
params2: JsonDict = {"username": "ernie", "password": "monkey"} params2: JsonDict = {"username": "ernie", "password": "monkey"}
# Do 2 requests without auth to get two session IDs # Do 2 requests without auth to get two session IDs
channel1 = self.make_request(b"POST", self.url, json.dumps(params1)) channel1 = self.make_request(b"POST", self.url, params1)
session1 = channel1.json_body["session"] session1 = channel1.json_body["session"]
channel2 = self.make_request(b"POST", self.url, json.dumps(params2)) channel2 = self.make_request(b"POST", self.url, params2)
session2 = channel2.json_body["session"] session2 = channel2.json_body["session"]
# Use token with session1 and check `pending` is 1 # Use token with session1 and check `pending` is 1
@ -348,9 +342,9 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session1, "session": session1,
} }
self.make_request(b"POST", self.url, json.dumps(params1)) self.make_request(b"POST", self.url, params1)
# Repeat request to make sure pending isn't increased again # Repeat request to make sure pending isn't increased again
self.make_request(b"POST", self.url, json.dumps(params1)) self.make_request(b"POST", self.url, params1)
pending = self.get_success( pending = self.get_success(
store.db_pool.simple_select_one_onecol( store.db_pool.simple_select_one_onecol(
"registration_tokens", "registration_tokens",
@ -366,14 +360,14 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session2, "session": session2,
} }
channel = self.make_request(b"POST", self.url, json.dumps(params2)) channel = self.make_request(b"POST", self.url, params2)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED) self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
# Complete registration with session1 # Complete registration with session1
params1["auth"]["type"] = LoginType.DUMMY params1["auth"]["type"] = LoginType.DUMMY
self.make_request(b"POST", self.url, json.dumps(params1)) self.make_request(b"POST", self.url, params1)
# Check pending=0 and completed=1 # Check pending=0 and completed=1
res = self.get_success( res = self.get_success(
store.db_pool.simple_select_one( store.db_pool.simple_select_one(
@ -386,7 +380,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
self.assertEqual(res["completed"], 1) self.assertEqual(res["completed"], 1)
# Check auth still fails when using token with session2 # Check auth still fails when using token with session2
channel = self.make_request(b"POST", self.url, json.dumps(params2)) channel = self.make_request(b"POST", self.url, params2)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED) self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
@ -411,7 +405,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
) )
params: JsonDict = {"username": "kermit", "password": "monkey"} params: JsonDict = {"username": "kermit", "password": "monkey"}
# Request without auth to get session # Request without auth to get session
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
session = channel.json_body["session"] session = channel.json_body["session"]
# Check authentication fails with expired token # Check authentication fails with expired token
@ -420,7 +414,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session, "session": session,
} }
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED) self.assertEqual(channel.json_body["errcode"], Codes.UNAUTHORIZED)
self.assertEqual(channel.json_body["completed"], []) self.assertEqual(channel.json_body["completed"], [])
@ -435,7 +429,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
) )
# Check authentication succeeds # Check authentication succeeds
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
completed = channel.json_body["completed"] completed = channel.json_body["completed"]
self.assertCountEqual([LoginType.REGISTRATION_TOKEN], completed) self.assertCountEqual([LoginType.REGISTRATION_TOKEN], completed)
@ -460,9 +454,9 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
# Do 2 requests without auth to get two session IDs # Do 2 requests without auth to get two session IDs
params1: JsonDict = {"username": "bert", "password": "monkey"} params1: JsonDict = {"username": "bert", "password": "monkey"}
params2: JsonDict = {"username": "ernie", "password": "monkey"} params2: JsonDict = {"username": "ernie", "password": "monkey"}
channel1 = self.make_request(b"POST", self.url, json.dumps(params1)) channel1 = self.make_request(b"POST", self.url, params1)
session1 = channel1.json_body["session"] session1 = channel1.json_body["session"]
channel2 = self.make_request(b"POST", self.url, json.dumps(params2)) channel2 = self.make_request(b"POST", self.url, params2)
session2 = channel2.json_body["session"] session2 = channel2.json_body["session"]
# Use token with both sessions # Use token with both sessions
@ -471,18 +465,18 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session1, "session": session1,
} }
self.make_request(b"POST", self.url, json.dumps(params1)) self.make_request(b"POST", self.url, params1)
params2["auth"] = { params2["auth"] = {
"type": LoginType.REGISTRATION_TOKEN, "type": LoginType.REGISTRATION_TOKEN,
"token": token, "token": token,
"session": session2, "session": session2,
} }
self.make_request(b"POST", self.url, json.dumps(params2)) self.make_request(b"POST", self.url, params2)
# Complete registration with session1 # Complete registration with session1
params1["auth"]["type"] = LoginType.DUMMY params1["auth"]["type"] = LoginType.DUMMY
self.make_request(b"POST", self.url, json.dumps(params1)) self.make_request(b"POST", self.url, params1)
# Check `result` of registration token stage for session1 is `True` # Check `result` of registration token stage for session1 is `True`
result1 = self.get_success( result1 = self.get_success(
@ -550,7 +544,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
# Do request without auth to get a session ID # Do request without auth to get a session ID
params: JsonDict = {"username": "kermit", "password": "monkey"} params: JsonDict = {"username": "kermit", "password": "monkey"}
channel = self.make_request(b"POST", self.url, json.dumps(params)) channel = self.make_request(b"POST", self.url, params)
session = channel.json_body["session"] session = channel.json_body["session"]
# Use token # Use token
@ -559,7 +553,7 @@ class RegisterRestServletTestCase(unittest.HomeserverTestCase):
"token": token, "token": token,
"session": session, "session": session,
} }
self.make_request(b"POST", self.url, json.dumps(params)) self.make_request(b"POST", self.url, params)
# Delete token # Delete token
self.get_success( self.get_success(
@ -827,8 +821,7 @@ class AccountValidityTestCase(unittest.HomeserverTestCase):
admin_tok = self.login("admin", "adminpassword") admin_tok = self.login("admin", "adminpassword")
url = "/_synapse/admin/v1/account_validity/validity" url = "/_synapse/admin/v1/account_validity/validity"
params = {"user_id": user_id} request_data = {"user_id": user_id}
request_data = json.dumps(params)
channel = self.make_request(b"POST", url, request_data, access_token=admin_tok) channel = self.make_request(b"POST", url, request_data, access_token=admin_tok)
self.assertEqual(channel.result["code"], b"200", channel.result) self.assertEqual(channel.result["code"], b"200", channel.result)
@ -845,12 +838,11 @@ class AccountValidityTestCase(unittest.HomeserverTestCase):
admin_tok = self.login("admin", "adminpassword") admin_tok = self.login("admin", "adminpassword")
url = "/_synapse/admin/v1/account_validity/validity" url = "/_synapse/admin/v1/account_validity/validity"
params = { request_data = {
"user_id": user_id, "user_id": user_id,
"expiration_ts": 0, "expiration_ts": 0,
"enable_renewal_emails": False, "enable_renewal_emails": False,
} }
request_data = json.dumps(params)
channel = self.make_request(b"POST", url, request_data, access_token=admin_tok) channel = self.make_request(b"POST", url, request_data, access_token=admin_tok)
self.assertEqual(channel.result["code"], b"200", channel.result) self.assertEqual(channel.result["code"], b"200", channel.result)
@ -870,12 +862,11 @@ class AccountValidityTestCase(unittest.HomeserverTestCase):
admin_tok = self.login("admin", "adminpassword") admin_tok = self.login("admin", "adminpassword")
url = "/_synapse/admin/v1/account_validity/validity" url = "/_synapse/admin/v1/account_validity/validity"
params = { request_data = {
"user_id": user_id, "user_id": user_id,
"expiration_ts": 0, "expiration_ts": 0,
"enable_renewal_emails": False, "enable_renewal_emails": False,
} }
request_data = json.dumps(params)
channel = self.make_request(b"POST", url, request_data, access_token=admin_tok) channel = self.make_request(b"POST", url, request_data, access_token=admin_tok)
self.assertEqual(channel.result["code"], b"200", channel.result) self.assertEqual(channel.result["code"], b"200", channel.result)
@ -1041,16 +1032,14 @@ class AccountValidityRenewalByEmailTestCase(unittest.HomeserverTestCase):
(user_id, tok) = self.create_user() (user_id, tok) = self.create_user()
request_data = json.dumps( request_data = {
{ "auth": {
"auth": { "type": "m.login.password",
"type": "m.login.password", "user": user_id,
"user": user_id, "password": "monkey",
"password": "monkey", },
}, "erase": False,
"erase": False, }
}
)
channel = self.make_request( channel = self.make_request(
"POST", "account/deactivate", request_data, access_token=tok "POST", "account/deactivate", request_data, access_token=tok
) )

View file

@ -12,8 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
from twisted.test.proto_helpers import MemoryReactor from twisted.test.proto_helpers import MemoryReactor
import synapse.rest.admin import synapse.rest.admin
@ -77,10 +75,7 @@ class ReportEventTestCase(unittest.HomeserverTestCase):
def _assert_status(self, response_status: int, data: JsonDict) -> None: def _assert_status(self, response_status: int, data: JsonDict) -> None:
channel = self.make_request( channel = self.make_request(
"POST", "POST", self.report_path, data, access_token=self.other_user_tok
self.report_path,
json.dumps(data),
access_token=self.other_user_tok,
) )
self.assertEqual( self.assertEqual(
response_status, int(channel.result["code"]), msg=channel.result["body"] response_status, int(channel.result["code"]), msg=channel.result["body"]

View file

@ -770,16 +770,14 @@ class RoomsCreateTestCase(RoomBase):
# Build the request's content. We use local MXIDs because invites over federation # Build the request's content. We use local MXIDs because invites over federation
# are more difficult to mock. # are more difficult to mock.
content = json.dumps( content = {
{ "invite": [
"invite": [ "@alice1:red",
"@alice1:red", "@alice2:red",
"@alice2:red", "@alice3:red",
"@alice3:red", "@alice4:red",
"@alice4:red", ]
] }
}
).encode("utf8")
# Test that the invites are correctly ratelimited. # Test that the invites are correctly ratelimited.
channel = self.make_request("POST", "/createRoom", content) channel = self.make_request("POST", "/createRoom", content)
@ -2251,8 +2249,7 @@ class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
# Set a profile for the test user # Set a profile for the test user
self.displayname = "test user" self.displayname = "test user"
data = {"displayname": self.displayname} request_data = {"displayname": self.displayname}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", "PUT",
"/_matrix/client/r0/profile/%s/displayname" % (self.user_id,), "/_matrix/client/r0/profile/%s/displayname" % (self.user_id,),
@ -2264,8 +2261,7 @@ class PerRoomProfilesForbiddenTestCase(unittest.HomeserverTestCase):
self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok) self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
def test_per_room_profile_forbidden(self) -> None: def test_per_room_profile_forbidden(self) -> None:
data = {"membership": "join", "displayname": "other test user"} request_data = {"membership": "join", "displayname": "other test user"}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", "PUT",
"/_matrix/client/r0/rooms/%s/state/m.room.member/%s" "/_matrix/client/r0/rooms/%s/state/m.room.member/%s"
@ -2605,16 +2601,14 @@ class LabelsTestCase(unittest.HomeserverTestCase):
def test_search_filter_labels(self) -> None: def test_search_filter_labels(self) -> None:
"""Test that we can filter by a label on a /search request.""" """Test that we can filter by a label on a /search request."""
request_data = json.dumps( request_data = {
{ "search_categories": {
"search_categories": { "room_events": {
"room_events": { "search_term": "label",
"search_term": "label", "filter": self.FILTER_LABELS,
"filter": self.FILTER_LABELS,
}
} }
} }
) }
self._send_labelled_messages_in_room() self._send_labelled_messages_in_room()
@ -2642,16 +2636,14 @@ class LabelsTestCase(unittest.HomeserverTestCase):
def test_search_filter_not_labels(self) -> None: def test_search_filter_not_labels(self) -> None:
"""Test that we can filter by the absence of a label on a /search request.""" """Test that we can filter by the absence of a label on a /search request."""
request_data = json.dumps( request_data = {
{ "search_categories": {
"search_categories": { "room_events": {
"room_events": { "search_term": "label",
"search_term": "label", "filter": self.FILTER_NOT_LABELS,
"filter": self.FILTER_NOT_LABELS,
}
} }
} }
) }
self._send_labelled_messages_in_room() self._send_labelled_messages_in_room()
@ -2691,16 +2683,14 @@ class LabelsTestCase(unittest.HomeserverTestCase):
"""Test that we can filter by both a label and the absence of another label on a """Test that we can filter by both a label and the absence of another label on a
/search request. /search request.
""" """
request_data = json.dumps( request_data = {
{ "search_categories": {
"search_categories": { "room_events": {
"room_events": { "search_term": "label",
"search_term": "label", "filter": self.FILTER_LABELS_NOT_LABELS,
"filter": self.FILTER_LABELS_NOT_LABELS,
}
} }
} }
) }
self._send_labelled_messages_in_room() self._send_labelled_messages_in_room()
@ -3145,8 +3135,7 @@ class RoomAliasListTestCase(unittest.HomeserverTestCase):
def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None: def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
url = "/_matrix/client/r0/directory/room/" + alias url = "/_matrix/client/r0/directory/room/" + alias
data = {"room_id": self.room_id} request_data = {"room_id": self.room_id}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", url, request_data, access_token=self.room_owner_tok "PUT", url, request_data, access_token=self.room_owner_tok
@ -3175,8 +3164,7 @@ class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None: def _set_alias_via_directory(self, alias: str, expected_code: int = 200) -> None:
url = "/_matrix/client/r0/directory/room/" + alias url = "/_matrix/client/r0/directory/room/" + alias
data = {"room_id": self.room_id} request_data = {"room_id": self.room_id}
request_data = json.dumps(data)
channel = self.make_request( channel = self.make_request(
"PUT", url, request_data, access_token=self.room_owner_tok "PUT", url, request_data, access_token=self.room_owner_tok
@ -3202,7 +3190,7 @@ class RoomCanonicalAliasTestCase(unittest.HomeserverTestCase):
channel = self.make_request( channel = self.make_request(
"PUT", "PUT",
"rooms/%s/state/m.room.canonical_alias" % (self.room_id,), "rooms/%s/state/m.room.canonical_alias" % (self.room_id,),
json.dumps(content), content,
access_token=self.room_owner_tok, access_token=self.room_owner_tok,
) )
self.assertEqual(channel.code, expected_code, channel.result) self.assertEqual(channel.code, expected_code, channel.result)

View file

@ -606,11 +606,10 @@ class UnreadMessagesTestCase(unittest.HomeserverTestCase):
self._check_unread_count(1) self._check_unread_count(1)
# Send a read receipt to tell the server we've read the latest event. # Send a read receipt to tell the server we've read the latest event.
body = json.dumps({ReceiptTypes.READ: res["event_id"]}).encode("utf8")
channel = self.make_request( channel = self.make_request(
"POST", "POST",
f"/rooms/{self.room_id}/read_markers", f"/rooms/{self.room_id}/read_markers",
body, {ReceiptTypes.READ: res["event_id"]},
access_token=self.tok, access_token=self.tok,
) )
self.assertEqual(channel.code, 200, channel.json_body) self.assertEqual(channel.code, 200, channel.json_body)

View file

@ -136,7 +136,7 @@ class RestHelper:
self.site, self.site,
"POST", "POST",
path, path,
json.dumps(content).encode("utf8"), content,
custom_headers=custom_headers, custom_headers=custom_headers,
) )
@ -210,7 +210,7 @@ class RestHelper:
self.site, self.site,
"POST", "POST",
path, path,
json.dumps(data).encode("utf8"), data,
) )
assert ( assert (
@ -309,7 +309,7 @@ class RestHelper:
self.site, self.site,
"PUT", "PUT",
path, path,
json.dumps(data).encode("utf8"), data,
) )
assert ( assert (
@ -392,7 +392,7 @@ class RestHelper:
self.site, self.site,
"PUT", "PUT",
path, path,
json.dumps(content or {}).encode("utf8"), content or {},
custom_headers=custom_headers, custom_headers=custom_headers,
) )

View file

@ -12,7 +12,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
import json
from unittest.mock import Mock from unittest.mock import Mock
from twisted.test.proto_helpers import MemoryReactorClock from twisted.test.proto_helpers import MemoryReactorClock
@ -51,7 +50,7 @@ class TermsTestCase(unittest.HomeserverTestCase):
def test_ui_auth(self): def test_ui_auth(self):
# Do a UI auth request # Do a UI auth request
request_data = json.dumps({"username": "kermit", "password": "monkey"}) request_data = {"username": "kermit", "password": "monkey"}
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
@ -82,16 +81,14 @@ class TermsTestCase(unittest.HomeserverTestCase):
self.assertDictContainsSubset(channel.json_body["params"], expected_params) self.assertDictContainsSubset(channel.json_body["params"], expected_params)
# We have to complete the dummy auth stage before completing the terms stage # We have to complete the dummy auth stage before completing the terms stage
request_data = json.dumps( request_data = {
{ "username": "kermit",
"username": "kermit", "password": "monkey",
"password": "monkey", "auth": {
"auth": { "session": channel.json_body["session"],
"session": channel.json_body["session"], "type": "m.login.dummy",
"type": "m.login.dummy", },
}, }
}
)
self.registration_handler.check_username = Mock(return_value=True) self.registration_handler.check_username = Mock(return_value=True)
@ -102,16 +99,14 @@ class TermsTestCase(unittest.HomeserverTestCase):
self.assertEqual(channel.result["code"], b"401", channel.result) self.assertEqual(channel.result["code"], b"401", channel.result)
# Finish the UI auth for terms # Finish the UI auth for terms
request_data = json.dumps( request_data = {
{ "username": "kermit",
"username": "kermit", "password": "monkey",
"password": "monkey", "auth": {
"auth": { "session": channel.json_body["session"],
"session": channel.json_body["session"], "type": "m.login.terms",
"type": "m.login.terms", },
}, }
}
)
channel = self.make_request(b"POST", self.url, request_data) channel = self.make_request(b"POST", self.url, request_data)
# We're interested in getting a response that looks like a successful # We're interested in getting a response that looks like a successful

View file

@ -16,7 +16,6 @@
import gc import gc
import hashlib import hashlib
import hmac import hmac
import json
import logging import logging
import secrets import secrets
import time import time
@ -619,20 +618,16 @@ class HomeserverTestCase(TestCase):
want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str) want_mac.update(nonce.encode("ascii") + b"\x00" + nonce_str)
want_mac_digest = want_mac.hexdigest() want_mac_digest = want_mac.hexdigest()
body = json.dumps( body = {
{ "nonce": nonce,
"nonce": nonce, "username": username,
"username": username, "displayname": displayname,
"displayname": displayname, "password": password,
"password": password, "admin": admin,
"admin": admin, "mac": want_mac_digest,
"mac": want_mac_digest, "inhibit_login": True,
"inhibit_login": True, }
} channel = self.make_request("POST", "/_synapse/admin/v1/register", body)
)
channel = self.make_request(
"POST", "/_synapse/admin/v1/register", body.encode("utf8")
)
self.assertEqual(channel.code, 200, channel.json_body) self.assertEqual(channel.code, 200, channel.json_body)
user_id = channel.json_body["user_id"] user_id = channel.json_body["user_id"]
@ -676,9 +671,7 @@ class HomeserverTestCase(TestCase):
custom_headers: Optional[Iterable[CustomHeaderType]] = None, custom_headers: Optional[Iterable[CustomHeaderType]] = None,
) -> str: ) -> str:
""" """
Log in a user, and get an access token. Requires the Login API be Log in a user, and get an access token. Requires the Login API be registered.
registered.
""" """
body = {"type": "m.login.password", "user": username, "password": password} body = {"type": "m.login.password", "user": username, "password": password}
if device_id: if device_id:
@ -687,7 +680,7 @@ class HomeserverTestCase(TestCase):
channel = self.make_request( channel = self.make_request(
"POST", "POST",
"/_matrix/client/r0/login", "/_matrix/client/r0/login",
json.dumps(body).encode("utf8"), body,
custom_headers=custom_headers, custom_headers=custom_headers,
) )
self.assertEqual(channel.code, 200, channel.result) self.assertEqual(channel.code, 200, channel.result)