Skip to content

Commit 8128c80

Browse files
authored
MockSubtensor work offline (#2487)
* Updates `ensure_connected` for the change to websockets. * Only need to catch ConnectionClosed, as ConnectionClosedError subclasses ConnectionClosed. * Regenerates the websocket connection if it is closed. * Add property to FakeWebsocket * Ruff * Makes tests that use MockSubtensor run offline. * Changed scope of patch.
1 parent aa9e71b commit 8128c80

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

bittensor/utils/mock/subtensor_mock.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@
2020
from hashlib import sha256
2121
from types import SimpleNamespace
2222
from typing import Any, Optional, Union, TypedDict
23-
from unittest.mock import MagicMock
23+
from unittest.mock import MagicMock, patch
2424

2525
from bittensor_wallet import Wallet
26+
from substrateinterface.base import SubstrateInterface
27+
from websockets.sync.client import ClientConnection
2628

2729
from bittensor.core.chain_data import (
2830
NeuronInfo,
@@ -33,6 +35,7 @@
3335
from bittensor.core.types import AxonServeCallParams, PrometheusServeCallParams
3436
from bittensor.core.errors import ChainQueryError
3537
from bittensor.core.subtensor import Subtensor
38+
import bittensor.core.subtensor as subtensor_module
3639
from bittensor.utils import RAOPERTAO, u16_normalized_float
3740
from bittensor.utils.balance import Balance
3841

@@ -248,14 +251,22 @@ def setup(self) -> None:
248251

249252
self.network = "mock"
250253
self.chain_endpoint = "ws://mock_endpoint.bt"
251-
self.substrate = MagicMock()
254+
self.substrate = MagicMock(autospec=SubstrateInterface)
252255

253256
def __init__(self, *args, **kwargs) -> None:
254-
super().__init__()
255-
self.__dict__ = __GLOBAL_MOCK_STATE__
256-
257-
if not hasattr(self, "chain_state") or getattr(self, "chain_state") is None:
258-
self.setup()
257+
mock_substrate_interface = MagicMock(autospec=SubstrateInterface)
258+
mock_websocket = MagicMock(autospec=ClientConnection)
259+
mock_websocket.close_code = None
260+
with patch.object(
261+
subtensor_module,
262+
"SubstrateInterface",
263+
return_value=mock_substrate_interface,
264+
):
265+
super().__init__(websocket=mock_websocket)
266+
self.__dict__ = __GLOBAL_MOCK_STATE__
267+
268+
if not hasattr(self, "chain_state") or getattr(self, "chain_state") is None:
269+
self.setup()
259270

260271
def get_block_hash(self, block_id: int) -> str:
261272
return "0x" + sha256(str(block_id).encode()).hexdigest()[:64]

0 commit comments

Comments
 (0)