Coverage for tests/common/test_rpc_connection.py: 100%
171 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 19:49 +0000
1import pytest
2import logging
4from monero import MoneroRpcConnection, MoneroConnectionType, MoneroError, MoneroRpcError, MoneroUtils
5from utils import (
6 TestUtils as Utils, RpcConnectionUtils,
7 StringUtils, BaseTestClass, FakeDaemonRpcServer
8)
10logger: logging.Logger = logging.getLogger("TestMoneroRpcConnection")
13@pytest.mark.integration
14class TestMoneroRpcConnection(BaseTestClass):
15 """Rpc connection integration tests."""
17 TIMEOUT_MS: int = Utils.AUTO_CONNECT_TIMEOUT_MS * 5
18 """Rpc connection timeout in milliseconds."""
20 # region Fixtures
22 # Node rpc connection fixture
23 @pytest.fixture(scope="class")
24 @classmethod
25 def node_connection(cls) -> MoneroRpcConnection:
26 """Rpc connection test instance."""
27 return MoneroRpcConnection(Utils.DAEMON_RPC_URI, Utils.DAEMON_RPC_USERNAME, Utils.DAEMON_RPC_PASSWORD, timeout_ms=cls.TIMEOUT_MS)
29 # Wallet rpc connection fixture
30 @pytest.fixture(scope="class")
31 @classmethod
32 def wallet_connection(cls) -> MoneroRpcConnection:
33 """Rpc connection test instance."""
34 return MoneroRpcConnection(Utils.WALLET_RPC_URI, Utils.WALLET_RPC_USERNAME, Utils.WALLET_RPC_PASSWORD, timeout_ms=cls.TIMEOUT_MS)
36 #endregion
38 #region Tests
40 # Validate uri type
41 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
42 def test_validate_uri(self) -> None:
43 # test daemon uri
44 connection: MoneroRpcConnection = MoneroRpcConnection(Utils.DAEMON_RPC_URI)
45 assert not connection.is_onion()
46 assert not connection.is_i2p()
48 # test onion uri
49 connection.uri = "http://moneronkvv2hu2anvcc5b4qd5y7strnc2ob6khqsrtikmhocyvjpdjyd.onion:18089"
50 assert connection.is_onion()
51 assert not connection.is_i2p()
53 # test i2p uri
54 connection.uri = "http://2rcznulrxqlygrk2qumpwkbonnh72fujukk5nmrcuuzrkl5rn5ta.b32.i2p:18081"
55 assert not connection.is_onion()
56 assert connection.is_i2p()
58 # test empty uri
59 connection.uri = ""
60 assert not connection.is_onion()
61 assert not connection.is_i2p()
63 # test None uri
64 connection.uri = None
65 assert not connection.is_onion()
66 assert not connection.is_i2p()
68 # Test rpc connection json serialization
69 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
70 def test_rpc_connection_serialization(self, node_connection: MoneroRpcConnection, wallet_connection: MoneroRpcConnection) -> None:
71 # test node connection serialization
72 connection_str: str = node_connection.serialize()
73 assert '{"uri":"http://127.0.0.1:18081","username":"rpc_daemon_user","password":"abc123","priority":0,"timeoutMs":15000,"sslVerify":true}' == connection_str
75 # node wallet connection serialization
76 connection_str = wallet_connection.serialize()
77 assert '{"uri":"http://127.0.0.1:18082","username":"rpc_user","password":"abc123","priority":0,"timeoutMs":15000,"sslVerify":true}' == connection_str
79 # test empty connection
80 connection: MoneroRpcConnection = MoneroRpcConnection()
81 connection_str = connection.serialize()
82 assert '{"priority":0,"sslVerify":true}' == connection.serialize()
84 # test connection
85 connection = MoneroRpcConnection("test_node:18081", "user", "abc123", "127.0.0.1:9050", "test_node:18084", 1, 1000)
86 connection_str = connection.serialize()
87 assert '{"uri":"test_node:18081","username":"user","password":"abc123","proxyUri":"127.0.0.1:9050","zmqUri":"test_node:18084","priority":1,"timeoutMs":1000,"sslVerify":true}' == connection_str
89 # Can disable the verification of the TLS certificate
90 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
91 def test_ssl_verify(self) -> None:
92 # verified by default
93 connection: MoneroRpcConnection = MoneroRpcConnection("https://node.example:18081")
94 assert connection.ssl_verify is True
96 # can be disabled, the setting is serialized and copied
97 connection.ssl_verify = False
98 assert connection.ssl_verify is False
99 assert '"sslVerify":false' in connection.serialize()
100 assert MoneroRpcConnection(connection).ssl_verify is False
101 assert MoneroRpcConnection.deserialize(connection.serialize()).ssl_verify is False
103 # connections that don't mention it stay verified
104 assert MoneroRpcConnection.deserialize('{"uri":"https://node.example:18081"}').ssl_verify is True
106 # Can copy a rpc connection
107 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
108 def test_connection_copy(self, node_connection: MoneroRpcConnection) -> None:
109 # test copy
110 copy: MoneroRpcConnection = MoneroRpcConnection(node_connection)
111 assert copy.serialize() == node_connection.serialize()
113 # Test monerod rpc connection
114 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
115 def test_node_rpc_connection(self, node_connection: MoneroRpcConnection) -> None:
116 RpcConnectionUtils.test_rpc_connection(node_connection, Utils.DAEMON_RPC_URI, True, MoneroConnectionType.IPV4)
118 # Test wallet rpc connection
119 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
120 def test_wallet_rpc_connection(self, wallet_connection: MoneroRpcConnection) -> None:
121 RpcConnectionUtils.test_rpc_connection(wallet_connection, Utils.WALLET_RPC_URI, True, MoneroConnectionType.IPV4)
123 # Test invalid connection
124 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
125 def test_invalid_connection(self) -> None:
126 connection: MoneroRpcConnection = MoneroRpcConnection(Utils.OFFLINE_SERVER_URI)
127 RpcConnectionUtils.test_rpc_connection(connection, Utils.OFFLINE_SERVER_URI, False, MoneroConnectionType.INVALID)
129 # Can set credentials
130 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
131 def test_set_credentials(self) -> None:
132 # create connection
133 connection: MoneroRpcConnection = MoneroRpcConnection(Utils.DAEMON_RPC_URI)
135 # test connection without credentials
136 assert connection.username is None
137 assert connection.password is None
139 # test set credentials
140 connection.set_credentials(Utils.DAEMON_RPC_USERNAME, Utils.DAEMON_RPC_PASSWORD)
142 assert not connection.is_online(), "Expected not online"
143 assert not connection.is_authenticated(), "Expected not authenticated"
144 assert not connection.is_connected(), "Expected not connected"
146 # test connection
147 assert connection.username == Utils.DAEMON_RPC_USERNAME
148 assert connection.password == Utils.DAEMON_RPC_PASSWORD
150 assert connection.check_connection(), "Could not check connection"
152 assert connection.is_online(), "Expected online after check"
153 assert connection.is_authenticated(), "Not authenticated"
154 assert connection.is_connected(), "Expected connected after check"
156 # test empty credentials
157 connection.set_credentials("", "")
159 assert not connection.is_online(), "Expected not online"
160 assert not connection.is_authenticated(), "Expected not authenticated"
161 assert not connection.is_connected(), "Expected not connected"
163 assert connection.username is None
164 assert connection.password is None
166 # Test invalid credentials
167 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
168 def test_set_invalid_credentials(self) -> None:
169 # create test connection
170 connection: MoneroRpcConnection = MoneroRpcConnection(Utils.DAEMON_RPC_URI, Utils.DAEMON_RPC_USERNAME, Utils.DAEMON_RPC_PASSWORD)
172 # username / password are read-only properties (set via set_credentials())
173 with pytest.raises(AttributeError, match="object has no setter"):
174 connection.username = "user" # type: ignore
176 with pytest.raises(AttributeError, match="object has no setter"):
177 connection.password = "abc123" # type: ignore
179 # set invalid username
180 with pytest.raises(RuntimeError, match="username cannot be empty because password is not empty"):
181 connection.set_credentials("", "abc123")
183 # set invalid password
184 with pytest.raises(RuntimeError, match="password cannot be empty because username is not empty"):
185 connection.set_credentials("user", "")
187 # test connection
188 assert connection.username == Utils.DAEMON_RPC_USERNAME
189 assert connection.password == Utils.DAEMON_RPC_PASSWORD
191 connection.set_credentials("user", "abc123")
193 # test connection
194 assert connection.username == "user"
195 assert connection.password == "abc123"
197 assert connection.check_connection()
198 assert connection.is_online()
199 assert connection.is_authenticated() is False
200 assert connection.is_connected() is False
202 # Can get and set arbitrary key/value attributes
203 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
204 def test_set_attributes(self, node_connection: MoneroRpcConnection) -> None:
205 # set attributes
206 attr_range: range = range(100)
208 for i in attr_range:
209 assert node_connection.get_attribute(f"attr{i}") == ""
211 attrs: dict[str, str] = {}
212 for i in attr_range:
213 key: str = f"attr{i}"
214 val: str = StringUtils.get_random_string()
215 attrs[key] = val
216 node_connection.set_attribute(key, val)
218 # test attributes
219 for key in attrs:
220 val = attrs[key]
221 assert val == node_connection.get_attribute(key)
223 # Test connection priorities
224 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
225 def test_priority(self) -> None:
226 for i in range(100):
227 for j in range(100):
228 expected: bool = (i == 0 and j != 0) or (i != 0 and j != 0 and i > j)
229 assert MoneroRpcConnection.compare(i, j) is expected
231 # Can send json request
232 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
233 def test_send_json_request(self, node_connection: MoneroRpcConnection) -> None:
234 RpcConnectionUtils.setup_rpc_connection(node_connection)
235 result: object = node_connection.send_json_request("get_version")
236 assert result is not None
237 logger.debug(f"JSON-RPC response {result}")
239 # test invalid json rpc method
240 with pytest.raises(MoneroRpcError) as exc_info:
241 node_connection.send_json_request("invalid_method")
242 assert str(exc_info.value) == "Method not found"
243 assert exc_info.value.code == -32601
245 # Can send binary request
246 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
247 def test_send_binary_request(self, node_connection: MoneroRpcConnection) -> None:
248 RpcConnectionUtils.setup_rpc_connection(node_connection)
249 parameters: dict[str, list[int]] = { "heights": list(range(100)) }
250 bin_result: bytes | None = node_connection.send_binary_request("get_blocks_by_height.bin", parameters)
251 assert bin_result is not None
252 logger.debug(f"Binary response: {bin_result}")
253 json_result: str = MoneroUtils.binary_blocks_to_json(bin_result)
254 logger.debug(f"Deserialized binary response: {StringUtils.prettify(json_result)}")
256 # test invalid binary method
257 with pytest.raises(MoneroRpcError) as exc_info:
258 node_connection.send_binary_request("invalid_method")
259 assert exc_info.value.code == 404
261 # Can send path request
262 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled")
263 def test_send_path_request(self, node_connection: MoneroRpcConnection) -> None:
264 RpcConnectionUtils.setup_rpc_connection(node_connection)
265 result: object = node_connection.send_path_request("get_height")
266 assert result is not None
267 logger.debug(f"Path response {result}")
269 # test invalid path method
270 with pytest.raises(MoneroRpcError) as exc_info:
271 node_connection.send_path_request("invalid_method")
272 assert exc_info.value.code == 404
274 #endregion
277@pytest.mark.unit
278class TestMoneroRpcConnectionTimeout(BaseTestClass):
279 """Rpc connection request timeout unit tests, on a local rpc server that answers late."""
281 # Can apply the timeout of a request to the request
282 @pytest.mark.parametrize("kind", ["json", "path", "binary"])
283 def test_send_request_timeout(self, kind: str) -> None:
284 # the bindings hold the gil for the whole request, so the server in this process answers only after the timeout: enough to see
285 # which timeout the request got
286 with FakeDaemonRpcServer(response_delay=0.5) as server:
287 connection: MoneroRpcConnection = MoneroRpcConnection(server.uri)
288 send = {"json": connection.send_json_request, "path": connection.send_path_request, "binary": connection.send_binary_request}[kind]
289 with pytest.raises(MoneroError, match=r"Network error: no response from .* \(timeout: 100ms\)"):
290 send("get_last_block_header", timeout_ms=100)