Coverage for tests/wallet/base_test_monero_wallet.py: 93%
112 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
1from __future__ import annotations
3import logging
4from abc import abstractmethod
5from configparser import ConfigParser
6from typing import Optional
8import pytest
9from monero import MoneroDaemonRpc, MoneroMiningStatus, MoneroWallet, MoneroWalletConfig
10from typing_extensions import override
12from utils import (
13 BaseTestClass,
14 IntegrationTestUtils,
15 MiningUtils,
16 MultisigSampleCodeTester,
17 TestUtils,
18 WalletType,
19)
21logger: logging.Logger = logging.getLogger("TestMoneroWalletCommon")
24class BaseTestMoneroWallet(BaseTestClass):
25 """Common wallet tests that every Monero wallet implementation should support."""
27 _test_wallet: Optional[MoneroWallet] = None
28 """Private reference to test wallet instance."""
30 @classmethod
31 def get_wallet_type(cls) -> WalletType:
32 """Wallet type to test."""
33 return WalletType.UNDEFINED
35 @classmethod
36 def supports_save(cls) -> bool:
37 wallet_type: WalletType = cls.get_wallet_type()
38 return wallet_type == WalletType.FULL or wallet_type == WalletType.RPC
40 class Config:
41 """Wallet test configuration."""
43 seed: str = ""
44 """Test wallet seed."""
46 @classmethod
47 def parse(cls, parser: ConfigParser) -> BaseTestMoneroWallet.Config:
48 """Parse wallet test configuration.
50 :param ConfigParser parser: configuration parser.
51 :returns BaseTestMoneroWallet.Config: wallet test configuration.
52 """
53 section: str = "test_create_wallet_from_seed"
54 if not parser.has_section(section):
55 # raise exception if section not found
56 raise Exception(f"Cannot find section '{section}' in test_monero_wallet_common.ini")
57 config: BaseTestMoneroWallet.Config = cls()
58 # parse configuration
59 config.seed = parser.get(section, "seed")
60 return config
62 @classmethod
63 def _get_test_daemon(cls) -> MoneroDaemonRpc:
64 """Get the daemon to test.
66 :returns MoneroDaemonRpc: the daemon to test.
67 """
68 return TestUtils.get_daemon_rpc()
70 @classmethod
71 def get_test_wallet(cls) -> MoneroWallet:
72 """Get the main wallet to test.
74 :returns MoneroWallet: the wallet to test.
75 """
76 if cls._test_wallet is None:
77 wallet_type: WalletType = cls.get_wallet_type()
78 if wallet_type == WalletType.FULL:
79 cls._test_wallet = TestUtils.get_wallet_full()
80 elif wallet_type == WalletType.RPC:
81 cls._test_wallet = TestUtils.get_wallet_rpc()
82 elif wallet_type == WalletType.KEYS:
83 cls._test_wallet = TestUtils.get_wallet_keys()
84 else:
85 raise Exception("Cannot get test wallet: No wallet type setup for tests")
87 return cls._test_wallet
89 @abstractmethod
90 def _open_wallet(self, config: Optional[MoneroWalletConfig]) -> MoneroWallet:
91 """Open a test wallet with default configuration for each wallet type.
93 :param MoneroWalletConfig | None config: configures the wallet to open.
94 :returns MoneroWallet: is the opened wallet.
95 """
96 ...
98 @abstractmethod
99 def _create_wallet(self, config: MoneroWalletConfig) -> MoneroWallet:
100 """Create a test wallet with default configuration for each wallet type.
102 :param MoneroWalletConfig config: configures the wallet to create.
103 :returns MoneroWallet: is the created wallet.
104 """
105 ...
107 @abstractmethod
108 def _close_wallet(self, wallet: MoneroWallet, save: bool = False) -> None:
109 """Close a test wallet with customization for each wallet type.
111 :param MoneroWallet wallet: the wallet to close.
112 :param bool save: whether or not to save the wallet.
113 """
114 ...
116 @abstractmethod
117 def _get_seed_languages(self) -> list[str]:
118 """Get the wallet's supported languages for the seed. This is an
119 instance method for wallet rpc and a static utility for other wallets.
121 :returns list[str]: the wallet's supported languages.
122 """
123 ...
125 def _open_wallet_from_path(self, path: str, password: str | None) -> MoneroWallet:
126 """Open a wallet from path.
128 :param str path: wallet path to open.
129 :param str | None password: wallet password.
130 :returns MoneroWallet: opened wallet.
131 """
132 config: MoneroWalletConfig = MoneroWalletConfig()
133 config.path = path
134 config.password = password
136 return self._open_wallet(config)
138 def get_daemon_rpc_uri(self) -> str:
139 return TestUtils.DAEMON_RPC_URI
141 @classmethod
142 def is_random_wallet_config(cls, config: Optional[MoneroWalletConfig]) -> bool:
143 """Check if config is valid to create a random wallet.
145 :param MoneroWalletConfig | None config: config to check.
146 :returns bool: `True` if config is valid to create a random wallet, `False` otherwise.
147 """
148 assert config is not None
149 return config.seed is None and config.primary_address is None
151 # Test wallet configuration
152 @pytest.fixture(scope="class")
153 @classmethod
154 def test_config(cls) -> BaseTestMoneroWallet.Config:
155 """Test configuration."""
156 parser: ConfigParser = ConfigParser()
157 parser.read('tests/config/test_monero_wallet_common.ini')
158 return BaseTestMoneroWallet.Config.parse(parser)
160 # Test daemon fixture
161 @pytest.fixture(scope="class")
162 @classmethod
163 def daemon(cls) -> MoneroDaemonRpc:
164 """Test rpc daemon instance."""
165 return TestUtils.get_daemon_rpc()
167 # Test wallet fixture
168 @pytest.fixture(scope="class")
169 @classmethod
170 def wallet(cls) -> MoneroWallet:
171 """Test wallet instance."""
172 pytest.skip("No wallet test instance setup")
174 # Before all tests
175 @override
176 def before_all(self) -> None:
177 super().before_all()
178 IntegrationTestUtils.setup(self.get_wallet_type())
180 # After all tests
181 @override
182 def after_all(self) -> None:
183 super().after_all()
184 daemon: MoneroDaemonRpc = self._get_test_daemon()
185 MiningUtils.try_stop_mining(daemon)
186 # the wallet is not closed here: the classes of the topics share it, and TestUtils.close_wallets() closes it
187 # when the session ends (see conftest.py)
189 # Before each test
190 @override
191 def before_each(self, request: pytest.FixtureRequest) -> None:
192 super().before_each(request)
193 daemon: MoneroDaemonRpc = self._get_test_daemon()
194 wallet: MoneroWallet = self.get_test_wallet()
195 status: MoneroMiningStatus = daemon.get_mining_status()
197 if status.is_active is True:
198 wallet.stop_mining()
200 # After each test
201 @override
202 def after_each(self, request: pytest.FixtureRequest) -> None:
203 super().after_each(request)
204 daemon: MoneroDaemonRpc = self._get_test_daemon()
205 status: MoneroMiningStatus = daemon.get_mining_status()
207 if status.is_active is True:
208 logger.warning(f"Mining is active after test {request.node.name}")
210 def _test_multisig_sample(self, m: int, n: int) -> None:
211 """
212 Test multisig sample code.
214 :param int m: multisig threshold.
215 :param int n: number of participants.
216 """
217 # create participant wallets
218 wallets: list[MoneroWallet] = []
220 for i in range(n):
221 wallets.append(self._create_wallet(MoneroWalletConfig()))
222 logger.debug(f"Created multisig wallet participant {i + 1}")
224 tester: MultisigSampleCodeTester = MultisigSampleCodeTester(m, wallets)
225 tester.test()
227 if self.get_wallet_type() == WalletType.RPC:
228 TestUtils.free_wallet_rpc_resources()