-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathexecutable_test.py
More file actions
1152 lines (906 loc) · 44 KB
/
Copy pathexecutable_test.py
File metadata and controls
1152 lines (906 loc) · 44 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
from __future__ import annotations
from itertools import chain, repeat
from unittest.mock import patch
import grpc
import pytest
from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction
from hiero_sdk_python.account.account_id import AccountId
from hiero_sdk_python.consensus.topic_create_transaction import TopicCreateTransaction
from hiero_sdk_python.crypto.private_key import PrivateKey
from hiero_sdk_python.exceptions import MaxAttemptsError, PrecheckError
from hiero_sdk_python.executable import (
_is_transaction_receipt_or_record_request,
)
from hiero_sdk_python.hapi.services import (
basic_types_pb2,
crypto_get_account_balance_pb2,
query_pb2,
response_header_pb2,
response_pb2,
transaction_get_receipt_pb2,
transaction_receipt_pb2,
)
from hiero_sdk_python.hapi.services.transaction_response_pb2 import (
TransactionResponse as TransactionResponseProto,
)
from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery
from hiero_sdk_python.query.transaction_get_receipt_query import (
TransactionGetReceiptQuery,
)
from hiero_sdk_python.query.transaction_record_query import TransactionRecordQuery
from hiero_sdk_python.response_code import ResponseCode
from hiero_sdk_python.transaction.transaction_id import TransactionId
from tests.unit.mock_server import RealRpcError, mock_hedera_servers
pytestmark = pytest.mark.unit
def test_retry_success_before_max_attempts():
"""Test that execution succeeds on the last attempt before max_attempts."""
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(
status=ResponseCode.SUCCESS,
accountID=basic_types_pb2.AccountID(shardNum=0, realmNum=0, accountNum=1234),
),
)
)
# First server gives 2 BUSY responses then OK on the 3rd try
response_sequences = [[busy_response, busy_response, ok_response, receipt_response]]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
# Configure client to allow 3 attempts - should succeed on the last try
client.max_attempts = 3
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
try:
receipt = transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
assert receipt.status == ResponseCode.SUCCESS
def test_retry_failure_after_max_attempts():
"""Test that execution fails after max_attempts with retriable errors."""
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
response_sequences = [[busy_response, busy_response]]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
client.max_attempts = 2
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
# Should raise an exception after max attempts
with pytest.raises(MaxAttemptsError) as excinfo:
transaction.execute(client)
# Verify the exception contains information about retry exhaustion
error_message = str(excinfo.value)
assert "Exceeded maximum attempts" in error_message
assert "failed precheck with status: BUSY" in error_message
def test_node_switching_after_single_grpc_error():
"""Test that execution switches nodes after receiving a non-retriable error."""
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
error = RealRpcError(grpc.StatusCode.UNAVAILABLE, "Test error")
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
# First node gives error, second node gives OK, third node gives error
response_sequences = [
[error],
[ok_response, receipt_response],
[error],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
try:
transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
# Verify we're now on the second node
assert transaction.node_account_ids[transaction._node_account_ids_index] == AccountId(0, 0, 4), (
"Client should have switched to the second node"
)
def test_node_switching_after_multiple_grpc_errors():
"""Test that execution switches nodes after receiving multiple non-retriable errors."""
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
error_response = RealRpcError(grpc.StatusCode.UNAVAILABLE, "Test error")
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
response_sequences = [
[error_response, error_response],
[error_response, error_response],
[ok_response, receipt_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
try:
receipt = transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
# Verify we're now on the third node
assert transaction.node_account_ids[transaction._node_account_ids_index] == AccountId(0, 0, 5), (
"Client should have switched to the third node"
)
assert receipt.status == ResponseCode.SUCCESS
def test_transaction_with_expired_error_not_retried():
"""Test that an expired error is not retried."""
error_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.TRANSACTION_EXPIRED)
response_sequences = [[error_response]]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
with pytest.raises(PrecheckError) as exc_info:
transaction.execute(client)
assert str(error_response.nodeTransactionPrecheckCode) in str(exc_info.value)
def test_transaction_with_fatal_error_not_retried():
"""Test that a fatal error is not retried."""
error_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.INVALID_TRANSACTION_BODY)
response_sequences = [[error_response]]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
with pytest.raises(PrecheckError) as exc_info:
transaction.execute(client)
assert str(error_response.nodeTransactionPrecheckCode) in str(exc_info.value)
def test_exponential_backoff_retry():
"""Test that the retry mechanism uses exponential backoff."""
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
# Create several BUSY responses to force multiple retries
response_sequences = [[busy_response, busy_response, busy_response, ok_response, receipt_response]]
# Use a mock for time.sleep to capture the delay values
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,
):
client.max_attempts = 5
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
try:
transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
# Check that time.sleep was called the expected number of times (3 retries)
assert mock_sleep.call_count == 3, f"Expected 3 sleep calls, got {mock_sleep.call_count}"
# Verify exponential backoff by checking sleep durations are increasing
sleep_args = [call_args[0][0] for call_args in mock_sleep.call_args_list]
# Verify each subsequent delay is double than the previous
for i in range(1, len(sleep_args)):
assert abs(sleep_args[i] - sleep_args[i - 1] * 2) < 0.1, f"Expected doubling delays, but got {sleep_args}"
def test_retriable_error_does_not_switch_node():
"""Test that a retriable error does not switch nodes."""
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
response_sequences = [[busy_response, ok_response, receipt_response]]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
)
try:
transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
assert client.network.current_node._account_id == AccountId(0, 0, 3), (
"Client should not switch node on retriable errors"
)
def test_topic_create_transaction_retry_on_busy():
"""Test that TopicCreateTransaction retries on BUSY response."""
# First response is BUSY, second is OK
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(
status=ResponseCode.SUCCESS,
topicID=basic_types_pb2.TopicID(shardNum=0, realmNum=0, topicNum=456),
),
)
)
response_sequences = [
[busy_response, ok_response, receipt_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,
):
client.max_attempts = 3
tx = TopicCreateTransaction().set_memo("Test with retry").set_admin_key(PrivateKey.generate().public_key())
try:
receipt = tx.execute(client)
except Exception as e:
pytest.fail(f"Should not raise exception, but raised: {e}")
# Verify transaction succeeded after retry
assert receipt.status == ResponseCode.SUCCESS
assert receipt.topic_id.num == 456
# Verify we slept once for the retry
assert mock_sleep.call_count == 1, "Should have retried once"
# Verify we didn't switch nodes (BUSY is retriable without node switch)
assert client.network.current_node._account_id == AccountId(0, 0, 3), "Should not have switched nodes on BUSY"
def test_topic_create_transaction_fails_on_nonretriable_error():
"""Test that TopicCreateTransaction fails on non-retriable error."""
# Create a response with a non-retriable error
error_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.INVALID_TRANSACTION_BODY)
response_sequences = [
[error_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
tx = TopicCreateTransaction().set_memo("Test with error").set_admin_key(PrivateKey.generate().public_key())
with pytest.raises(PrecheckError, match="failed precheck with status: INVALID_TRANSACTION_BODY"):
tx.execute(client)
def test_transaction_node_switching_body_bytes():
"""Test that execution switches nodes after receiving a non-retriable error."""
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
error = RealRpcError(grpc.StatusCode.UNAVAILABLE, "Test error")
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
# First node gives error, second node gives OK, third node gives error
response_sequences = [
[error],
[ok_response, receipt_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
):
# We set the current node to 0
client.network._node_index = 0
client.network.current_node = client.network.nodes[0]
transaction = (
AccountCreateTransaction()
.set_key_without_alias(PrivateKey.generate().public_key())
.set_initial_balance(100_000_000)
.freeze_with(client)
.sign(client.operator_private_key)
)
for node in client.network.nodes:
assert transaction._transaction_body_bytes.get(node._account_id) is not None, (
"Transaction body bytes should be set for all nodes"
)
sig_map = transaction._signature_map.get(transaction._transaction_body_bytes[node._account_id])
assert sig_map is not None, "Signature map should be set for all nodes"
assert len(sig_map.sigPair) == 1, "Signature map should have one signature"
assert sig_map.sigPair[0].pubKeyPrefix == client.operator_private_key.public_key().to_bytes_raw(), (
"Signature should be for the operator"
)
try:
transaction.execute(client)
except (Exception, grpc.RpcError) as e:
pytest.fail(f"Transaction execution should not raise an exception, but raised: {e}")
# Verify we're now on the second node
assert transaction.node_account_ids[transaction._node_account_ids_index] == AccountId(0, 0, 4), (
"Client should have switched to the second node"
)
def test_query_retry_on_busy():
"""
Test query retry behavior when receiving BUSY response.
This test simulates two scenarios:
1. First node returns BUSY response
2. Second node returns OK response with the balance
Verifies that the query successfully retries on a different node after receiving BUSY,
that the balance is returned correctly and that time.sleep was called once for the retry delay.
"""
# Create a BUSY response to simulate a node being temporarily unavailable
# This response indicates the node cannot process the request at this time
busy_response = response_pb2.Response(
cryptogetAccountBalance=crypto_get_account_balance_pb2.CryptoGetAccountBalanceResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.BUSY)
)
)
# Create a successful OK response with a balance of 1 Hbar
# This simulates a successful account balance query response
ok_response = response_pb2.Response(
cryptogetAccountBalance=crypto_get_account_balance_pb2.CryptoGetAccountBalanceResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
balance=100000000, # Balance in tinybars
)
)
# Set up response sequences for multiple nodes:
# First node returns BUSY, forcing a retry
# Second node returns OK with the balance
response_sequences = [
[busy_response],
[ok_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,
):
# We set the current node to the first node so we are sure it will return BUSY response
client.network._node_index = 0
client.network.current_node = client.network.nodes[0]
query = CryptoGetAccountBalanceQuery()
query.set_account_id(AccountId(0, 0, 1234))
balance = query.execute(client)
# Verify we slept once for the retry
assert mock_sleep.call_count == 1, "Should have retried once"
assert balance.hbars.to_tinybars() == 100000000
# Verify we switched to the second node
assert query._node_account_ids_index == 1
assert query.node_account_ids[query._node_account_ids_index] == AccountId(0, 0, 4), (
"Client should have switched to the second node"
)
# Set max_attempts
def test_set_max_attempts_with_valid_param():
"""Test that set_max_attempts for the transaction and query."""
# Transaction
transaction = AccountCreateTransaction()
assert transaction._max_attempts is None
transaction.set_max_attempts(10)
assert transaction._max_attempts == 10
# Query
query = CryptoGetAccountBalanceQuery()
assert query._max_attempts is None
query.set_max_attempts(10)
assert query._max_attempts == 10
@pytest.mark.parametrize("invalid_max_attempts", ["1", 0.2, True, False, object(), {}])
def test_set_max_attempts_with_invalid_type(invalid_max_attempts):
"""Test that set_max_attempts raises TypeError for non-int values."""
with pytest.raises(
TypeError,
match=f"max_attempts must be of type int, got {type(invalid_max_attempts).__name__}",
):
transaction = AccountCreateTransaction()
transaction.set_max_attempts(invalid_max_attempts)
with pytest.raises(
TypeError,
match=f"max_attempts must be of type int, got {type(invalid_max_attempts).__name__}",
):
query = CryptoGetAccountBalanceQuery()
query.set_max_attempts(invalid_max_attempts)
@pytest.mark.parametrize("invalid_max_attempts", [0, -10])
def test_set_max_attempts_with_invalid_value(invalid_max_attempts):
"""Test that set_max_attempts raises ValueError for non-positive values."""
with pytest.raises(ValueError, match="max_attempts must be greater than 0"):
transaction = AccountCreateTransaction()
transaction.set_max_attempts(invalid_max_attempts)
with pytest.raises(ValueError, match="max_attempts must be greater than 0"):
query = CryptoGetAccountBalanceQuery()
query.set_max_attempts(invalid_max_attempts)
# Set grpc_deadline
def test_set_grpc_deadline_with_valid_param():
"""Test that set_grpc_deadline updates default value of _grpc_deadline."""
# Transaction
transaction = AccountCreateTransaction()
assert transaction._grpc_deadline is None
returned = transaction.set_grpc_deadline(20)
assert transaction._grpc_deadline == 20
assert returned is transaction
# Query
query = CryptoGetAccountBalanceQuery()
assert query._grpc_deadline is None
returned = query.set_grpc_deadline(20)
assert query._grpc_deadline == 20
assert returned is query
@pytest.mark.parametrize("invalid_grpc_deadline", ["1", True, False, object(), {}])
def test_set_grpc_deadline_with_invalid_type(invalid_grpc_deadline):
"""Test that set_grpc_deadline raises TypeError for invalid types."""
with pytest.raises(
TypeError,
match=f"grpc_deadline must be of type Union\\[int, float\\], got {type(invalid_grpc_deadline).__name__}",
):
# Transaction
transaction = AccountCreateTransaction()
transaction.set_grpc_deadline(invalid_grpc_deadline)
with pytest.raises(
TypeError,
match=f"grpc_deadline must be of type Union\\[int, float\\], got {type(invalid_grpc_deadline).__name__}",
):
query = CryptoGetAccountBalanceQuery()
query.set_grpc_deadline(invalid_grpc_deadline)
@pytest.mark.parametrize("invalid_grpc_deadline", [0, -10, 0.0, -2.3, float("inf"), float("nan")])
def test_set_grpc_deadline_with_invalid_value(invalid_grpc_deadline):
"""Test that set_grpc_deadline raises ValueError for non-positive values."""
with pytest.raises(ValueError, match="grpc_deadline must be a finite value greater than 0"):
# Transaction
transaction = AccountCreateTransaction()
transaction.set_grpc_deadline(invalid_grpc_deadline)
with pytest.raises(ValueError, match="grpc_deadline must be a finite value greater than 0"):
# Query
query = CryptoGetAccountBalanceQuery()
query.set_grpc_deadline(invalid_grpc_deadline)
def test_warning_when_request_timeout_less_than_grpc_deadline():
"""Warn when request_timeout is less than grpc_deadline."""
tx = AccountCreateTransaction()
tx.set_grpc_deadline(10)
with pytest.warns(UserWarning):
tx.set_request_timeout(5)
# Set request_timeout
def test_set_request_timeout_with_valid_param():
"""Test that set_request_timeout updates default value of _request_timeout."""
# Transaction
transaction = AccountCreateTransaction()
assert transaction._request_timeout is None
returned = transaction.set_request_timeout(200)
assert transaction._request_timeout == 200
assert returned is transaction
# Query
query = CryptoGetAccountBalanceQuery()
assert query._request_timeout is None
returned = query.set_request_timeout(200)
assert query._request_timeout == 200
assert returned is query
@pytest.mark.parametrize("invalid_request_timeout", ["1", True, False, object(), {}])
def test_set_request_timeout_with_invalid_type(invalid_request_timeout):
"""Test that set_request_timeout raises TypeError for invalid types."""
with pytest.raises(
TypeError,
match=f"request_timeout must be of type Union\\[int, float\\], got {type(invalid_request_timeout).__name__}",
):
# Transaction
transaction = AccountCreateTransaction()
transaction.set_request_timeout(invalid_request_timeout)
with pytest.raises(
TypeError,
match=f"request_timeout must be of type Union\\[int, float\\], got {type(invalid_request_timeout).__name__}",
):
# Query
query = CryptoGetAccountBalanceQuery()
query.set_request_timeout(invalid_request_timeout)
@pytest.mark.parametrize("invalid_request_timeout", [0, -10, 0.0, -2.3, float("inf"), float("nan")])
def test_set_request_timeout_with_invalid_value(invalid_request_timeout):
"""Test that set_request_timeout raises ValueError for non-positive values."""
with pytest.raises(ValueError, match="request_timeout must be a finite value greater than 0"):
transaction = AccountCreateTransaction()
transaction.set_request_timeout(invalid_request_timeout)
with pytest.raises(ValueError, match="request_timeout must be a finite value greater than 0"):
query = CryptoGetAccountBalanceQuery()
query.set_request_timeout(invalid_request_timeout)
def test_warning_when_grpc_deadline_exceeds_request_timeout():
"""Warn when grpc_deadline is greater than request_timeout."""
tx = AccountCreateTransaction()
tx.set_request_timeout(5)
with pytest.warns(UserWarning):
tx.set_grpc_deadline(10)
# Test is transaction_recepit_or_record
def test_is_transaction_receipt_or_record_request():
"""Detect receipt and record query requests correctly."""
receipt_query = query_pb2.Query(transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptQuery())
assert _is_transaction_receipt_or_record_request(receipt_query) is True
assert _is_transaction_receipt_or_record_request(object()) is False
# Set min_backoff
def test_set_min_backoff_with_valid_param():
"""Test that set_min_backoff updates default value of _min_backoff."""
# Transaction
transaction = AccountCreateTransaction()
assert transaction._min_backoff is None
returned = transaction.set_min_backoff(2)
assert transaction._min_backoff == 2
assert returned is transaction
# Query
query = CryptoGetAccountBalanceQuery()
assert query._min_backoff is None
returned = query.set_min_backoff(2)
assert query._min_backoff == 2
assert returned is query
@pytest.mark.parametrize("invalid_min_backoff", ["1", True, False, object(), {}])
def test_set_min_backoff_with_invalid_type(invalid_min_backoff):
"""Test that set_min_backoff raises TypeError for invalid types."""
with pytest.raises(
TypeError,
match=f"min_backoff must be of type int or float, got {type(invalid_min_backoff).__name__}",
):
# Transaction
transaction = AccountCreateTransaction()
transaction.set_min_backoff(invalid_min_backoff)
with pytest.raises(
TypeError,
match=f"min_backoff must be of type int or float, got {type(invalid_min_backoff).__name__}",
):
query = CryptoGetAccountBalanceQuery()
query.set_min_backoff(invalid_min_backoff)
@pytest.mark.parametrize("invalid_min_backoff", [-1, -10, float("inf"), float("-inf"), float("nan")])
def test_set_min_backoff_with_invalid_value(invalid_min_backoff):
"""Test that set_min_backoff raises ValueError for invalid values."""
with pytest.raises(ValueError, match="min_backoff must be a finite value >= 0"):
transaction = AccountCreateTransaction()
transaction.set_min_backoff(invalid_min_backoff)
with pytest.raises(ValueError, match="min_backoff must be a finite value >= 0"):
query = CryptoGetAccountBalanceQuery()
query.set_min_backoff(invalid_min_backoff)
def test_set_min_backoff_exceeds_max_backoff():
"""Test that set_min_backoff raises ValueError if it exceeds max_backoff."""
with pytest.raises(ValueError, match="min_backoff cannot exceed max_backoff"):
transaction = AccountCreateTransaction()
transaction.set_max_backoff(5)
transaction.set_min_backoff(10)
with pytest.raises(ValueError, match="min_backoff cannot exceed max_backoff"):
query = CryptoGetAccountBalanceQuery()
query.set_max_backoff(5)
query.set_min_backoff(10)
# Set max_backoff
def test_set_max_backoff_with_valid_param():
"""Test that set_max_backoff updates default value of _max_backoff."""
# Transaction
transaction = AccountCreateTransaction()
assert transaction._max_backoff is None
returned = transaction.set_max_backoff(2)
assert transaction._max_backoff == 2
assert returned is transaction
# Query
query = CryptoGetAccountBalanceQuery()
assert query._max_backoff is None
returned = query.set_max_backoff(2)
assert query._max_backoff == 2
assert returned is query
@pytest.mark.parametrize("invalid_max_backoff", ["1", True, False, object(), {}])
def test_set_max_backoff_with_invalid_type(invalid_max_backoff):
"""Test that set_max_backoff raises TypeError for invalid types."""
with pytest.raises(
TypeError,
match=f"max_backoff must be of type int or float, got {type(invalid_max_backoff).__name__}",
):
transaction = AccountCreateTransaction()
transaction.set_max_backoff(invalid_max_backoff)
with pytest.raises(
TypeError,
match=f"max_backoff must be of type int or float, got {type(invalid_max_backoff).__name__}",
):
query = CryptoGetAccountBalanceQuery()
query.set_max_backoff(invalid_max_backoff)
@pytest.mark.parametrize("invalid_max_backoff", [-1, -10, float("inf"), float("-inf"), float("nan")])
def test_set_max_backoff_with_invalid_value(invalid_max_backoff):
"""Test that set_max_backoff raises ValueError for invalid values."""
with pytest.raises(ValueError, match="max_backoff must be a finite value >= 0"):
transaction = AccountCreateTransaction()
transaction.set_max_backoff(invalid_max_backoff)
with pytest.raises(ValueError, match="max_backoff must be a finite value >= 0"):
query = CryptoGetAccountBalanceQuery()
query.set_max_backoff(invalid_max_backoff)
def test_set_max_backoff_less_than_min_backoff():
"""Test that set_max_backoff raises ValueError if it is less than min_backoff."""
with pytest.raises(ValueError, match="max_backoff cannot be less than min_backoff"):
transaction = AccountCreateTransaction()
transaction.set_min_backoff(5)
transaction.set_max_backoff(2)
with pytest.raises(ValueError, match="max_backoff cannot be less than min_backoff"):
query = CryptoGetAccountBalanceQuery()
query.set_min_backoff(5)
query.set_max_backoff(2)
def test_backoff_is_capped_by_max_backoff():
"""Backoff delay must not exceed max_backoff."""
tx = AccountCreateTransaction()
tx.set_min_backoff(2)
tx.set_max_backoff(5)
# attempt=0 min * 2 = 4
assert tx._calculate_backoff(0) == 4
# attempt=1 min * 4 = 8 : capped to 5
assert tx._calculate_backoff(1) == 5
# Resolve config
def test_execution_config_inherits_from_client(mock_client):
"""Test that resolve_execution_config inherits config from client if not set."""
mock_client.max_attempts = 7
mock_client._min_backoff = 1
mock_client._max_backoff = 8
mock_client._grpc_deadline = 9
mock_client._request_timeout = 20
tx = AccountCreateTransaction()
tx.set_node_account_ids([AccountId(0, 0, 3)])
tx._resolve_execution_config(mock_client, None)
assert tx._max_attempts == 7
assert tx._min_backoff == 1
assert tx._max_backoff == 8
assert tx._grpc_deadline == 9
assert tx._request_timeout == 20
def test_executable_overrides_client_config(mock_client):
"""Test the set value override the set config property."""
mock_client.max_attempts = 10
tx = AccountCreateTransaction().set_max_attempts(3)
tx.set_node_account_ids([AccountId(0, 0, 3)])
tx._resolve_execution_config(mock_client, None)
assert tx._max_attempts == 3
def test_no_nodes_raises_exception(mock_client):
"""Test that execution fails if no nodes are available."""
mock_client.network.nodes = []
tx = AccountCreateTransaction().set_key_without_alias(PrivateKey.generate().public_key()).set_initial_balance(1)
with pytest.raises(RuntimeError, match="No nodes available for execution"):
tx._resolve_execution_config(mock_client, None)
def test_set_node_account_ids_overrides_client_nodes(mock_client):
"""Explicit node_account_ids should override client network."""
node = AccountId(0, 0, 999)
tx = AccountCreateTransaction().set_node_account_id(node)
tx._resolve_execution_config(mock_client, None)
assert tx.node_account_ids == [node]
def test_parameter_timeout_overrides_client_default(mock_client):
"""Explicit timeout pass on the executable should override the client default timeout."""
tx = AccountCreateTransaction()
tx.set_node_account_ids([AccountId(0, 0, 3)])
tx._resolve_execution_config(mock_client, 2)
assert tx._request_timeout == 2
def test_set_timeout_overrides_parameter_timeout(mock_client):
"""Explicit timeout set on the tx should override the pass timeout."""
tx = AccountCreateTransaction()
tx.set_request_timeout(5)
tx.set_node_account_ids([AccountId(0, 0, 3)])
tx._resolve_execution_config(mock_client, 2)
assert tx._request_timeout == 5
# Reuest timeout
def test_request_timeout_exceeded_stops_execution():
"""Test that execution stops when request_timeout is exceeded."""
busy_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.BUSY)
response_sequences = [[busy_response]]
def fake_time():
yield 0 # start
yield 5 # attempt 1
while True:
yield 11 # timeout exceeded
time_iter = fake_time()
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep"),
patch("hiero_sdk_python.executable.time.monotonic", side_effect=lambda: next(time_iter)),
patch("hiero_sdk_python.node._Node.is_healthy", return_value=True),
patch(
"hiero_sdk_python.executable._execute_method",
return_value=busy_response,
),
):
client._request_timeout = 10
client.max_attempts = 5
tx = AccountCreateTransaction().set_key_without_alias(PrivateKey.generate().public_key()).set_initial_balance(1)
with pytest.raises(MaxAttemptsError):
tx.execute(client)
@pytest.mark.parametrize(
"error",
[
RealRpcError(grpc.StatusCode.DEADLINE_EXCEEDED, "timeout"),
RealRpcError(grpc.StatusCode.UNAVAILABLE, "unavailable"),
RealRpcError(grpc.StatusCode.RESOURCE_EXHAUSTED, "busy"),
RealRpcError(grpc.StatusCode.INTERNAL, "received rst stream"), # internal with rst stream
Exception("non grpc exception"), # non grpc exception
],
)
def test_should_exponential_returns_true(error):
"""Test should exponential returns true for listed grpc error and non grpc error."""
tx = AccountCreateTransaction()
assert tx._should_retry_exponentially(error) is True
@pytest.mark.parametrize(
"error",
[
RealRpcError(grpc.StatusCode.INVALID_ARGUMENT, "invalid args"),
RealRpcError(grpc.StatusCode.INTERNAL, "internal"), # internal with no rst stream
],
)
def test_should_exponential_returns_false(error):
"""Test should exponential returns false for non-listed grpc error."""
tx = AccountCreateTransaction()
assert tx._should_retry_exponentially(error) is False
@pytest.mark.parametrize(
"error",
[
RealRpcError(grpc.StatusCode.DEADLINE_EXCEEDED, "timeout"),
RealRpcError(grpc.StatusCode.UNAVAILABLE, "unavailable"),
RealRpcError(grpc.StatusCode.RESOURCE_EXHAUSTED, "busy"),
],
)
def test_should_exponential_error_mark_node_unhealty_and_advance(error):
"""Exponential gRPC retry errors advance the node without sleep-based backoff."""
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
response_sequences = [
[error],
[ok_response, receipt_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,
):
tx = AccountCreateTransaction().set_key_without_alias(PrivateKey.generate().public_key()).set_initial_balance(1)
receipt = tx.execute(client)
assert receipt.status == ResponseCode.SUCCESS
# No delay_for_attempt backoff call, Node is mark unhealthy and advance
assert mock_sleep.call_count == 0
# Node must have changed
assert tx._node_account_ids_index == 1
def test_rst_stream_error_marks_node_unhealthy_and_advances_without_backoff():
"""INTERNAL RST_STREAM errors trigger exponential retry by advancing the node without sleep-based backoff."""
error = RealRpcError(grpc.StatusCode.INTERNAL, "received rst stream")
ok_response = TransactionResponseProto(nodeTransactionPrecheckCode=ResponseCode.OK)
receipt_response = response_pb2.Response(
transactionGetReceipt=transaction_get_receipt_pb2.TransactionGetReceiptResponse(
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
receipt=transaction_receipt_pb2.TransactionReceipt(status=ResponseCode.SUCCESS),
)
)
response_sequences = [
[error],
[ok_response, receipt_response],
]
with (
mock_hedera_servers(response_sequences) as client,
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,