-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathtest_async_subtensor.py
2739 lines (2249 loc) · 83.5 KB
/
test_async_subtensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import unittest.mock as mock
import pytest
from bittensor_wallet import Wallet
from bittensor.core import async_subtensor
from bittensor.core.async_subtensor import AsyncSubtensor
from bittensor.core.chain_data import proposal_vote_data
from bittensor.utils.balance import Balance
@pytest.fixture(autouse=True)
def subtensor(mocker):
fake_async_substrate = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface
)
mocker.patch.object(
async_subtensor, "AsyncSubstrateInterface", return_value=fake_async_substrate
)
return async_subtensor.AsyncSubtensor()
def test_decode_ss58_tuples_in_proposal_vote_data(mocker):
"""Tests that ProposalVoteData instance instantiation works properly,"""
# Preps
mocked_decode_account_id = mocker.patch.object(
proposal_vote_data, "decode_account_id"
)
fake_proposal_dict = {
"index": "0",
"threshold": 1,
"ayes": ("0 line", "1 line"),
"nays": ("2 line", "3 line"),
"end": 123,
}
# Call
async_subtensor.ProposalVoteData(fake_proposal_dict)
# Asserts
assert mocked_decode_account_id.call_count == len(fake_proposal_dict["ayes"]) + len(
fake_proposal_dict["nays"]
)
assert mocked_decode_account_id.mock_calls == [
mocker.call("0"),
mocker.call("1"),
mocker.call("2"),
mocker.call("3"),
]
def test_decode_hex_identity_dict_with_single_byte_utf8():
"""Tests _decode_hex_identity_dict when value is a single utf-8 decodable byte."""
info_dict = {"name": (b"Neuron",)}
result = async_subtensor._decode_hex_identity_dict(info_dict)
assert result["name"] == "Neuron"
def test_decode_hex_identity_dict_with_non_utf8_data():
"""Tests _decode_hex_identity_dict when value cannot be decoded as utf-8."""
info_dict = {"data": (b"\xff\xfe",)}
result = async_subtensor._decode_hex_identity_dict(info_dict)
assert result["data"] == (b"\xff\xfe",)
def test_decode_hex_identity_dict_with_non_tuple_value():
"""Tests _decode_hex_identity_dict when value is not a tuple."""
info_dict = {"info": "regular_string"}
result = async_subtensor._decode_hex_identity_dict(info_dict)
assert result["info"] == "regular_string"
def test_decode_hex_identity_dict_with_nested_dict():
"""Tests _decode_hex_identity_dict with a nested dictionary."""
info_dict = {"identity": {"rank": (65, 66, 67)}}
result = async_subtensor._decode_hex_identity_dict(info_dict)
assert result["identity"] == "41 4243"
@pytest.mark.asyncio
async def test_init_if_unknown_network_is_valid(mocker):
"""Tests __init__ if passed network unknown and is valid."""
# Preps
fake_valid_endpoint = "wss://blabla.net"
mocker.patch.object(async_subtensor, "AsyncSubstrateInterface")
# Call
subtensor = AsyncSubtensor(fake_valid_endpoint)
# Asserts
assert subtensor.chain_endpoint == fake_valid_endpoint
assert subtensor.network == "unknown"
@pytest.mark.asyncio
async def test_init_if_unknown_network_is_known_endpoint(mocker):
"""Tests __init__ if passed network unknown and is valid."""
# Preps
fake_valid_endpoint = "ws://127.0.0.1:9944"
mocker.patch.object(async_subtensor, "AsyncSubstrateInterface")
# Call
subtensor = AsyncSubtensor(fake_valid_endpoint)
# Asserts
assert subtensor.chain_endpoint == fake_valid_endpoint
assert subtensor.network == "local"
@pytest.mark.asyncio
async def test_init_if_unknown_network_is_not_valid(mocker):
"""Tests __init__ if passed network unknown and isn't valid."""
# Preps
mocker.patch.object(async_subtensor, "AsyncSubstrateInterface")
# Call
subtensor = AsyncSubtensor("blabla-net")
# Asserts
assert subtensor.chain_endpoint == "ws://blabla-net"
assert subtensor.network == "unknown"
def test__str__return(subtensor):
"""Simply tests the result if printing subtensor instance."""
# Asserts
assert str(subtensor) == "Network: test, Chain: wss://test.finney.opentensor.ai:443"
@pytest.mark.asyncio
async def test_async_subtensor_magic_methods(mocker):
"""Tests async magic methods of AsyncSubtensor class."""
# Preps
fake_async_substrate = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface
)
mocker.patch.object(
async_subtensor, "AsyncSubstrateInterface", return_value=fake_async_substrate
)
# Call
subtensor = async_subtensor.AsyncSubtensor(network="local")
async with subtensor:
pass
# Asserts
fake_async_substrate.__aenter__.assert_called_once()
fake_async_substrate.__aexit__.assert_called_once()
fake_async_substrate.close.assert_awaited_once()
@pytest.mark.parametrize(
"error",
[ConnectionRefusedError, async_subtensor.ssl.SSLError, TimeoutError],
)
@pytest.mark.asyncio
async def test_async_subtensor_aenter_connection_refused_error(
subtensor, mocker, error
):
"""Tests __aenter__ method handling all errors."""
# Preps
fake_async_substrate = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface,
__aenter__=mocker.AsyncMock(side_effect=error),
)
mocker.patch.object(
async_subtensor, "AsyncSubstrateInterface", return_value=fake_async_substrate
)
# Call
subtensor = async_subtensor.AsyncSubtensor(network="local")
with pytest.raises(ConnectionError):
async with subtensor:
pass
# Asserts
fake_async_substrate.__aenter__.assert_called_once()
@pytest.mark.asyncio
async def test_encode_params(subtensor, mocker):
"""Tests encode_params happy path."""
# Preps
subtensor.substrate.create_scale_object = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.create_scale_object
)
subtensor.substrate.create_scale_object.return_value.encode = mocker.Mock(
return_value=b""
)
call_definition = {
"params": [
{"name": "coldkey", "type": "Vec<u8>"},
{"name": "uid", "type": "u16"},
]
}
params = ["coldkey", "uid"]
# Call
decoded_params = await subtensor.encode_params(
call_definition=call_definition, params=params
)
# Asserts
subtensor.substrate.create_scale_object.call_args(
mocker.call("coldkey"),
mocker.call("Vec<u8>"),
mocker.call("uid"),
mocker.call("u16"),
)
assert decoded_params == "0x"
@pytest.mark.asyncio
async def test_encode_params_raises_error(subtensor, mocker):
"""Tests encode_params with raised error."""
# Preps
subtensor.substrate.create_scale_object = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.create_scale_object
)
subtensor.substrate.create_scale_object.return_value.encode = mocker.Mock(
return_value=b""
)
call_definition = {
"params": [
{"name": "coldkey", "type": "Vec<u8>"},
]
}
params = {"undefined param": "some value"}
# Call and assert
with pytest.raises(ValueError):
await subtensor.encode_params(call_definition=call_definition, params=params)
subtensor.substrate.create_scale_object.return_value.encode.assert_not_called()
@pytest.mark.asyncio
async def test_get_current_block(subtensor):
"""Tests get_current_block method."""
# Call
result = await subtensor.get_current_block()
# Asserts
subtensor.substrate.get_block_number.assert_called_once()
assert result == subtensor.substrate.get_block_number.return_value
@pytest.mark.asyncio
async def test_get_block_hash_without_block_id_aka_none(subtensor):
"""Tests get_block_hash method without passed block_id."""
# Call
result = await subtensor.get_block_hash()
# Asserts
assert result == subtensor.substrate.get_chain_head.return_value
@pytest.mark.asyncio
async def test_get_block_hash_with_block_id(subtensor):
"""Tests get_block_hash method with passed block_id."""
# Call
result = await subtensor.get_block_hash(block=1)
# Asserts
assert result == subtensor.substrate.get_block_hash.return_value
@pytest.mark.asyncio
async def test_is_hotkey_registered_any(subtensor, mocker):
"""Tests is_hotkey_registered_any method."""
# Preps
mocked_get_netuids_for_hotkey = mocker.AsyncMock(
return_value=[1, 2], autospec=subtensor.get_netuids_for_hotkey
)
subtensor.get_netuids_for_hotkey = mocked_get_netuids_for_hotkey
# Call
result = await subtensor.is_hotkey_registered_any(
hotkey_ss58="hotkey", block_hash="FAKE_HASH"
)
# Asserts
assert result is (len(mocked_get_netuids_for_hotkey.return_value) > 0)
@pytest.mark.asyncio
async def test_get_subnet_burn_cost(subtensor, mocker):
"""Tests get_subnet_burn_cost method."""
# Preps
mocked_query_runtime_api = mocker.AsyncMock(autospec=subtensor.query_runtime_api)
subtensor.query_runtime_api = mocked_query_runtime_api
fake_block_hash = None
# Call
result = await subtensor.get_subnet_burn_cost(block_hash=fake_block_hash)
# Assert
assert result == mocked_query_runtime_api.return_value
mocked_query_runtime_api.assert_called_once_with(
runtime_api="SubnetRegistrationRuntimeApi",
method="get_network_registration_cost",
params=[],
block=None,
block_hash=fake_block_hash,
reuse_block=False,
)
@pytest.mark.asyncio
async def test_get_total_subnets(subtensor, mocker):
"""Tests get_total_subnets method."""
# Preps
mocked_substrate_query = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query
)
subtensor.substrate.query = mocked_substrate_query
fake_block_hash = None
# Call
result = await subtensor.get_total_subnets(block_hash=fake_block_hash)
# Assert
assert result == mocked_substrate_query.return_value.value
mocked_substrate_query.assert_called_once_with(
module="SubtensorModule",
storage_function="TotalNetworks",
params=[],
block_hash=fake_block_hash,
reuse_block_hash=False,
)
@pytest.mark.parametrize(
"records, response",
[([(0, True), (1, False), (3, False), (3, True)], [0, 3]), ([], [])],
ids=["with records", "empty-records"],
)
@pytest.mark.asyncio
async def test_get_subnets(subtensor, mocker, records, response):
"""Tests get_subnets method with any return."""
# Preps
fake_result = mocker.AsyncMock(autospec=list)
fake_result.records = records
fake_result.__aiter__.return_value = iter(records)
mocked_substrate_query_map = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query_map,
return_value=fake_result,
)
subtensor.substrate.query_map = mocked_substrate_query_map
fake_block_hash = None
# Call
result = await subtensor.get_subnets(block_hash=fake_block_hash)
# Asserts
mocked_substrate_query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
block_hash=fake_block_hash,
reuse_block_hash=False,
)
assert result == response
@pytest.mark.parametrize(
"hotkey_ss58_in_result",
[True, False],
ids=["hotkey-exists", "hotkey-doesnt-exist"],
)
@pytest.mark.asyncio
async def test_is_hotkey_delegate(subtensor, mocker, hotkey_ss58_in_result):
"""Tests is_hotkey_delegate method with any return."""
# Preps
fake_hotkey_ss58 = "hotkey_58"
mocked_get_delegates = mocker.AsyncMock(
return_value=[
mocker.Mock(hotkey_ss58=fake_hotkey_ss58 if hotkey_ss58_in_result else "")
]
)
subtensor.get_delegates = mocked_get_delegates
# Call
result = await subtensor.is_hotkey_delegate(
hotkey_ss58=fake_hotkey_ss58, block_hash=None, reuse_block=True
)
# Asserts
assert result == hotkey_ss58_in_result
mocked_get_delegates.assert_called_once_with(block_hash=None, reuse_block=True)
@pytest.mark.parametrize(
"fake_result, response", [(None, []), ([mock.Mock()], [mock.Mock()])]
)
@pytest.mark.asyncio
async def test_get_delegates(subtensor, mocker, fake_result, response):
"""Tests get_delegates method."""
# Preps
mocked_query_runtime_api = mocker.AsyncMock(
autospec=subtensor.query_runtime_api, return_value=fake_result
)
subtensor.query_runtime_api = mocked_query_runtime_api
mocked_delegate_info_list_from_dicts = mocker.Mock()
async_subtensor.DelegateInfo.list_from_dicts = mocked_delegate_info_list_from_dicts
# Call
result = await subtensor.get_delegates(block_hash=None, reuse_block=False)
# Asserts
if fake_result:
assert result == mocked_delegate_info_list_from_dicts.return_value
mocked_delegate_info_list_from_dicts.assert_called_once_with(fake_result)
else:
assert result == response
mocked_query_runtime_api.assert_called_once_with(
runtime_api="DelegateInfoRuntimeApi",
method="get_delegates",
params=[],
block=None,
block_hash=None,
reuse_block=False,
)
@pytest.mark.parametrize(
"fake_result, response", [(None, []), ([mock.Mock()], [mock.Mock()])]
)
@pytest.mark.asyncio
async def test_get_stake_info_for_coldkey(subtensor, mocker, fake_result, response):
"""Tests get_stake_info_for_coldkey method."""
# Preps
fake_coldkey_ss58 = "fake_coldkey_58"
mocked_query_runtime_api = mocker.AsyncMock(
autospec=subtensor.query_runtime_api, return_value=fake_result
)
subtensor.query_runtime_api = mocked_query_runtime_api
mock_stake_info = mocker.Mock(
spec=async_subtensor.StakeInfo, stake=Balance.from_rao(100)
)
mocked_stake_info_list_from_dicts = mocker.Mock(
return_value=[mock_stake_info] if fake_result else []
)
async_subtensor.StakeInfo.list_from_dicts = mocked_stake_info_list_from_dicts
# Call
result = await subtensor.get_stake_info_for_coldkey(
coldkey_ss58=fake_coldkey_ss58, block_hash=None, reuse_block=True
)
# Asserts
if fake_result:
mocked_stake_info_list_from_dicts.assert_called_once_with(fake_result)
assert result == mocked_stake_info_list_from_dicts.return_value
else:
assert result == []
mocked_query_runtime_api.assert_called_once_with(
runtime_api="StakeInfoRuntimeApi",
method="get_stake_info_for_coldkey",
params=[fake_coldkey_ss58],
block=None,
block_hash=None,
reuse_block=True,
)
@pytest.mark.asyncio
async def test_get_stake_for_coldkey_and_hotkey(subtensor, mocker):
"""Tests get_stake_for_coldkey_and_hotkey method."""
# Preps
mocked_substrate_query = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query
)
subtensor.substrate.query = mocked_substrate_query
spy_balance = mocker.spy(async_subtensor, "Balance")
# Call
result = await subtensor.get_stake_for_coldkey_and_hotkey(
hotkey_ss58="hotkey", coldkey_ss58="coldkey", block_hash=None
)
# Asserts
mocked_substrate_query.assert_awaited_with(
module="SubtensorModule",
storage_function="TotalHotkeyShares",
params=["hotkey", None],
block_hash=None,
reuse_block_hash=False,
)
assert mocked_substrate_query.call_count == 3
assert result == spy_balance.from_rao.return_value.set_unit.return_value
spy_balance.from_rao.assert_called()
assert spy_balance.from_rao.call_count == 1
@pytest.mark.asyncio
async def test_query_runtime_api(subtensor, mocker):
"""Tests query_runtime_api method."""
# Preps
fake_runtime_api = "DelegateInfoRuntimeApi"
fake_method = "get_delegated"
fake_params = [1, 2, 3]
fake_block_hash = None
reuse_block = False
mocked_runtime_call = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.runtime_call
)
subtensor.substrate.runtime_call = mocked_runtime_call
mocked_scalecodec = mocker.Mock(autospec=async_subtensor.scalecodec.ScaleBytes)
mocker.patch.object(async_subtensor.scalecodec, "ScaleBytes", mocked_scalecodec)
# Call
result = await subtensor.query_runtime_api(
runtime_api=fake_runtime_api,
method=fake_method,
params=fake_params,
block_hash=fake_block_hash,
reuse_block=reuse_block,
)
# Asserts
mocked_runtime_call.assert_called_once_with(
fake_runtime_api,
fake_method,
fake_params,
fake_block_hash,
)
assert result == mocked_runtime_call.return_value.value
@pytest.mark.asyncio
async def test_get_balance(subtensor, mocker):
"""Tests get_balance method."""
# Preps
fake_address = "a1"
fake_block = 123
fake_block_hash = None
reuse_block = True
mocked_determine_block_hash = mocker.AsyncMock()
mocker.patch.object(
async_subtensor.AsyncSubtensor,
"determine_block_hash",
mocked_determine_block_hash,
)
mocked_balance = mocker.patch.object(async_subtensor, "Balance")
# Call
result = await subtensor.get_balance(
fake_address, fake_block, fake_block_hash, reuse_block
)
mocked_determine_block_hash.assert_awaited_once_with(
fake_block, fake_block_hash, reuse_block
)
subtensor.substrate.query.assert_awaited_once_with(
module="System",
storage_function="Account",
params=[fake_address],
block_hash=mocked_determine_block_hash.return_value,
reuse_block_hash=reuse_block,
)
mocked_balance.assert_called_once_with(
subtensor.substrate.query.return_value.__getitem__.return_value.__getitem__.return_value
)
assert result == mocked_balance.return_value
@pytest.mark.parametrize("balance", [100, 100.1])
@pytest.mark.asyncio
async def test_get_transfer_fee(subtensor, mocker, balance):
"""Tests get_transfer_fee method."""
# Preps
fake_wallet = mocker.Mock(coldkeypub="coldkeypub", autospec=Wallet)
fake_dest = "fake_dest"
fake_value = balance
mocked_compose_call = mocker.AsyncMock()
subtensor.substrate.compose_call = mocked_compose_call
mocked_get_payment_info = mocker.AsyncMock(return_value={"partialFee": 100})
subtensor.substrate.get_payment_info = mocked_get_payment_info
# Call
result = await subtensor.get_transfer_fee(
wallet=fake_wallet, dest=fake_dest, value=fake_value
)
# Assertions
mocked_compose_call.assert_awaited_once()
mocked_compose_call.assert_called_once_with(
call_module="Balances",
call_function="transfer_allow_death",
call_params={
"dest": fake_dest,
"value": async_subtensor.Balance.from_rao(fake_value),
},
)
assert isinstance(result, async_subtensor.Balance)
mocked_get_payment_info.assert_awaited_once()
mocked_get_payment_info.assert_called_once_with(
call=mocked_compose_call.return_value, keypair="coldkeypub"
)
@pytest.mark.asyncio
async def test_get_transfer_fee_with_non_balance_accepted_value_type(subtensor, mocker):
"""Tests get_transfer_fee method with non balance accepted value type."""
# Preps
fake_wallet = mocker.Mock(coldkeypub="coldkeypub", autospec=Wallet)
fake_dest = "fake_dest"
fake_value = "1000"
# Call
result = await subtensor.get_transfer_fee(
wallet=fake_wallet, dest=fake_dest, value=fake_value
)
# Assertions
assert result == async_subtensor.Balance.from_rao(int(2e7))
@pytest.mark.asyncio
async def test_get_transfer_with_exception(subtensor, mocker):
"""Tests get_transfer_fee method handle Exception properly."""
# Preps
fake_value = 123
mocked_compose_call = mocker.AsyncMock()
subtensor.substrate.compose_call = mocked_compose_call
subtensor.substrate.get_payment_info.side_effect = Exception
# Call
result = await subtensor.get_transfer_fee(
wallet=mocker.Mock(), dest=mocker.Mock(), value=fake_value
)
# Assertions
assert result == async_subtensor.Balance.from_rao(int(2e7))
@pytest.mark.asyncio
async def test_get_total_stake_for_coldkey(subtensor, mocker):
"""Tests get_total_stake_for_coldkey method."""
# Preps
fake_addresses = "a1"
fake_block_hash = None
mocked_determine_block_hash = mocker.AsyncMock()
mocker.patch.object(
async_subtensor.AsyncSubtensor,
"determine_block_hash",
mocked_determine_block_hash,
)
mocked_balance_from_rao = mocker.patch.object(async_subtensor.Balance, "from_rao")
# Call
result = await subtensor.get_total_stake_for_coldkey(
fake_addresses, block_hash=fake_block_hash
)
mocked_determine_block_hash.assert_awaited_once_with(
block=None, block_hash=None, reuse_block=False
)
subtensor.substrate.query.assert_awaited_once_with(
module="SubtensorModule",
storage_function="TotalColdkeyStake",
params=[fake_addresses],
block_hash=mocked_determine_block_hash.return_value,
reuse_block_hash=False,
)
assert result == mocked_balance_from_rao.return_value
@pytest.mark.asyncio
async def test_get_total_stake_for_hotkey(subtensor, mocker):
"""Tests get_total_stake_for_hotkey method."""
# Preps
fake_addresses = "a1"
fake_block_hash = None
mocked_determine_block_hash = mocker.AsyncMock()
mocker.patch.object(
async_subtensor.AsyncSubtensor,
"determine_block_hash",
mocked_determine_block_hash,
)
mocked_balance_from_rao = mocker.patch.object(async_subtensor.Balance, "from_rao")
# Call
result = await subtensor.get_total_stake_for_hotkey(
fake_addresses, block_hash=fake_block_hash
)
mocked_determine_block_hash.assert_awaited_once_with(
block=None, block_hash=None, reuse_block=False
)
subtensor.substrate.query.assert_awaited_once_with(
module="SubtensorModule",
storage_function="TotalHotkeyStake",
params=[fake_addresses],
block_hash=mocked_determine_block_hash.return_value,
reuse_block_hash=False,
)
assert result == mocked_balance_from_rao.return_value
@pytest.mark.asyncio
async def test_get_netuids_for_hotkey_with_records(subtensor, mocker):
"""Tests get_netuids_for_hotkey method handle records properly."""
# Preps
records = []
expected_response = []
fake_result = mocker.AsyncMock(autospec=list)
fake_result.records = records
fake_result.__aiter__.return_value = iter(records)
mocked_substrate_query_map = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query_map,
return_value=fake_result,
)
subtensor.substrate.query_map = mocked_substrate_query_map
fake_hotkey_ss58 = "hotkey_58"
fake_block_hash = None
# Call
result = await subtensor.get_netuids_for_hotkey(
hotkey_ss58=fake_hotkey_ss58, block_hash=fake_block_hash, reuse_block=True
)
# Assertions
mocked_substrate_query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="IsNetworkMember",
params=[fake_hotkey_ss58],
block_hash=fake_block_hash,
reuse_block_hash=True,
)
assert result == expected_response
@pytest.mark.asyncio
async def test_get_netuids_for_hotkey_without_records(subtensor, mocker):
"""Tests get_netuids_for_hotkey method handle empty records properly."""
# Preps
records = []
expected_response = []
fake_result = mocker.AsyncMock(autospec=list)
fake_result.records = records
fake_result.__aiter__.return_value = iter(records)
mocked_substrate_query_map = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query_map,
return_value=fake_result,
)
subtensor.substrate.query_map = mocked_substrate_query_map
fake_hotkey_ss58 = "hotkey_58"
fake_block_hash = None
# Call
result = await subtensor.get_netuids_for_hotkey(
hotkey_ss58=fake_hotkey_ss58, block_hash=fake_block_hash, reuse_block=True
)
# Assertions
mocked_substrate_query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="IsNetworkMember",
params=[fake_hotkey_ss58],
block_hash=fake_block_hash,
reuse_block_hash=True,
)
assert result == expected_response
@pytest.mark.asyncio
async def test_subnet_exists(subtensor, mocker):
"""Tests subnet_exists method ."""
# Preps
fake_netuid = 1
fake_block_hash = "block_hash"
fake_reuse_block_hash = False
mocked_substrate_query = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query
)
subtensor.substrate.query = mocked_substrate_query
# Call
result = await subtensor.subnet_exists(
netuid=fake_netuid,
block_hash=fake_block_hash,
reuse_block=fake_reuse_block_hash,
)
# Asserts
mocked_substrate_query.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[fake_netuid],
block_hash=fake_block_hash,
reuse_block_hash=fake_reuse_block_hash,
)
assert result == mocked_substrate_query.return_value.value
@pytest.mark.asyncio
async def test_get_hyperparameter_happy_path(subtensor, mocker):
"""Tests get_hyperparameter method with happy path."""
# Preps
fake_param_name = "param_name"
fake_netuid = 1
fake_block_hash = "block_hash"
fake_reuse_block_hash = False
# kind of fake subnet exists
mocked_subtensor_subnet_exists = mocker.AsyncMock(return_value=True)
subtensor.subnet_exists = mocked_subtensor_subnet_exists
mocked_substrate_query = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query
)
subtensor.substrate.query = mocked_substrate_query
# Call
result = await subtensor.get_hyperparameter(
param_name=fake_param_name,
netuid=fake_netuid,
block_hash=fake_block_hash,
reuse_block=fake_reuse_block_hash,
)
# Assertions
mocked_subtensor_subnet_exists.assert_called_once()
mocked_substrate_query.assert_called_once_with(
module="SubtensorModule",
storage_function=fake_param_name,
params=[fake_netuid],
block_hash=fake_block_hash,
reuse_block_hash=fake_reuse_block_hash,
)
assert result == mocked_substrate_query.return_value.value
@pytest.mark.asyncio
async def test_get_hyperparameter_if_subnet_does_not_exist(subtensor, mocker):
"""Tests get_hyperparameter method if subnet does not exist."""
# Preps
# kind of fake subnet doesn't exist
mocked_subtensor_subnet_exists = mocker.AsyncMock(return_value=False)
subtensor.subnet_exists = mocked_subtensor_subnet_exists
mocked_substrate_query = mocker.AsyncMock(
autospec=async_subtensor.AsyncSubstrateInterface.query
)
subtensor.substrate.query = mocked_substrate_query
# Call
result = await subtensor.get_hyperparameter(mocker.Mock(), mocker.Mock())
# Assertions
mocked_subtensor_subnet_exists.assert_called_once()
mocked_substrate_query.assert_not_called()
assert result is None
@pytest.mark.parametrize(
"all_netuids, filter_for_netuids, response",
[([1, 2], [3, 4], []), ([1, 2], [1, 3], [1]), ([1, 2], None, [1, 2])],
ids=[
"all arguments -> no comparison",
"all arguments -> is comparison",
"not filter_for_netuids",
],
)
@pytest.mark.asyncio
async def test_filter_netuids_by_registered_hotkeys(
subtensor, mocker, all_netuids, filter_for_netuids, response
):
"""Tests filter_netuids_by_registered_hotkeys method."""
# Preps
fake_wallet_1 = mocker.Mock(autospec=Wallet)
fake_wallet_1.hotkey.ss58_address = "ss58_address_1"
fake_wallet_2 = mocker.Mock(autospec=Wallet)
fake_wallet_2.hotkey.ss58_address = "ss58_address_2"
fake_all_netuids = all_netuids
fake_filter_for_netuids = filter_for_netuids
fake_all_hotkeys = [fake_wallet_1, fake_wallet_2]
fake_block_hash = "fake_block_hash"
fake_reuse_block = False
mocked_get_netuids_for_hotkey = mocker.AsyncMock(
# returned subnets list
return_value=[1, 2]
)
subtensor.get_netuids_for_hotkey = mocked_get_netuids_for_hotkey
# Call
result = await subtensor.filter_netuids_by_registered_hotkeys(
all_netuids=fake_all_netuids,
filter_for_netuids=fake_filter_for_netuids,
all_hotkeys=fake_all_hotkeys,
block_hash=fake_block_hash,
reuse_block=fake_reuse_block,
)
# Asserts
mocked_get_netuids_for_hotkey.call_count = len(fake_all_netuids)
assert mocked_get_netuids_for_hotkey.mock_calls == [
mocker.call(
w.hotkey.ss58_address,
block_hash=fake_block_hash,
reuse_block=fake_reuse_block,
)
for w in fake_all_hotkeys
]
assert result == response
@pytest.mark.asyncio
async def test_get_existential_deposit_happy_path(subtensor, mocker):
"""Tests get_existential_deposit method."""
# Preps
fake_block_hash = "block_hash"
fake_reuse_block_hash = False
mocked_substrate_get_constant = mocker.AsyncMock(return_value=mocker.Mock(value=1))
subtensor.substrate.get_constant = mocked_substrate_get_constant
spy_balance_from_rao = mocker.spy(async_subtensor.Balance, "from_rao")
# Call
result = await subtensor.get_existential_deposit(
block_hash=fake_block_hash, reuse_block=fake_reuse_block_hash
)
# Asserts
mocked_substrate_get_constant.assert_awaited_once()
mocked_substrate_get_constant.assert_called_once_with(
module_name="Balances",
constant_name="ExistentialDeposit",
block_hash=fake_block_hash,
reuse_block_hash=fake_reuse_block_hash,
)
spy_balance_from_rao.assert_called_once_with(
mocked_substrate_get_constant.return_value.value
)
assert result == async_subtensor.Balance(
mocked_substrate_get_constant.return_value.value
)
@pytest.mark.asyncio
async def test_get_existential_deposit_raise_exception(subtensor, mocker):
"""Tests get_existential_deposit method raise Exception."""
# Preps
fake_block_hash = "block_hash"
fake_reuse_block_hash = False
mocked_substrate_get_constant = mocker.AsyncMock(return_value=None)
subtensor.substrate.get_constant = mocked_substrate_get_constant
spy_balance_from_rao = mocker.spy(async_subtensor.Balance, "from_rao")
# Call
with pytest.raises(Exception):
await subtensor.get_existential_deposit(
block_hash=fake_block_hash, reuse_block=fake_reuse_block_hash
)
# Asserts
mocked_substrate_get_constant.assert_awaited_once()
mocked_substrate_get_constant.assert_called_once_with(
module_name="Balances",
constant_name="ExistentialDeposit",
block_hash=fake_block_hash,
reuse_block_hash=fake_reuse_block_hash,
)
spy_balance_from_rao.assert_not_called()