From dfc37129da76b4ced656bc072e701cdc475a1b3b Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Tue, 24 Nov 2026 11:07:36 +0100 Subject: [PATCH 1/4] bindings: compare the serializable structs by value and represent them with their json --- .../mkdocs/docs/en/api/serializable_struct.md | 14 ++ docs/mkdocs/docs/en/tests/files/common.md | 1 + src/cpp/common/py_monero_common.cpp | 29 +++ src/cpp/common/py_monero_common.h | 18 ++ src/cpp/common/py_monero_common_bindings.cpp | 17 ++ src/cpp/wallet/py_monero_wallet_bindings.cpp | 3 + src/monero/monero_rpc_connection.pyi | 21 +++ src/monero/monero_wallet_config.pyi | 10 + src/monero/serializable_struct.pyi | 30 ++- tests/common/test_serializable_struct.py | 174 ++++++++++++++++++ tests/utils/assert_utils.py | 4 - tests/utils/test_utils.py | 3 +- 12 files changed, 317 insertions(+), 7 deletions(-) create mode 100644 tests/common/test_serializable_struct.py diff --git a/docs/mkdocs/docs/en/api/serializable_struct.md b/docs/mkdocs/docs/en/api/serializable_struct.md index a8ed9167..5e793348 100644 --- a/docs/mkdocs/docs/en/api/serializable_struct.md +++ b/docs/mkdocs/docs/en/api/serializable_struct.md @@ -18,4 +18,18 @@ def carry(result: MoneroKeyImageExportResult) -> MoneroKeyImageExportResult: It is how an object goes from a process or a machine to another ([Signing Offline with a Cold Wallet](../examples/scenarios/cold_signing.md)). +Two objects of the same class are equal if they serialize the same, so `==` compares what they hold and not whether they are the +same object. Like with monero-java, the back references are left out: a tx does not compare its block, an output its tx. The +objects can be changed, so they are not hashable: they can not be keys of a `dict` or go in a `set`. + +```python +assert wallet.get_tx(tx_hash) == wallet.get_tx(tx_hash) # two objects, equal +print(repr(tx)) # MoneroTxWallet({"hash":"...",...}) +``` + +The `repr` of an object is its class with its JSON. [`MoneroRpcConnection`][monero.MoneroRpcConnection] and +[`MoneroWalletConfig`][monero.MoneroWalletConfig] hide their password, seed and private keys there, while `serialize()` keeps +them. A connection equals another with the same uri, credentials, proxy, zmq uri and ssl verify, whatever its priority, its timeout +or its state. + ::: monero.SerializableStruct diff --git a/docs/mkdocs/docs/en/tests/files/common.md b/docs/mkdocs/docs/en/tests/files/common.md index a45adb8b..b246e507 100644 --- a/docs/mkdocs/docs/en/tests/files/common.md +++ b/docs/mkdocs/docs/en/tests/files/common.md @@ -8,6 +8,7 @@ What is not about a wallet or a daemon. | File | Marker | What it tests | | --- | --- | --- | | `test_common.py` | unit | `MoneroError`, the serialization of the structs, the SSL options | +| `test_serializable_struct.py` | unit | the equality, the hash and the `repr` of the structs, of `MoneroRpcConnection` and of `MoneroWalletConfig` | | `test_rpc_connection.py` | integration | `MoneroRpcConnection`: the validation of the uri, the copy and the serialization, the credentials, the priority, the connections to a node and to a wallet rpc server, the json, binary and path requests | | `test_gen_utils.py` | unit | the helpers of the tests: the uuids, the waits, and the reconciliation of the values of two models (the rules of `merge`) | | `test_block_generation.py` | unit | the choice of the tests between generating blocks (at a low difficulty) and mining them | diff --git a/src/cpp/common/py_monero_common.cpp b/src/cpp/common/py_monero_common.cpp index 96212ed1..5f523684 100644 --- a/src/cpp/common/py_monero_common.cpp +++ b/src/cpp/common/py_monero_common.cpp @@ -52,6 +52,8 @@ * Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers */ #include "py_monero_common.h" +#include "utils/gen_utils.h" +#include // --------------------------- GEN UTILS --------------------------- @@ -131,6 +133,33 @@ py::object PyGenUtils::parse_rpc_response(const std::string& body, const std::st return response_dict.contains("jsonrpc") ? py::none() : response; } +// replaces the non-empty strings of the keys with ***, at any depth, like the password of the server of a wallet config +static void redact(rapidjson::Value& val, const std::vector& keys) { + if (val.IsArray()) { + for (auto& item : val.GetArray()) redact(item, keys); + return; + } + if (!val.IsObject()) return; + for (auto& member : val.GetObject()) { + bool secret = std::find(keys.begin(), keys.end(), member.name.GetString()) != keys.end(); + if (secret && member.value.IsString() && member.value.GetStringLength() > 0) member.value.SetString("***"); + else redact(member.value, keys); + } +} + +std::string PyGenUtils::serialize_redacted(const serializable_struct& s, const std::vector& keys) { + rapidjson::Document doc; + doc.SetObject(); + rapidjson::Value val = s.to_rapidjson_val(doc.GetAllocator()); + val.Swap(doc); + redact(doc, keys); + return gen_utils::serialize(doc); +} + +py::str PyGenUtils::repr(const py::object& self, const std::string& json) { + return py::str("{}({})").format(py::type::of(self).attr("__name__"), json); +} + // --------------------------- MONERO REQUEST PARAMS --------------------------- PyMoneroRequestParams::PyMoneroRequestParams(const boost::optional& py_params) { diff --git a/src/cpp/common/py_monero_common.h b/src/cpp/common/py_monero_common.h index b7848d83..635920ae 100644 --- a/src/cpp/common/py_monero_common.h +++ b/src/cpp/common/py_monero_common.h @@ -124,6 +124,24 @@ class PyGenUtils { * @return the result of a JSON-RPC response, or the whole response of a path request */ static py::object parse_rpc_response(const std::string& body, const std::string& method, const std::string& uri, bool json_rpc); + + /** + * Serialize a struct with the non-empty strings of the given keys replaced by ***, at any depth. + * + * @param s is the struct to serialize + * @param keys are the json keys of the secrets to hide, like "password" + * @return the json of the struct without its secrets + */ + static std::string serialize_redacted(const serializable_struct& s, const std::vector& keys); + + /** + * Represent a struct as the name of its python type with its json. + * + * @param self is the struct + * @param json is the json to show + * @return the representation, like MoneroTx({...}) + */ + static py::str repr(const py::object& self, const std::string& json); }; /** diff --git a/src/cpp/common/py_monero_common_bindings.cpp b/src/cpp/common/py_monero_common_bindings.cpp index dcd55e1a..f3e473ac 100644 --- a/src/cpp/common/py_monero_common_bindings.cpp +++ b/src/cpp/common/py_monero_common_bindings.cpp @@ -230,6 +230,14 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) { t.py_serializable_struct .def("serialize", [](serializable_struct& self) { MONERO_CATCH_AND_RETHROW(self.serialize()); + }) + .def("__eq__", [](const py::object& self, const py::object& other) -> py::object { + // structs of the same type are equal if they serialize the same, without their back references like monero-java + if (!py::type::of(self).is(py::type::of(other))) return py::reinterpret_borrow(Py_NotImplemented); + MONERO_CATCH_AND_RETHROW(py::bool_(self.cast().serialize() == other.cast().serialize())); + }, py::arg("other"), py::is_operator()) + .def("__repr__", [](const py::object& self) { + MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, self.cast().serialize())); }); // monero_rpc_payment_info @@ -263,6 +271,15 @@ void py_monero_bind_common(py::module_& m, PyMoneroTypes& t) { .def_static("deserialize", [](const std::string& json) { MONERO_CATCH_AND_RETHROW(monero_rpc_connection::deserialize(json)); }, py::arg("json")) + .def("__eq__", [](const monero_rpc_connection& self, const py::object& other) -> py::object { + // compare the config of the connections like monero-java, not their state + if (!py::isinstance(other)) return py::reinterpret_borrow(Py_NotImplemented); + const monero_rpc_connection& connection = other.cast(); + return py::bool_(self.m_uri == connection.m_uri && self.m_username == connection.m_username && self.m_password == connection.m_password && self.m_proxy_uri == connection.m_proxy_uri && self.m_zmq_uri == connection.m_zmq_uri && self.m_ssl_verify == connection.m_ssl_verify); + }, py::arg("other"), py::is_operator()) + .def("__repr__", [](const py::object& self) { + MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, PyGenUtils::serialize_redacted(self.cast(), {"password"}))); + }) .def_property("uri", [](const monero_rpc_connection& self) { return self.m_uri; }, [](monero_rpc_connection& self, const boost::optional& val) { diff --git a/src/cpp/wallet/py_monero_wallet_bindings.cpp b/src/cpp/wallet/py_monero_wallet_bindings.cpp index bff4e068..9612f6da 100644 --- a/src/cpp/wallet/py_monero_wallet_bindings.cpp +++ b/src/cpp/wallet/py_monero_wallet_bindings.cpp @@ -108,6 +108,9 @@ void py_monero_bind_wallet(py::module_& m, PyMoneroTypes& t) { .def_readwrite("regtest", &monero_wallet_config::m_regtest) .def("copy", [](monero_wallet_config& self) { MONERO_CATCH_AND_RETHROW(self.copy()); + }) + .def("__repr__", [](const py::object& self) { + MONERO_CATCH_AND_RETHROW(PyGenUtils::repr(self, PyGenUtils::serialize_redacted(self.cast(), {"password", "seed", "seedOffset", "privateViewKey", "privateSpendKey"}))); }); // monero_subaddress diff --git a/src/monero/monero_rpc_connection.pyi b/src/monero/monero_rpc_connection.pyi index 41a3533c..af701fa0 100644 --- a/src/monero/monero_rpc_connection.pyi +++ b/src/monero/monero_rpc_connection.pyi @@ -34,6 +34,27 @@ class MoneroRpcConnection(SerializableStruct): """Connection response time in milliseconds.""" ... + @typing.override + def __eq__(self, other: object) -> bool: + """ + Compare this connection to another like monero-java: by uri, username, password, proxy uri, zmq uri and ssl verify. + The priority, the timeout and the state of the connections, like the response time, are not compared. + + :param object other: connection to compare against. + + :returns bool: `True` if `other` is a connection with the same config. + """ + ... + + @typing.override + def __repr__(self) -> str: + """ + Represent this connection as its json, with the password hidden. + + :returns str: e.g. `MoneroRpcConnection({"uri":"http://localhost:28081","username":"rpc_user","password":"***",...})`. + """ + ... + @staticmethod def compare(p1: int, p2: int) -> bool: """ diff --git a/src/monero/monero_wallet_config.pyi b/src/monero/monero_wallet_config.pyi index 546b6435..fefb056b 100644 --- a/src/monero/monero_wallet_config.pyi +++ b/src/monero/monero_wallet_config.pyi @@ -76,3 +76,13 @@ class MoneroWalletConfig(SerializableStruct): :returns MoneroWalletConfig: Copy of the wallet config. """ ... + + @typing.override + def __repr__(self) -> str: + """ + Represent this config as its json, with the password, the seed, its offset, the private keys and the password of its + server hidden. + + :returns str: e.g. `MoneroWalletConfig({"networkType":2,"path":"wallets/main","password":"***",...})`. + """ + ... diff --git a/src/monero/serializable_struct.pyi b/src/monero/serializable_struct.pyi index f59044d1..cfedbdee 100644 --- a/src/monero/serializable_struct.pyi +++ b/src/monero/serializable_struct.pyi @@ -1,8 +1,16 @@ +import typing + from abc import ABC class SerializableStruct(ABC): - """Base struct which can be serialized.""" + """Base struct which can be serialized. + + Structs of the same type are equal if they serialize the same: the back references, like the block of a tx or the tx + of an output, are not compared. Structs are mutable, so they are not hashable. + """ + + __hash__: typing.ClassVar[None] # type: ignore[assignment] def serialize(self) -> str: """ @@ -11,3 +19,23 @@ class SerializableStruct(ABC): :returns str: the struct serialized to a json string. """ ... + + @typing.override + def __eq__(self, other: object) -> bool: + """ + Compare this struct to another by their serialization. + + :param object other: struct to compare against. + + :returns bool: `True` if `other` has the same type and serializes the same. + """ + ... + + @typing.override + def __repr__(self) -> str: + """ + Represent this struct as its type with its json. + + :returns str: e.g. `MoneroSubaddress({"accountIndex":0,"index":1})`. + """ + ... diff --git a/tests/common/test_serializable_struct.py b/tests/common/test_serializable_struct.py new file mode 100644 index 00000000..8d106ee5 --- /dev/null +++ b/tests/common/test_serializable_struct.py @@ -0,0 +1,174 @@ +import pytest +import logging + +from monero import ( + MoneroBlock, MoneroOutput, MoneroOutputWallet, MoneroRpcConnection, MoneroSubaddress, MoneroTx, MoneroTxWallet, + MoneroWalletConfig +) + +from utils import BaseTestClass + +logger: logging.Logger = logging.getLogger("TestSerializableStruct") + + +@pytest.mark.unit +class TestSerializableStruct(BaseTestClass): + """Equality and representation of the serializable structs unit tests.""" + + # Can compare structs of the same type by value + def test_equals(self) -> None: + subaddress1: MoneroSubaddress = self._get_subaddress() + subaddress2: MoneroSubaddress = self._get_subaddress() + assert subaddress1 is not subaddress2 + assert subaddress1 == subaddress2 + assert not subaddress1 != subaddress2 + + subaddress2.label = "other label" + assert subaddress1 != subaddress2 + + # a struct does not equal another type + assert MoneroOutput() != MoneroOutputWallet() + assert MoneroTx() != MoneroTxWallet() + assert MoneroSubaddress() != MoneroSubaddress().serialize() + assert MoneroSubaddress() != None # noqa: E711 + + # Can compare the children of the structs but not their back references + def test_equals_children(self) -> None: + tx1: MoneroTx = self._get_tx() + tx2: MoneroTx = self._get_tx() + assert tx1 == tx2 + + # the outputs are compared + tx2.outputs[0].amount = 2 + assert tx1 != tx2 + tx2.outputs[0].amount = 1 + assert tx1 == tx2 + + # the block of a tx and the tx of an output are back references, like with monero-java + block: MoneroBlock = MoneroBlock() + block.height = 10 + block.txs = [tx1] + tx1.block = block + assert tx1.block is not None + assert tx2.block is None + assert tx1 == tx2 + assert tx1.outputs[0] == tx2.outputs[0] + + # the txs of a block are its children + other_block: MoneroBlock = MoneroBlock() + other_block.height = 10 + assert block != other_block + other_block.txs = [tx2] + assert block == other_block + + # Cannot hash the structs, which are mutable + @pytest.mark.parametrize("struct", [MoneroSubaddress(), MoneroTxWallet(), MoneroRpcConnection(), MoneroWalletConfig()]) + def test_not_hashable(self, struct: object) -> None: + with pytest.raises(TypeError, match="unhashable type"): + hash(struct) + + # Can represent a struct as its type with its json + def test_repr(self) -> None: + subaddress: MoneroSubaddress = self._get_subaddress() + assert repr(subaddress) == f"MoneroSubaddress({subaddress.serialize()})" + + # the type is the one of the struct, not the one of the binding that returns it + tx: MoneroTx = self._get_tx() + assert repr(tx.outputs[0]).startswith("MoneroOutputWallet(") + + # Can compare the config of the connections and not their state + def test_connection_equals(self) -> None: + connection1: MoneroRpcConnection = MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123", "socks5://127.0.0.1:9050") + connection2: MoneroRpcConnection = MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123", "socks5://127.0.0.1:9050") + assert connection1 == connection2 + + # the priority and the timeout are not compared, like with monero-java + connection2.priority = 1 + connection2.timeout_ms = 1000 + assert connection1 == connection2 + + # the uri, the credentials, the proxy, the zmq uri and the ssl verify are + for connection in ( + MoneroRpcConnection("http://localhost:28082", "rpc_user", "abc123", "socks5://127.0.0.1:9050"), + MoneroRpcConnection("http://localhost:28081", "other_user", "abc123", "socks5://127.0.0.1:9050"), + MoneroRpcConnection("http://localhost:28081", "rpc_user", "other_password", "socks5://127.0.0.1:9050"), + MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123"), + MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123", "socks5://127.0.0.1:9050", "tcp://127.0.0.1:18083"), + ): + assert connection1 != connection + connection2.ssl_verify = not connection1.ssl_verify + assert connection1 != connection2 + + # a copy equals the connection + assert MoneroRpcConnection(connection1) == connection1 + assert connection1 != connection1.uri + + # Cannot see the password of a connection in its representation + def test_connection_repr(self) -> None: + connection: MoneroRpcConnection = MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123") + representation: str = repr(connection) + assert representation.startswith("MoneroRpcConnection(") + assert "http://localhost:28081" in representation + assert "rpc_user" in representation + assert "abc123" not in representation + assert '"password":"***"' in representation + assert "abc123" in connection.serialize() + + # a connection without password has none to hide + assert "***" not in repr(MoneroRpcConnection("http://localhost:28081")) + + # Cannot see the secrets of a wallet config in its representation + def test_wallet_config_repr(self) -> None: + secrets: list[str] = ["supersecretpassword123", "my seed words", "my seed offset", "my private view key", "my private spend key"] + config: MoneroWalletConfig = MoneroWalletConfig() + config.path = "wallets/main" + config.primary_address = "my primary address" + config.password, config.seed, config.seed_offset, config.private_view_key, config.private_spend_key = secrets + representation: str = repr(config) + assert representation.startswith("MoneroWalletConfig(") + assert "wallets/main" in representation + assert "my primary address" in representation + for secret in secrets: + assert secret not in representation + assert secret in config.serialize() + assert representation.count('"***"') == len(secrets) + + # the password of its server too + config.server = MoneroRpcConnection("http://localhost:28081", "rpc_user", "abc123") + representation = repr(config) + assert "rpc_user" in representation + assert "abc123" not in representation + assert representation.count('"***"') == len(secrets) + 1 + + # the config is compared with its secrets + other: MoneroWalletConfig = config.copy() + assert other == config + other.seed = "other seed words" + assert other != config + + #region Utils + + @classmethod + def _get_subaddress(cls) -> MoneroSubaddress: + subaddress: MoneroSubaddress = MoneroSubaddress() + subaddress.account_index = 0 + subaddress.index = 1 + subaddress.address = "my address" + subaddress.label = "my label" + subaddress.balance = 100 + subaddress.is_used = True + return subaddress + + @classmethod + def _get_tx(cls) -> MoneroTx: + tx: MoneroTx = MoneroTxWallet() + tx.hash = "my tx hash" + tx.fee = 10 + output: MoneroOutputWallet = MoneroOutputWallet() + output.amount = 1 + output.account_index = 0 + output.tx = tx + tx.outputs = [output] + return tx + + #endregion diff --git a/tests/utils/assert_utils.py b/tests/utils/assert_utils.py index 2257d240..033e9451 100644 --- a/tests/utils/assert_utils.py +++ b/tests/utils/assert_utils.py @@ -25,10 +25,6 @@ def assert_equals(cls, expr1: Any, expr2: Any, message: str = "assertion failed" assert expr1.proxy_uri == expr2.proxy_uri assert expr1.priority == expr2.priority assert expr1.timeout_ms == expr2.timeout_ms - elif isinstance(expr1, SerializableStruct) and isinstance(expr2, SerializableStruct): - str1: str = expr1.serialize() - str2: str = expr2.serialize() - assert str1 == str2, f"{message}: {str1} == {str2}" else: assert expr1 == expr2, f"{message}: {expr1} == {expr2}" diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py index ba265cb1..f9098b28 100644 --- a/tests/utils/test_utils.py +++ b/tests/utils/test_utils.py @@ -409,8 +409,7 @@ def get_wallet_full(cls) -> MoneroWalletFull: cls._WALLET_FULL = MoneroWalletFull.create_wallet(config) logger.debug(f"Created full wallet at path '{cls.WALLET_FULL_PATH}'") assert cls.FIRST_RECEIVE_HEIGHT == cls._WALLET_FULL.get_restore_height() - # TODO implement __eq__ method - #assert daemon_connection == cls._WALLET_FULL.get_daemon_connection() + assert daemon_connection == cls._WALLET_FULL.get_daemon_connection() # otherwise open existing wallet and update daemon connection else: From a44f146d660f01ab73826488b32a2a8038711837 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Tue, 24 Nov 2026 13:05:20 +0100 Subject: [PATCH 2/4] tests: check the references of the models with is like monero-java --- tests/utils/block_utils.py | 2 +- tests/utils/daemon_notification_collector.py | 6 +++--- tests/utils/from_multiple_tx_sender.py | 2 +- tests/utils/output_utils.py | 4 ++-- tests/utils/single_tx_sender.py | 2 +- tests/utils/sync_with_pool_submit_tester.py | 2 +- tests/utils/to_multiple_tx_sender.py | 2 +- tests/utils/tx_tester.py | 4 ++-- tests/utils/tx_utils.py | 2 +- tests/utils/tx_wallet_tester.py | 4 ++-- tests/utils/tx_wallet_utils.py | 2 +- tests/utils/txs_structure_tester.py | 19 ++++++++++--------- tests/wallet/model/test_output_query.py | 14 +++++++------- tests/wallet/model/test_transfer_query.py | 8 ++++---- tests/wallet/model/test_tx_query.py | 18 +++++++++--------- tests/wallet/test_creation.py | 6 +++--- tests/wallet/test_outputs.py | 2 +- tests/wallet/test_transfers.py | 2 +- tests/wallet/test_txs.py | 2 +- 19 files changed, 52 insertions(+), 51 deletions(-) diff --git a/tests/utils/block_utils.py b/tests/utils/block_utils.py index f46393de..3b9d2ff8 100644 --- a/tests/utils/block_utils.py +++ b/tests/utils/block_utils.py @@ -125,7 +125,7 @@ def test_block(cls, block: MoneroBlock, ctx: TestContext) -> None: if ctx.has_txs: assert ctx.tx_context is not None for tx in block.txs: - assert block == tx.block + assert block is tx.block TxUtils.test_tx(tx, ctx.tx_context) # test duplicates diff --git a/tests/utils/daemon_notification_collector.py b/tests/utils/daemon_notification_collector.py index 02a0c344..682dc812 100644 --- a/tests/utils/daemon_notification_collector.py +++ b/tests/utils/daemon_notification_collector.py @@ -14,7 +14,7 @@ class DaemonNotificationCollector(MoneroDaemonListener): """Daemon instance.""" listening: bool """Indicates if listener is expected to be active.""" - block_headers: set[MoneroBlockHeader] + block_headers: list[MoneroBlockHeader] """Collection of block headers seen by the daemon.""" block_hashes: set[str] """Collection of block hashes seen by the daemon.""" @@ -52,7 +52,7 @@ def __init__(self, daemon: MoneroDaemonRpc, auto_remove: bool = False) -> None: self.listening = True self.daemon = daemon self.auto_remove = auto_remove - self.block_headers = set() + self.block_headers = [] self.block_hashes = set() self.last_block_height = None self.errors = [] @@ -68,7 +68,7 @@ def on_block_header(self, header: MoneroBlockHeader) -> None: assert header.hash is not None assert header.hash not in self.block_hashes, f"Duplicate block header found: {header.hash}" self.block_hashes.add(header.hash) - self.block_headers.add(header) + self.block_headers.append(header) assert header.height is not None if self.last_block_height is not None and header.height != self.last_block_height + 1: diff --git a/tests/utils/from_multiple_tx_sender.py b/tests/utils/from_multiple_tx_sender.py index 3560e81d..ee55466a 100644 --- a/tests/utils/from_multiple_tx_sender.py +++ b/tests/utils/from_multiple_tx_sender.py @@ -141,7 +141,7 @@ def send(self) -> None: assert len(txs) == 1 # test that config is unchanged - assert config_copy != self._config + assert config_copy is not self._config AssertUtils.assert_equals(config_copy, self._config) # test that balances of intended subaddresses decreased diff --git a/tests/utils/output_utils.py b/tests/utils/output_utils.py index 723a8f58..14b4f3af 100644 --- a/tests/utils/output_utils.py +++ b/tests/utils/output_utils.py @@ -144,13 +144,13 @@ def test_output_wallet(cls, output: Optional[MoneroOutputWallet]) -> None: # test copying copy: MoneroOutputWallet = output.copy() - assert copy != output + assert copy is not output AssertUtils.assert_equals(copy, output) # TODO: should output copy do deep copy of tx so models are graph instead of tree? Would need to work out circular references # monero-cpp gives non-null output tx # assert copy.tx is None assert copy.tx is not None - assert copy.tx == output.tx + assert copy.tx is output.tx @classmethod def get_and_test_outputs(cls, wallet: MoneroWallet, query: Optional[MoneroOutputQuery], is_expected: Optional[bool]) -> list[MoneroOutputWallet]: diff --git a/tests/utils/single_tx_sender.py b/tests/utils/single_tx_sender.py index 23a9ebf4..3f9da93c 100644 --- a/tests/utils/single_tx_sender.py +++ b/tests/utils/single_tx_sender.py @@ -273,7 +273,7 @@ def send(self) -> None: logger.debug(f"Created {len(txs)} txs") # test that config is unchanged - assert config_copy != config + assert config_copy is not config AssertUtils.assert_equals(config_copy, config) # test common tx set among txs diff --git a/tests/utils/sync_with_pool_submit_tester.py b/tests/utils/sync_with_pool_submit_tester.py index 34bc7024..d2f0cf95 100644 --- a/tests/utils/sync_with_pool_submit_tester.py +++ b/tests/utils/sync_with_pool_submit_tester.py @@ -163,7 +163,7 @@ def test(self) -> None: assert tx_double_spend.full_hex is not None # test that config is unchanged - assert config_no_relay_copy != config_no_relay + assert config_no_relay_copy is not config_no_relay AssertUtils.assert_equals(config_no_relay_copy, config_no_relay) # submit tx directly to the pool but do not relay diff --git a/tests/utils/to_multiple_tx_sender.py b/tests/utils/to_multiple_tx_sender.py index 03424e0d..6ace6f68 100644 --- a/tests/utils/to_multiple_tx_sender.py +++ b/tests/utils/to_multiple_tx_sender.py @@ -220,7 +220,7 @@ def send(self) -> None: assert len(txs) == 1 # test that config is unchanged - assert config_copy != config + assert config_copy is not config AssertUtils.assert_equals(config_copy, config) # test that wallet balance decreased diff --git a/tests/utils/tx_tester.py b/tests/utils/tx_tester.py index 9e3bbac0..dd90c873 100644 --- a/tests/utils/tx_tester.py +++ b/tests/utils/tx_tester.py @@ -152,12 +152,12 @@ def _test_inputs_and_outputs(self) -> None: assert len(self.tx.inputs) > 0 for tx_input in self.tx.inputs: - assert self.tx == tx_input.tx + assert self.tx is tx_input.tx OutputUtils.test_input(tx_input, self.ctx) assert len(self.tx.outputs) > 0 for output in self.tx.outputs: - assert self.tx == output.tx + assert self.tx is output.tx OutputUtils.test_output(output, self.ctx) def _test_full_tx(self) -> None: diff --git a/tests/utils/tx_utils.py b/tests/utils/tx_utils.py index 2a8c9ccd..d29e720c 100644 --- a/tests/utils/tx_utils.py +++ b/tests/utils/tx_utils.py @@ -33,7 +33,7 @@ def test_tx_copy(cls, tx: Optional[MoneroTx], context: Optional[TestContext]) -> block_copy.txs = [copy] AssertUtils.assert_equals(tx, copy) - assert copy != tx + assert copy is not tx # test different input references if len(copy.inputs) == 0: diff --git a/tests/utils/tx_wallet_tester.py b/tests/utils/tx_wallet_tester.py index d25f81a6..f296d7fa 100644 --- a/tests/utils/tx_wallet_tester.py +++ b/tests/utils/tx_wallet_tester.py @@ -68,7 +68,7 @@ def _test_send(self) -> None: assert self.tx.weight > 0 assert len(self.tx.inputs) > 0 for tx_input in self.tx.inputs: - assert tx_input.tx == self.tx + assert tx_input.tx is self.tx else: assert self.tx.weight is None assert len(self.tx.inputs) == 0 @@ -224,7 +224,7 @@ def _test_send_response(self) -> None: assert self.tx.tx_set is not None found: bool = False for a_tx in self.tx.tx_set.txs: - if a_tx == self.tx: + if a_tx is self.tx: found = True break diff --git a/tests/utils/tx_wallet_utils.py b/tests/utils/tx_wallet_utils.py index 701b05ce..13fdfc24 100644 --- a/tests/utils/tx_wallet_utils.py +++ b/tests/utils/tx_wallet_utils.py @@ -126,7 +126,7 @@ def test_common_tx_sets(cls, txs: list[MoneroTxWallet], has_signed: bool, has_un if i == 0: tx_set = tx.tx_set else: - assert tx.tx_set == tx_set + assert tx.tx_set is tx_set # test expected set assert tx_set is not None diff --git a/tests/utils/txs_structure_tester.py b/tests/utils/txs_structure_tester.py index 568c40c6..c9d455bb 100644 --- a/tests/utils/txs_structure_tester.py +++ b/tests/utils/txs_structure_tester.py @@ -17,8 +17,8 @@ class TxsStructureTester: regtest: bool """Indicates if running test on regtest network.""" - seen_blocks: set[MoneroBlock] - """Unique set of seen blocks in txs.""" + seen_blocks: set[int] + """Ids of the blocks seen in the txs: the blocks are not hashable, and the txs of a block share it.""" blocks: list[MoneroBlock] """All blocks seen by txs.""" @@ -66,13 +66,14 @@ def __init__(self, txs: list[MoneroTxWallet], query: Optional[MoneroTxQuery], re # initialize for tx in txs: - if tx.block is None: + block: MoneroBlock | None = tx.block + if block is None: self.unconfirmed_txs.append(tx) else: - assert BlockUtils.is_tx_in_block(tx.hash, tx.block) - if tx.block not in self.seen_blocks: - self.seen_blocks.add(tx.block) - self.blocks.append(tx.block) + assert BlockUtils.is_tx_in_block(tx.hash, block) + if id(block) not in self.seen_blocks: + self.seen_blocks.add(id(block)) + self.blocks.append(block) def _test_block_txs_order(self, tx: MoneroTx, block: MoneroBlock, index: int) -> None: """Test that `tx` is at the expected position within `block`'s tx order. @@ -81,13 +82,13 @@ def _test_block_txs_order(self, tx: MoneroTx, block: MoneroBlock, index: int) -> :param MoneroBlock block: block `tx` belongs to. :param int index: expected position of `tx` in `self.txs`. """ - assert tx.block == block + assert tx.block is block if self.num_tx_hashes == 0: other: MoneroTxWallet = self.txs[index] if not self.regtest: assert other.hash == tx.hash, "Txs in block are not in order" # verify tx order is self-consistent with blocks unless txs manually re-ordered by querying by hash - assert other == tx + assert other is tx else: # TODO regtest wallet2 has inconsinstent txs order between calls assert other in block.txs, "Tx not found in block" diff --git a/tests/wallet/model/test_output_query.py b/tests/wallet/model/test_output_query.py index 1353ea82..78b16aaa 100644 --- a/tests/wallet/model/test_output_query.py +++ b/tests/wallet/model/test_output_query.py @@ -30,15 +30,15 @@ def test_output_query(self) -> None: output_query.set_tx_query(tx_query, True) assert output_query.tx_query is not None - assert output_query.tx_query == tx_query + assert output_query.tx_query is tx_query assert tx_query.input_query is None assert tx_query.output_query is not None - assert tx_query.output_query == output_query + assert tx_query.output_query is output_query # reassign output query to tx query output_query.tx_query.output_query = output_query assert output_query.tx_query is not None - assert output_query == output_query.tx_query.output_query + assert output_query is output_query.tx_query.output_query # remove tx query from output query output_query.set_tx_query(None, True) @@ -55,15 +55,15 @@ def test_input_query(self) -> None: input_query.set_tx_query(tx_query, False) assert input_query.tx_query is not None - assert input_query.tx_query == tx_query + assert input_query.tx_query is tx_query assert tx_query.output_query is None assert tx_query.input_query is not None - assert tx_query.input_query == input_query + assert tx_query.input_query is input_query # reassign input query to tx query input_query.tx_query.input_query = input_query assert input_query.tx_query is not None - assert input_query == input_query.tx_query.input_query + assert input_query is input_query.tx_query.input_query # remove tx query from input query input_query.set_tx_query(None, False) @@ -78,7 +78,7 @@ def test_output_query_reassign_same_tx_query(self, output_query: bool) -> None: tx_query: MoneroTxQuery = MoneroTxQuery() query.set_tx_query(tx_query, output_query) query.set_tx_query(tx_query, output_query) - assert query.tx_query == tx_query + assert query.tx_query is tx_query assert (tx_query.output_query if output_query else tx_query.input_query) == query def test_output_query_meets_criteria_matches_unconstrained_output(self) -> None: diff --git a/tests/wallet/model/test_transfer_query.py b/tests/wallet/model/test_transfer_query.py index c87e0a71..3e4ea517 100644 --- a/tests/wallet/model/test_transfer_query.py +++ b/tests/wallet/model/test_transfer_query.py @@ -31,12 +31,12 @@ def test_transfer_query(self) -> None: transfer_query.tx_query = tx_query assert tx_query.transfer_query is not None - assert tx_query.transfer_query == transfer_query + assert tx_query.transfer_query is transfer_query # reassign transfer query to tx query transfer_query.tx_query.transfer_query = transfer_query assert transfer_query.tx_query is not None - assert transfer_query == transfer_query.tx_query.transfer_query + assert transfer_query is transfer_query.tx_query.transfer_query # remove tx query from transfer query transfer_query.tx_query = None @@ -71,8 +71,8 @@ def test_transfer_query_reassign_same_tx_query(self) -> None: tx_query: MoneroTxQuery = MoneroTxQuery() transfer_query.tx_query = tx_query transfer_query.tx_query = tx_query - assert transfer_query.tx_query == tx_query - assert tx_query.transfer_query == transfer_query + assert transfer_query.tx_query is tx_query + assert tx_query.transfer_query is transfer_query def test_transfer_query_meets_criteria_matches_unconstrained_transfer(self) -> None: transfer: MoneroIncomingTransfer = MoneroIncomingTransfer() diff --git a/tests/wallet/model/test_tx_query.py b/tests/wallet/model/test_tx_query.py index 6e925782..a4f52a11 100644 --- a/tests/wallet/model/test_tx_query.py +++ b/tests/wallet/model/test_tx_query.py @@ -33,40 +33,40 @@ def test_tx_query(self) -> None: # assign transfer query to tx query tx_query.transfer_query = transfer_query - assert tx_query.transfer_query == transfer_query + assert tx_query.transfer_query is transfer_query assert transfer_query.tx_query is not None - assert transfer_query.tx_query == tx_query + assert transfer_query.tx_query is tx_query # remove transfer query from tx query tx_query.transfer_query = None - assert tx_query.transfer_query != transfer_query + assert tx_query.transfer_query is not transfer_query assert transfer_query.tx_query is None # assign output query to tx query tx_query.output_query = output_query - assert tx_query.output_query == output_query + assert tx_query.output_query is output_query assert output_query.tx_query is not None - assert output_query.tx_query == tx_query + assert output_query.tx_query is tx_query # remove output query from tx query tx_query.output_query = None - assert tx_query.output_query != output_query + assert tx_query.output_query is not output_query assert output_query.tx_query is None # assign input query to tx query tx_query.input_query = input_query - assert tx_query.input_query == input_query + assert tx_query.input_query is input_query assert input_query.tx_query is not None - assert input_query.tx_query == tx_query + assert input_query.tx_query is tx_query # remove output query from tx query tx_query.input_query = None - assert tx_query.input_query != input_query + assert tx_query.input_query is not input_query assert input_query.tx_query is None def test_tx_query_meets_criteria_matches_unconstrained_tx(self) -> None: diff --git a/tests/wallet/test_creation.py b/tests/wallet/test_creation.py index 33218412..c40bf4e2 100644 --- a/tests/wallet/test_creation.py +++ b/tests/wallet/test_creation.py @@ -438,7 +438,7 @@ def test_create_wallet_random_full(self, daemon: MoneroDaemonRpc) -> None: MoneroUtils.validate_address(wallet.get_primary_address(), MoneroNetworkType.TESTNET) assert wallet.get_network_type() == MoneroNetworkType.TESTNET assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + assert wallet.get_daemon_connection() is not daemon.get_rpc_connection() AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) assert wallet.is_connected_to_daemon() assert wallet.get_seed_language() == "Spanish" @@ -487,7 +487,7 @@ def test_create_wallet_from_seed_full(self, daemon: MoneroDaemonRpc) -> None: assert wallet.get_primary_address() == Utils.ADDRESS assert wallet.get_network_type() == Utils.NETWORK_TYPE assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + assert wallet.get_daemon_connection() is not daemon.get_rpc_connection() AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) assert wallet.is_connected_to_daemon() assert wallet.get_seed_language() == "English" @@ -539,7 +539,7 @@ def test_create_wallet_from_seed_full(self, daemon: MoneroDaemonRpc) -> None: assert wallet.get_primary_address() == Utils.ADDRESS assert wallet.get_network_type() == Utils.NETWORK_TYPE assert wallet.get_daemon_connection() is not None - assert wallet.get_daemon_connection() != daemon.get_rpc_connection() + assert wallet.get_daemon_connection() is not daemon.get_rpc_connection() AssertUtils.assert_equals(wallet.get_daemon_connection(), daemon.get_rpc_connection()) assert wallet.is_connected_to_daemon() assert wallet.get_seed_language() == "English" diff --git a/tests/wallet/test_outputs.py b/tests/wallet/test_outputs.py index 7ce2be3f..444e291f 100644 --- a/tests/wallet/test_outputs.py +++ b/tests/wallet/test_outputs.py @@ -239,7 +239,7 @@ def test_validate_inputs_get_outputs(self, wallet: MoneroWallet) -> None: assert isinstance(tx, MoneroTxWallet) for output in outputs: - assert output.tx == tx + assert output.tx is tx # Can export outputs in hex format @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False or TestUtils.LITE_MODE, reason="TEST_NON_RELAYS disabled") diff --git a/tests/wallet/test_transfers.py b/tests/wallet/test_transfers.py index a04baeb2..4877fe1e 100644 --- a/tests/wallet/test_transfers.py +++ b/tests/wallet/test_transfers.py @@ -334,7 +334,7 @@ def test_validate_inputs_get_transfers(self, wallet: MoneroWallet) -> None: tx: MoneroTxWallet | None = transfers[0].tx assert tx is not None for transfer in transfers: - assert transfer.tx == tx + assert transfer.tx is tx # test unused subaddress indices transfer_query = MoneroTransferQuery() diff --git a/tests/wallet/test_txs.py b/tests/wallet/test_txs.py index ff2a3fb6..cfe5e370 100644 --- a/tests/wallet/test_txs.py +++ b/tests/wallet/test_txs.py @@ -88,7 +88,7 @@ def test_get_txs_wallet(self, wallet: MoneroWallet) -> None: block_per_height[i] = it.block else: AssertUtils.assert_equals(block, it.block) - assert block == it.block, "Block references for same height must be same" + assert block is it.block, "Block references for same height must be same" # Can get transactions by hash @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") From 66c0d7a5c06e720c37828c46bcc0d7c5a547ab17 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Tue, 24 Nov 2026 13:05:20 +0100 Subject: [PATCH 3/4] docs: add a page about the equality and the identity of the models --- docs/mkdocs/docs/en/api/architecture.md | 2 + docs/mkdocs/docs/en/api/equality.md | 123 ++++++++++++++++++ .../mkdocs/docs/en/api/serializable_struct.md | 16 +-- docs/mkdocs/docs/en/tests/writing/index.md | 3 + docs/mkdocs/mkdocs.yml | 1 + 5 files changed, 132 insertions(+), 13 deletions(-) create mode 100644 docs/mkdocs/docs/en/api/equality.md diff --git a/docs/mkdocs/docs/en/api/architecture.md b/docs/mkdocs/docs/en/api/architecture.md index 19ea24d1..b5fa93f2 100644 --- a/docs/mkdocs/docs/en/api/architecture.md +++ b/docs/mkdocs/docs/en/api/architecture.md @@ -54,6 +54,8 @@ The model is the one of monero-cpp and monero-java, with the names of Python. It [`MoneroTransfer`][monero.MoneroTransfer], [`MoneroOutputQuery`][monero.MoneroOutputQuery] extends [`MoneroOutputWallet`][monero.MoneroOutputWallet]. - The classes of the model extend [`SerializableStruct`][monero.SerializableStruct], whose `serialize()` turns them into JSON. +- Two objects of the model are equal if they hold the same values, and the same object only with `is` + ([Equality and Identity](equality.md)). ## Listeners diff --git a/docs/mkdocs/docs/en/api/equality.md b/docs/mkdocs/docs/en/api/equality.md new file mode 100644 index 00000000..28286abf --- /dev/null +++ b/docs/mkdocs/docs/en/api/equality.md @@ -0,0 +1,123 @@ +--- +title: Equality and Identity +--- +# Equality and Identity + +The objects of the [data model](architecture.md#the-data-model) are compared like in monero-java, with the operators of Python: +`==` tells whether two objects hold the same values, `is` whether they are the same object. A test ported from monero-java has to +pick the right one, since Java writes them the other way around. + +## Equality + +Two objects are equal if they have the same class and the same JSON, the one of [`serialize`][monero.SerializableStruct.serialize]: + +```python +tx1: MoneroTxWallet = wallet.get_tx(tx_hash) +tx2: MoneroTxWallet = wallet.get_tx(tx_hash) +assert tx1 == tx2 # the same values +assert tx1 is not tx2 # two objects +``` + +- **The children are compared, the back references are not.** A block compares its txs and a tx its outputs, but a tx does not + compare its block and an output its tx, as with `equals` in monero-java. Two txs with the same values in two different blocks are + equal. +- **The class has to be the same.** A [`MoneroTx`][monero.MoneroTx] does not equal a [`MoneroTxWallet`][monero.MoneroTxWallet], and a + [`MoneroTxQuery`][monero.MoneroTxQuery] does not equal the tx that it selects, even with the same JSON. +- **What is not serialized is not compared**, and what is serialized is: the `server` of a + [`MoneroWalletConfig`][monero.MoneroWalletConfig] is compared by its JSON, with its priority and its state, unlike two + [`MoneroRpcConnection`][monero.MoneroRpcConnection] on their own. + +[`MoneroRpcConnection`][monero.MoneroRpcConnection] is compared as in monero-java, by uri, username, password, proxy uri, zmq uri and +ssl verify. Its JSON also has the priority, the timeout and the state of the connection (`responseTime`, `isOnline`), which are not +compared: a connection equals the one that a wallet returns for it. + +## Hashing + +The objects can be changed, so they are not hashable: they can not be keys of a `dict` or go in a `set`, and `hash(tx)` raises +`TypeError`. Key them by what identifies them: + +```python +txs_by_hash: dict[str, MoneroTxWallet] = {tx.hash: tx for tx in txs} +``` + +or, to tell the objects apart rather than their values, by their `id()` while a reference keeps them alive (see below). + +## Identity + +An object of the model is a Python object around a C++ object. The bindings give the same Python object for the same C++ object as long +as one is alive, so the back references are the objects that they point to: + +```python +for output in tx.outputs: + assert output.tx is tx +assert tx.block is None or tx in tx.block.txs +``` + +When no Python object is alive, the next access makes a new one: the `id()` of a temporary object can change from an access to the +next. Keep a reference before taking it: + +```python +block: MoneroBlock | None = tx.block +if block is not None and id(block) not in seen_blocks: + seen_blocks.add(id(block)) + blocks.append(block) # keeps it alive, so its id is not used again +``` + +## Lists of the model + +The fields that hold a list of objects of the model, as `block.txs`, `tx.inputs`, `tx.outputs`, `tx.incoming_transfers` or +`tx_set.txs`, are the vectors of C++ (`VectorMoneroTx`, `VectorMoneroOutput`...), and what the vector does compares its objects +**by identity**: `in`, `==`, `index`, `remove` and `count`. A `list` compares them by value: + +| | a vector, `tx.outputs` | a `list`, `list(tx.outputs)` | +| --- | --- | --- | +| `output in ...` | the same object is there | an equal object is there | +| `tx1.outputs == tx2.outputs` | the same objects, in the same order | equal objects, in the same order | + +```python +copy: MoneroOutputWallet = output.copy() +assert copy == output +assert copy not in output.tx.outputs # not the same object +assert copy in list(output.tx.outputs) # an equal one +``` + +## Representation + +The `repr` of an object is its class with its JSON, `MoneroTxWallet({"hash":"...",...})`, which is what pytest shows when an `==` +fails. [`MoneroRpcConnection`][monero.MoneroRpcConnection] shows `***` for its password, and +[`MoneroWalletConfig`][monero.MoneroWalletConfig] for its password, seed, seed offset, private keys and the password of its server, so +that they do not end up in a log. `serialize()` keeps them. + +## Differences from monero-java + +| monero-java | monero-python | | +| --- | --- | --- | +| `a == b`, `a != b` | `a is b`, `a is not b` | the same object | +| `a.equals(b)`, `assertEquals(a, b)` | `a == b` | the same values | +| `equals` of each class, field by field | `serialize()` of the two objects | the fields that are not serialized are not compared | +| `hashCode()`, `Set`, `Map` | not hashable | key by the hash, or by `id()` | +| `list.contains(x)`, with `equals` | `x in vector` by identity, `x in list(vector)` by value | the vectors of the model | +| `toString()`, an indented text | `repr()`, the JSON on one line | with the secrets hidden | + +## Porting a test from monero-java + +monero-java checks a copy with a pair of asserts, one for each meaning: + +```java +MoneroTxConfig configCopy = config.copy(); +// ... +assertTrue(configCopy != config); // another object +assertEquals(configCopy, config); // with the same values +``` + +In Python, the first is `is not`, not `!=`: `configCopy != config` would fail, since the copy has the same values. + +```python +config_copy: MoneroTxConfig = config.copy() +# ... +assert config_copy is not config +assert config_copy == config +``` + +The same goes for the back references, which monero-java checks with `==`: `assertTrue(tx == output.getTx())` is +`assert output.tx is tx`. A `==` there would also pass with a copy of the tx, which is not what the test checks. diff --git a/docs/mkdocs/docs/en/api/serializable_struct.md b/docs/mkdocs/docs/en/api/serializable_struct.md index 5e793348..2500eee4 100644 --- a/docs/mkdocs/docs/en/api/serializable_struct.md +++ b/docs/mkdocs/docs/en/api/serializable_struct.md @@ -18,18 +18,8 @@ def carry(result: MoneroKeyImageExportResult) -> MoneroKeyImageExportResult: It is how an object goes from a process or a machine to another ([Signing Offline with a Cold Wallet](../examples/scenarios/cold_signing.md)). -Two objects of the same class are equal if they serialize the same, so `==` compares what they hold and not whether they are the -same object. Like with monero-java, the back references are left out: a tx does not compare its block, an output its tx. The -objects can be changed, so they are not hashable: they can not be keys of a `dict` or go in a `set`. - -```python -assert wallet.get_tx(tx_hash) == wallet.get_tx(tx_hash) # two objects, equal -print(repr(tx)) # MoneroTxWallet({"hash":"...",...}) -``` - -The `repr` of an object is its class with its JSON. [`MoneroRpcConnection`][monero.MoneroRpcConnection] and -[`MoneroWalletConfig`][monero.MoneroWalletConfig] hide their password, seed and private keys there, while `serialize()` keeps -them. A connection equals another with the same uri, credentials, proxy, zmq uri and ssl verify, whatever its priority, its timeout -or its state. +Two objects of the same class are equal if they serialize the same, without their back references, and they are not hashable. Their +`repr` is their class with their JSON. [Equality and Identity](equality.md) says how `==` and `is` work on the model, and how they +differ from monero-java. ::: monero.SerializableStruct diff --git a/docs/mkdocs/docs/en/tests/writing/index.md b/docs/mkdocs/docs/en/tests/writing/index.md index e8fcc703..11142b33 100644 --- a/docs/mkdocs/docs/en/tests/writing/index.md +++ b/docs/mkdocs/docs/en/tests/writing/index.md @@ -11,6 +11,9 @@ How the tests are made, and what a new one needs. | [A New Wallet Method](new_wallet_method.md) | the call and the row of the support matrix that a new method of `MoneroWallet` needs | | [Helpers](helpers.md) | the helpers of `tests/utils` | +A test ported from monero-java turns its `==` between objects into `is`, and its `assertEquals` into `==`: see +[Porting a test from monero-java](../../api/equality.md#porting-a-test-from-monero-java). + ## Where a test goes | What it tests | Where | diff --git a/docs/mkdocs/mkdocs.yml b/docs/mkdocs/mkdocs.yml index dc26a8ca..0a18f416 100644 --- a/docs/mkdocs/mkdocs.yml +++ b/docs/mkdocs/mkdocs.yml @@ -60,6 +60,7 @@ nav: - Logging: 'api/utils/logging.md' - Binary RPC: 'api/utils/binary.md' - Test Helpers: 'api/utils/helpers.md' + - Equality and Identity: 'api/equality.md' - Glossary: 'api/glossary.md' - Security: 'api/security.md' - Troubleshooting: 'api/troubleshooting.md' From db94fe2631442a2f313c811f35b578d995c2df09 Mon Sep 17 00:00:00 2001 From: everoddandeven Date: Tue, 24 Nov 2026 16:30:49 +0100 Subject: [PATCH 4/4] bindings: iterate the json members without GetObject, which windows renames --- src/cpp/common/py_monero_common.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/cpp/common/py_monero_common.cpp b/src/cpp/common/py_monero_common.cpp index 5f523684..9d5a1772 100644 --- a/src/cpp/common/py_monero_common.cpp +++ b/src/cpp/common/py_monero_common.cpp @@ -135,15 +135,16 @@ py::object PyGenUtils::parse_rpc_response(const std::string& body, const std::st // replaces the non-empty strings of the keys with ***, at any depth, like the password of the server of a wallet config static void redact(rapidjson::Value& val, const std::vector& keys) { + // iterators rather than GetObject(), which windows.h renames to GetObjectA if (val.IsArray()) { - for (auto& item : val.GetArray()) redact(item, keys); + for (auto it = val.Begin(); it != val.End(); ++it) redact(*it, keys); return; } if (!val.IsObject()) return; - for (auto& member : val.GetObject()) { - bool secret = std::find(keys.begin(), keys.end(), member.name.GetString()) != keys.end(); - if (secret && member.value.IsString() && member.value.GetStringLength() > 0) member.value.SetString("***"); - else redact(member.value, keys); + for (auto it = val.MemberBegin(); it != val.MemberEnd(); ++it) { + bool secret = std::find(keys.begin(), keys.end(), it->name.GetString()) != keys.end(); + if (secret && it->value.IsString() && it->value.GetStringLength() > 0) it->value.SetString("***"); + else redact(it->value, keys); } }