-
Notifications
You must be signed in to change notification settings - Fork 444
Expand file tree
/
Copy pathtest_subtensor.py
More file actions
3634 lines (3013 loc) · 106 KB
/
test_subtensor.py
File metadata and controls
3634 lines (3013 loc) · 106 KB
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 argparse
import unittest.mock as mock
import datetime
from unittest.mock import MagicMock
import pytest
from bittensor_wallet import Wallet
from async_substrate_interface import sync_substrate
from async_substrate_interface.types import ScaleObj
import websockets
from bittensor import StakeInfo
from bittensor.core import settings
from bittensor.core import subtensor as subtensor_module
from bittensor.core.async_subtensor import AsyncSubtensor, logging
from bittensor.core.axon import Axon
from bittensor.core.chain_data import SubnetHyperparameters, SelectiveMetagraphIndex
from bittensor.core.extrinsics.serving import do_serve_axon
from bittensor.core.settings import version_as_int
from bittensor.core.subtensor import Subtensor
from bittensor.core.types import AxonServeCallParams
from bittensor.utils import (
Certificate,
u16_normalized_float,
u64_normalized_float,
determine_chain_endpoint_and_network,
)
from bittensor.utils.balance import Balance
U16_MAX = 65535
U64_MAX = 18446744073709551615
@pytest.fixture
def fake_call_params():
return call_params()
def call_params():
return AxonServeCallParams(
version=settings.version_as_int,
ip=0,
port=9090,
ip_type=4,
netuid=1,
hotkey="str",
coldkey="str",
protocol=4,
placeholder1=0,
placeholder2=0,
certificate=None,
)
def call_params_with_certificate():
params = call_params()
params.certificate = Certificate("fake_cert")
return params
def test_methods_comparable(mock_substrate):
"""Verifies that methods in sync and async Subtensors are comparable."""
# Preps
subtensor = Subtensor(_mock=True)
async_subtensor = AsyncSubtensor(_mock=True)
# methods which lives in async subtensor only
excluded_async_subtensor_methods = ["initialize"]
subtensor_methods = [m for m in dir(subtensor) if not m.startswith("_")]
async_subtensor_methods = [
m
for m in dir(async_subtensor)
if not m.startswith("_") and m not in excluded_async_subtensor_methods
]
# Assertions
for method in subtensor_methods:
assert method in async_subtensor_methods, (
f"`Subtensor.{method}` not in `AsyncSubtensor` class."
)
for method in async_subtensor_methods:
assert method in subtensor_methods, (
f"`AsyncSubtensor.{method}` not in `Subtensor` class."
)
def test_serve_axon_with_external_ip_set():
internal_ip: str = "192.0.2.146"
external_ip: str = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
mock_serve_axon = MagicMock(return_value=True)
mock_subtensor = MagicMock(spec=Subtensor, serve_axon=mock_serve_axon)
mock_wallet = MagicMock(
spec=Wallet,
coldkey=MagicMock(),
coldkeypub=MagicMock(
# mock ss58 address
ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm"
),
hotkey=MagicMock(
ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg"
),
)
mock_config = Axon.config()
mock_axon_with_external_ip_set = Axon(
wallet=mock_wallet,
ip=internal_ip,
external_ip=external_ip,
config=mock_config,
)
mock_subtensor.serve_axon(
netuid=-1,
axon=mock_axon_with_external_ip_set,
)
mock_serve_axon.assert_called_once()
# verify that the axon is served to the network with the external ip
_, kwargs = mock_serve_axon.call_args
axon_info = kwargs["axon"].info()
assert axon_info.ip == external_ip
def test_serve_axon_with_external_port_set(mock_get_external_ip):
internal_port: int = 1234
external_port: int = 5678
mock_serve = MagicMock(return_value=True)
mock_serve_axon = MagicMock(return_value=True)
mock_subtensor = MagicMock(
spec=Subtensor,
serve=mock_serve,
serve_axon=mock_serve_axon,
)
mock_wallet = MagicMock(
spec=Wallet,
coldkey=MagicMock(),
coldkeypub=MagicMock(
# mock ss58 address
ss58_address="5DD26kC2kxajmwfbbZmVmxhrY9VeeyR1Gpzy9i8wxLUg6zxm"
),
hotkey=MagicMock(
ss58_address="5CtstubuSoVLJGCXkiWRNKrrGg2DVBZ9qMs2qYTLsZR4q1Wg"
),
)
mock_config = Axon.config()
mock_axon_with_external_port_set = Axon(
wallet=mock_wallet,
port=internal_port,
external_port=external_port,
config=mock_config,
)
mock_subtensor.serve_axon(
netuid=-1,
axon=mock_axon_with_external_port_set,
)
mock_serve_axon.assert_called_once()
# verify that the axon is served to the network with the external port
_, kwargs = mock_serve_axon.call_args
axon_info = kwargs["axon"].info()
assert axon_info.port == external_port
class ExitEarly(Exception):
"""Mock exception to exit early from the called code"""
pass
@pytest.mark.parametrize(
"test_id, expected_output",
[
# Happy path test
(
"happy_path_default",
"Create and return a new object. See help(type) for accurate signature.",
),
],
)
def test_help(test_id, expected_output, capsys):
# Act
Subtensor.help()
# Assert
captured = capsys.readouterr()
assert expected_output in captured.out, f"Test case {test_id} failed"
@pytest.fixture
def parser():
return argparse.ArgumentParser()
# Mocking argparse.ArgumentParser.add_argument method to simulate ArgumentError
def test_argument_error_handling(monkeypatch, parser):
def mock_add_argument(*args, **kwargs):
raise argparse.ArgumentError(None, "message")
monkeypatch.setattr(argparse.ArgumentParser, "add_argument", mock_add_argument)
# No exception should be raised
Subtensor.add_args(parser)
@pytest.mark.parametrize(
"network, expected_network, expected_endpoint",
[
# Happy path tests
("finney", "finney", settings.FINNEY_ENTRYPOINT),
("local", "local", settings.LOCAL_ENTRYPOINT),
("test", "test", settings.FINNEY_TEST_ENTRYPOINT),
("archive", "archive", settings.ARCHIVE_ENTRYPOINT),
# Endpoint override tests
(
settings.FINNEY_ENTRYPOINT,
"finney",
settings.FINNEY_ENTRYPOINT,
),
(
"entrypoint-finney.opentensor.ai",
"finney",
settings.FINNEY_ENTRYPOINT,
),
(
settings.FINNEY_TEST_ENTRYPOINT,
"test",
settings.FINNEY_TEST_ENTRYPOINT,
),
(
"test.finney.opentensor.ai",
"test",
settings.FINNEY_TEST_ENTRYPOINT,
),
(
settings.ARCHIVE_ENTRYPOINT,
"archive",
settings.ARCHIVE_ENTRYPOINT,
),
(
"archive.chain.opentensor.ai",
"archive",
settings.ARCHIVE_ENTRYPOINT,
),
("127.0.0.1", "local", "127.0.0.1"),
("localhost", "local", "localhost"),
("ws://127.0.0.1:9945", "local", "ws://127.0.0.1:9945"),
("ws://localhost:9945", "local", "ws://localhost:9945"),
# Edge cases
(None, None, None),
("unknown", "unknown", "unknown"),
],
)
def test_determine_chain_endpoint_and_network(
network, expected_network, expected_endpoint
):
# Act
result_network, result_endpoint = determine_chain_endpoint_and_network(network)
# Assert
assert result_network == expected_network
assert result_endpoint == expected_endpoint
@pytest.fixture
def mock_logger():
with mock.patch.object(logging, "warning") as mock_warning:
yield mock_warning
def test_hyperparameter_subnet_does_not_exist(subtensor, mocker):
"""Tests when the subnet does not exist."""
subtensor.subnet_exists = mocker.MagicMock(return_value=False)
assert subtensor.get_hyperparameter("Difficulty", 1, None) is None
subtensor.subnet_exists.assert_called_once_with(1, block=None)
def test_hyperparameter_result_is_none(subtensor, mocker):
"""Tests when query_subtensor returns None."""
subtensor.subnet_exists = mocker.MagicMock(return_value=True)
subtensor.substrate.query = mocker.MagicMock(return_value=None)
assert subtensor.get_hyperparameter("Difficulty", 1, None) is None
subtensor.subnet_exists.assert_called_once_with(1, block=None)
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="Difficulty",
params=[1],
block_hash=None,
)
def test_hyperparameter_result_has_no_value(subtensor, mocker):
"""Test when the result has no 'value' attribute."""
subtensor.subnet_exists = mocker.MagicMock(return_value=True)
subtensor.substrate.query = mocker.MagicMock(return_value=None)
assert subtensor.get_hyperparameter("Difficulty", 1, None) is None
subtensor.subnet_exists.assert_called_once_with(1, block=None)
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="Difficulty",
params=[1],
block_hash=None,
)
def test_hyperparameter_success_int(subtensor, mocker):
"""Test when query_subtensor returns an integer value."""
subtensor.subnet_exists = mocker.MagicMock(return_value=True)
subtensor.substrate.query = mocker.MagicMock(
return_value=mocker.MagicMock(value=100)
)
assert subtensor.get_hyperparameter("Difficulty", 1, None) == 100
subtensor.subnet_exists.assert_called_once_with(1, block=None)
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="Difficulty",
params=[1],
block_hash=None,
)
def test_hyperparameter_success_float(subtensor, mocker):
"""Test when query_subtensor returns a float value."""
subtensor.subnet_exists = mocker.MagicMock(return_value=True)
subtensor.substrate.query = mocker.MagicMock(
return_value=mocker.MagicMock(value=0.5)
)
assert subtensor.get_hyperparameter("Difficulty", 1, None) == 0.5
subtensor.subnet_exists.assert_called_once_with(1, block=None)
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="Difficulty",
params=[1],
block_hash=None,
)
def test_blocks_since_last_update_success_calls(subtensor, mocker):
"""Tests the weights_rate_limit method to ensure it correctly fetches the LastUpdate hyperparameter."""
# Prep
uid = 7
mocked_current_block = 2
mocked_result = {uid: 1}
mocked_get_hyperparameter = mocker.patch.object(
subtensor,
"get_hyperparameter",
return_value=mocked_result,
)
mocked_get_current_block = mocker.patch.object(
subtensor,
"get_current_block",
return_value=mocked_current_block,
)
# Call
result = subtensor.blocks_since_last_update(netuid=7, uid=uid)
# Assertions
mocked_get_current_block.assert_called_once()
mocked_get_hyperparameter.assert_called_once_with(param_name="LastUpdate", netuid=7)
assert result == 1
# if we change the methods logic in the future we have to be make sure the returned type is correct
assert isinstance(result, int)
def test_weights_rate_limit_success_calls(subtensor, mocker):
"""Tests the weights_rate_limit method to ensure it correctly fetches the WeightsSetRateLimit hyperparameter."""
# Prep
mocked_get_hyperparameter = mocker.patch.object(
subtensor,
"get_hyperparameter",
return_value=5,
)
# Call
result = subtensor.weights_rate_limit(netuid=7)
# Assertions
mocked_get_hyperparameter.assert_called_once_with(
param_name="WeightsSetRateLimit",
netuid=7,
block=None,
)
# if we change the methods logic in the future we have to be make sure the returned type is correct
assert isinstance(result, int)
@pytest.fixture
def sample_hyperparameters():
return MagicMock(spec=SubnetHyperparameters)
def normalize_hyperparameters(
subnet: "SubnetHyperparameters",
) -> list[tuple[str, str, str]]:
"""
Normalizes the hyperparameters of a subnet.
Args:
subnet: The subnet hyperparameters object.
Returns:
A list of tuples containing the parameter name, value, and normalized value.
"""
param_mappings = {
"adjustment_alpha": u64_normalized_float,
"min_difficulty": u64_normalized_float,
"max_difficulty": u64_normalized_float,
"difficulty": u64_normalized_float,
"bonds_moving_avg": u64_normalized_float,
"max_weight_limit": u16_normalized_float,
"kappa": u16_normalized_float,
"alpha_high": u16_normalized_float,
"alpha_low": u16_normalized_float,
"min_burn": Balance.from_rao,
"max_burn": Balance.from_rao,
}
normalized_values: list[tuple[str, str, str]] = []
subnet_dict = subnet.__dict__
for param, value in subnet_dict.items():
try:
if param in param_mappings:
norm_value = param_mappings[param](value)
if isinstance(norm_value, float):
norm_value = f"{norm_value:.{10}g}"
else:
norm_value = value
except Exception as e:
logging.console.error(f"❌ Error normalizing parameter '{param}': {e}")
norm_value = "-"
normalized_values.append((param, str(value), str(norm_value)))
return normalized_values
def get_normalized_value(normalized_data, param_name):
return next(
(
norm_value
for p_name, _, norm_value in normalized_data
if p_name == param_name
),
None,
)
@pytest.mark.parametrize(
"param_name, max_value, mid_value, zero_value, is_balance",
[
("adjustment_alpha", U64_MAX, U64_MAX / 2, 0, False),
("max_weight_limit", U16_MAX, U16_MAX / 2, 0, False),
("difficulty", U64_MAX, U64_MAX / 2, 0, False),
("min_difficulty", U64_MAX, U64_MAX / 2, 0, False),
("max_difficulty", U64_MAX, U64_MAX / 2, 0, False),
("bonds_moving_avg", U64_MAX, U64_MAX / 2, 0, False),
("min_burn", 10000000000, 5000000000, 0, True), # These are in rao
("max_burn", 20000000000, 10000000000, 0, True),
],
ids=[
"adjustment-alpha",
"max_weight_limit",
"difficulty",
"min_difficulty",
"max_difficulty",
"bonds_moving_avg",
"min_burn",
"max_burn",
],
)
def test_hyperparameter_normalization(
sample_hyperparameters, param_name, max_value, mid_value, zero_value, is_balance
):
setattr(sample_hyperparameters, param_name, mid_value)
normalized = normalize_hyperparameters(sample_hyperparameters)
norm_value = get_normalized_value(normalized, param_name)
# Mid-value test
if is_balance:
numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL))
expected_tao = mid_value / 1e9
assert numeric_value == expected_tao, (
f"Mismatch in tao value for {param_name} at mid value"
)
else:
assert float(norm_value) == 0.5, f"Failed mid-point test for {param_name}"
# Max-value test
setattr(sample_hyperparameters, param_name, max_value)
normalized = normalize_hyperparameters(sample_hyperparameters)
norm_value = get_normalized_value(normalized, param_name)
if is_balance:
numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL))
expected_tao = max_value / 1e9
assert numeric_value == expected_tao, (
f"Mismatch in tao value for {param_name} at max value"
)
else:
assert float(norm_value) == 1.0, f"Failed max value test for {param_name}"
# Zero-value test
setattr(sample_hyperparameters, param_name, zero_value)
normalized = normalize_hyperparameters(sample_hyperparameters)
norm_value = get_normalized_value(normalized, param_name)
if is_balance:
numeric_value = float(str(norm_value).lstrip(settings.TAO_SYMBOL))
expected_tao = zero_value / 1e9
assert numeric_value == expected_tao, (
f"Mismatch in tao value for {param_name} at zero value"
)
else:
assert float(norm_value) == 0.0, f"Failed zero value test for {param_name}"
###########################
# Account functions tests #
###########################
def test_commit_reveal_enabled(subtensor, mocker):
"""Test commit_reveal_enabled."""
# Preps
netuid = 1
block = 123
mocked_get_hyperparameter = mocker.patch.object(subtensor, "get_hyperparameter")
# Call
result = subtensor.commit_reveal_enabled(netuid, block)
# Assertions
mocked_get_hyperparameter.assert_called_once_with(
param_name="CommitRevealWeightsEnabled", block=block, netuid=netuid
)
assert result is False
def test_get_subnet_reveal_period_epochs(subtensor, mocker):
"""Test get_subnet_reveal_period_epochs."""
# Preps
netuid = 1
block = 123
mocked_get_hyperparameter = mocker.patch.object(subtensor, "get_hyperparameter")
# Call
result = subtensor.get_subnet_reveal_period_epochs(netuid, block)
# Assertions
mocked_get_hyperparameter.assert_called_once_with(
param_name="RevealPeriodEpochs", block=block, netuid=netuid
)
assert result == mocked_get_hyperparameter.return_value
###########################
# Global Parameters tests #
###########################
# `block` property test
def test_block_property(mocker, subtensor):
"""Test block property returns the correct block number."""
expected_block = 123
mocker.patch.object(subtensor, "get_current_block", return_value=expected_block)
result = subtensor.block
assert result == expected_block
subtensor.get_current_block.assert_called_once()
# `subnet_exists` tests
def test_subnet_exists_success(mocker, subtensor):
"""Test subnet_exists returns True when subnet exists."""
# Prep
netuid = 1
block = 123
mock_result = mocker.MagicMock(value=True)
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.subnet_exists(netuid, block)
# Asserts
assert result is True
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[netuid],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_subnet_exists_no_data(mocker, subtensor):
"""Test subnet_exists returns False when no subnet information is found."""
# Prep
netuid = 1
block = 123
mocker.patch.object(subtensor.substrate, "query", return_value=None)
# Call
result = subtensor.subnet_exists(netuid, block)
# Asserts
assert result is False
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[netuid],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_subnet_exists_no_value_attribute(mocker, subtensor):
"""Test subnet_exists returns False when result has no value attribute."""
# Prep
netuid = 1
block = 123
mock_result = mocker.MagicMock()
del mock_result.value
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.subnet_exists(netuid, block)
# Asserts
assert result is False
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[netuid],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_subnet_exists_no_block(mocker, subtensor):
"""Test subnet_exists with no block specified."""
# Prep
netuid = 1
mock_result = mocker.MagicMock(value=True)
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.subnet_exists(netuid)
# Asserts
assert result is True
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
params=[netuid],
block_hash=None,
)
subtensor.substrate.get_block_hash.assert_not_called()
# `get_total_subnets` tests
def test_get_total_subnets_success(mocker, subtensor):
"""Test get_total_subnets returns correct data when total subnet information is found."""
# Prep
block = 123
total_subnets_value = 10
mock_result = mocker.MagicMock(value=total_subnets_value)
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.get_total_subnets(block)
# Asserts
assert result is not None
assert result == total_subnets_value
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="TotalNetworks",
params=[],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_get_total_subnets_no_data(mocker, subtensor):
"""Test get_total_subnets returns None when no total subnet information is found."""
# Prep
block = 123
mocker.patch.object(subtensor.substrate, "query", return_value=None)
# Call
result = subtensor.get_total_subnets(block)
# Asserts
assert result is None
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="TotalNetworks",
params=[],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_get_total_subnets_no_value_attribute(mocker, subtensor):
"""Test get_total_subnets returns None when result has no value attribute."""
# Prep
block = 123
mock_result = mocker.MagicMock()
del mock_result.value # Simulating a missing value attribute
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.get_total_subnets(block)
# Asserts
assert result is None
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="TotalNetworks",
params=[],
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_get_total_subnets_no_block(mocker, subtensor):
"""Test get_total_subnets with no block specified."""
# Prep
total_subnets_value = 10
mock_result = mocker.MagicMock(value=total_subnets_value)
mocker.patch.object(subtensor.substrate, "query", return_value=mock_result)
# Call
result = subtensor.get_total_subnets()
# Asserts
assert result is not None
assert result == total_subnets_value
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function="TotalNetworks",
params=[],
block_hash=None,
)
subtensor.substrate.get_block_hash.assert_not_called()
# `get_subnets` tests
def test_get_subnets_success(mocker, subtensor):
"""Test get_subnets returns correct list when subnet information is found."""
# Prep
block = 123
mock_result = mocker.MagicMock()
mock_result.records = [(1, True), (2, True)]
mock_result.__iter__.return_value = iter(mock_result.records)
mocker.patch.object(subtensor.substrate, "query_map", return_value=mock_result)
# Call
result = subtensor.get_subnets(block)
# Asserts
assert result == [1, 2]
subtensor.substrate.query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_get_subnets_no_data(mocker, subtensor):
"""Test get_subnets returns empty list when no subnet information is found."""
# Prep
block = 123
mock_result = mocker.MagicMock()
mock_result.records = []
mocker.patch.object(subtensor.substrate, "query_map", return_value=mock_result)
# Call
result = subtensor.get_subnets(block)
# Asserts
assert result == []
subtensor.substrate.query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
block_hash=subtensor.substrate.get_block_hash.return_value,
)
subtensor.substrate.get_block_hash.assert_called_once_with(block)
def test_get_subnets_no_block_specified(mocker, subtensor):
"""Test get_subnets with no block specified."""
# Prep
mock_result = mocker.MagicMock()
mock_result.records = [(1, True), (2, True)]
mock_result.__iter__.return_value = iter(mock_result.records)
mocker.patch.object(subtensor.substrate, "query_map", return_value=mock_result)
# Call
result = subtensor.get_subnets()
# Asserts
assert result == [1, 2]
subtensor.substrate.query_map.assert_called_once_with(
module="SubtensorModule",
storage_function="NetworksAdded",
block_hash=None,
)
subtensor.substrate.get_block_hash.assert_not_called
# `get_subnet_hyperparameters` tests
def test_get_subnet_hyperparameters_success(mocker, subtensor):
"""Test get_subnet_hyperparameters returns correct data when hyperparameters are found."""
# Prep
netuid = 1
block = 123
mocker.patch.object(
subtensor,
"query_runtime_api",
)
mocker.patch.object(
subtensor_module.SubnetHyperparameters,
"from_dict",
)
# Call
subtensor.get_subnet_hyperparameters(netuid, block)
# Asserts
subtensor.query_runtime_api.assert_called_once_with(
runtime_api="SubnetInfoRuntimeApi",
method="get_subnet_hyperparams",
params=[netuid],
block=block,
)
subtensor_module.SubnetHyperparameters.from_dict.assert_called_once_with(
subtensor.query_runtime_api.return_value,
)
def test_get_subnet_hyperparameters_no_data(mocker, subtensor):
"""Test get_subnet_hyperparameters returns empty list when no data is found."""
# Prep
netuid = 1
block = 123
mocker.patch.object(subtensor, "query_runtime_api", return_value=None)
mocker.patch.object(subtensor_module.SubnetHyperparameters, "from_dict")
# Call
result = subtensor.get_subnet_hyperparameters(netuid, block)
# Asserts
assert result is None
subtensor.query_runtime_api.assert_called_once_with(
runtime_api="SubnetInfoRuntimeApi",
method="get_subnet_hyperparams",
params=[netuid],
block=block,
)
subtensor_module.SubnetHyperparameters.from_dict.assert_not_called()
def test_query_subtensor(subtensor, mocker):
"""Tests query_subtensor call."""
# Prep
fake_name = "module_name"
# Call
result = subtensor.query_subtensor(fake_name)
# Asserts
subtensor.substrate.query.assert_called_once_with(
module="SubtensorModule",
storage_function=fake_name,
params=None,
block_hash=None,
)
assert result == subtensor.substrate.query.return_value
def test_query_runtime_api(subtensor, mocker):
"""Tests query_runtime_api call."""
# Prep
fake_runtime_api = "NeuronInfoRuntimeApi"
fake_method = "get_neuron_lite"
mock_determine_block_hash = mocker.patch.object(
subtensor,
"determine_block_hash",
)
# mock_runtime_call = mocker.patch.object(
# subtensor.substrate,
# "runtime_call",
# )
# Call
result = subtensor.query_runtime_api(fake_runtime_api, fake_method, None)
# Asserts
subtensor.substrate.runtime_call.assert_called_once_with(
fake_runtime_api,
fake_method,
None,
mock_determine_block_hash.return_value,
)
mock_determine_block_hash.assert_called_once_with(None)
assert result == subtensor.substrate.runtime_call.return_value.value
def test_query_map_subtensor(subtensor, mocker):
"""Tests query_map_subtensor call."""
# Prep
fake_name = "module_name"
# Call
result = subtensor.query_map_subtensor(fake_name)
# Asserts
subtensor.substrate.query_map.assert_called_once_with(
module="SubtensorModule",
storage_function=fake_name,
params=None,
block_hash=None,
)
assert result == subtensor.substrate.query_map.return_value
def test_state_call(subtensor, mocker):
"""Tests state_call call."""
# Prep
fake_method = "method"
fake_data = "data"
# Call
result = subtensor.state_call(fake_method, fake_data)
# Asserts
subtensor.substrate.rpc_request.assert_called_once_with(
method="state_call",
params=[fake_method, fake_data],
)
assert result == subtensor.substrate.rpc_request.return_value
def test_query_map(subtensor, mocker):
"""Tests query_map call."""
# Prep
fake_module_name = "module_name"
fake_name = "constant_name"
# Call
result = subtensor.query_map(fake_module_name, fake_name)
# Asserts
subtensor.substrate.query_map.assert_called_once_with(
module=fake_module_name,
storage_function=fake_name,
params=None,
block_hash=None,
)
assert result == subtensor.substrate.query_map.return_value
def test_query_constant(subtensor, mocker):
"""Tests query_constant call."""
# Prep
fake_module_name = "module_name"
fake_constant_name = "constant_name"
# Call
result = subtensor.query_constant(fake_module_name, fake_constant_name)
# Asserts
subtensor.substrate.get_constant.assert_called_once_with(
module_name=fake_module_name,
constant_name=fake_constant_name,
block_hash=None,
)
assert result == subtensor.substrate.get_constant.return_value
def test_query_module(subtensor):