-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathlinkstate_test.py
More file actions
1256 lines (1026 loc) · 42.9 KB
/
linkstate_test.py
File metadata and controls
1256 lines (1026 loc) · 42.9 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
# Copyright 2024 Flower Labs GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests all LinkState implemenations have to conform to."""
# pylint: disable=invalid-name, too-many-lines, R0904, R0913
import tempfile
import time
import unittest
from abc import abstractmethod
from datetime import datetime, timezone
from typing import Optional
from unittest.mock import patch
from uuid import UUID
from parameterized import parameterized
from flwr.common import DEFAULT_TTL, ConfigsRecord, Context, Error, RecordSet, now
from flwr.common.constant import SUPERLINK_NODE_ID, Status, SubStatus
from flwr.common.secure_aggregation.crypto.symmetric_encryption import (
generate_key_pairs,
public_key_to_bytes,
)
from flwr.common.serde import message_from_proto, message_to_proto
from flwr.common.typing import RunStatus
# pylint: disable=E0611
from flwr.proto.message_pb2 import Message, Metadata
# pylint: disable=E0611
from flwr.proto.node_pb2 import Node
from flwr.proto.recordset_pb2 import RecordSet as ProtoRecordSet
from flwr.proto.task_pb2 import Task, TaskIns, TaskRes
# pylint: enable=E0611
from flwr.server.superlink.linkstate import (
InMemoryLinkState,
LinkState,
SqliteLinkState,
)
class StateTest(unittest.TestCase):
"""Test all state implementations."""
# This is to True in each child class
__test__ = False
@abstractmethod
def state_factory(self) -> LinkState:
"""Provide state implementation to test."""
raise NotImplementedError()
def test_create_and_get_run(self) -> None:
"""Test if create_run and get_run work correctly."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
# Execute
run = state.get_run(run_id)
# Assert
assert run is not None
assert run.run_id == run_id
assert run.fab_hash == "9f86d08"
assert run.override_config["test_key"] == "test_value"
def test_get_all_run_ids(self) -> None:
"""Test if get_run_ids works correctly."""
# Prepare
state = self.state_factory()
run_id1 = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
run_id2 = state.create_run(
None, None, "fffffff", {"mock_key": "mock_value"}, ConfigsRecord()
)
# Execute
run_ids = state.get_run_ids()
# Assert
assert run_id1 in run_ids
assert run_id2 in run_ids
def test_get_all_run_ids_empty(self) -> None:
"""Test if get_run_ids works correctly when no runs are present."""
# Prepare
state = self.state_factory()
# Execute
run_ids = state.get_run_ids()
# Assert
assert len(run_ids) == 0
def test_get_pending_run_id(self) -> None:
"""Test if get_pending_run_id works correctly."""
# Prepare
state = self.state_factory()
_ = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
run_id2 = state.create_run(
None, None, "fffffff", {"mock_key": "mock_value"}, ConfigsRecord()
)
state.update_run_status(run_id2, RunStatus(Status.STARTING, "", ""))
# Execute
pending_run_id = state.get_pending_run_id()
assert pending_run_id is not None
run_status_dict = state.get_run_status({pending_run_id})
assert run_status_dict[pending_run_id].status == Status.PENDING
# Change state
state.update_run_status(pending_run_id, RunStatus(Status.STARTING, "", ""))
# Attempt get pending run
pending_run_id = state.get_pending_run_id()
assert pending_run_id is None
def test_get_and_update_run_status(self) -> None:
"""Test if get_run_status and update_run_status work correctly."""
# Prepare
state = self.state_factory()
run_id1 = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
run_id2 = state.create_run(
None, None, "fffffff", {"mock_key": "mock_value"}, ConfigsRecord()
)
state.update_run_status(run_id2, RunStatus(Status.STARTING, "", ""))
state.update_run_status(run_id2, RunStatus(Status.RUNNING, "", ""))
# Execute
run_status_dict = state.get_run_status({run_id1, run_id2})
status1 = run_status_dict[run_id1]
status2 = run_status_dict[run_id2]
# Assert
assert status1.status == Status.PENDING
assert status2.status == Status.RUNNING
@parameterized.expand([(0,), (1,), (2,)]) # type: ignore
def test_status_transition_valid(
self, num_transitions_before_finishing: int
) -> None:
"""Test valid run status transactions."""
# Prepare
state = self.state_factory()
run_id = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
# Execute and assert
status = state.get_run_status({run_id})[run_id]
assert status.status == Status.PENDING
if num_transitions_before_finishing > 0:
assert state.update_run_status(run_id, RunStatus(Status.STARTING, "", ""))
status = state.get_run_status({run_id})[run_id]
assert status.status == Status.STARTING
if num_transitions_before_finishing > 1:
assert state.update_run_status(run_id, RunStatus(Status.RUNNING, "", ""))
status = state.get_run_status({run_id})[run_id]
assert status.status == Status.RUNNING
assert state.update_run_status(
run_id, RunStatus(Status.FINISHED, SubStatus.FAILED, "mock failure")
)
status = state.get_run_status({run_id})[run_id]
assert status.status == Status.FINISHED
def test_status_transition_invalid(self) -> None:
"""Test invalid run status transitions."""
# Prepare
state = self.state_factory()
run_id = state.create_run(
None, None, "9f86d08", {"test_key": "test_value"}, ConfigsRecord()
)
run_statuses = [
RunStatus(Status.PENDING, "", ""),
RunStatus(Status.STARTING, "", ""),
RunStatus(Status.PENDING, "", ""),
RunStatus(Status.FINISHED, SubStatus.COMPLETED, ""),
]
# Execute and assert
# Cannot transition from RunStatus.PENDING to RunStatus.PENDING,
# RunStatus.RUNNING, or RunStatus.FINISHED with COMPLETED substatus
for run_status in [s for s in run_statuses if s.status != Status.STARTING]:
assert not state.update_run_status(run_id, run_status)
state.update_run_status(run_id, RunStatus(Status.STARTING, "", ""))
# Cannot transition from RunStatus.STARTING to RunStatus.PENDING,
# RunStatus.STARTING, or RunStatus.FINISHED with COMPLETED substatus
for run_status in [s for s in run_statuses if s.status != Status.RUNNING]:
assert not state.update_run_status(run_id, run_status)
state.update_run_status(run_id, RunStatus(Status.RUNNING, "", ""))
# Cannot transition from RunStatus.RUNNING
# to RunStatus.PENDING, RunStatus.STARTING, or RunStatus.RUNNING
for run_status in [s for s in run_statuses if s.status != Status.FINISHED]:
assert not state.update_run_status(run_id, run_status)
state.update_run_status(
run_id, RunStatus(Status.FINISHED, SubStatus.COMPLETED, "")
)
# Cannot transition to any status from RunStatus.FINISHED
run_statuses += [
RunStatus(Status.FINISHED, SubStatus.FAILED, ""),
RunStatus(Status.FINISHED, SubStatus.STOPPED, ""),
]
for run_status in run_statuses:
assert not state.update_run_status(run_id, run_status)
def test_get_task_ins_empty(self) -> None:
"""Validate that a new state has no TaskIns."""
# Prepare
state = self.state_factory()
# Execute
num_task_ins = state.num_task_ins()
# Assert
assert num_task_ins == 0
def test_get_task_res_empty(self) -> None:
"""Validate that a new state has no TaskRes."""
# Prepare
state = self.state_factory()
# Execute
num_tasks_res = state.num_task_res()
# Assert
assert num_tasks_res == 0
def test_store_task_ins_one(self) -> None:
"""Test store_task_ins."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
assert task_ins.task.created_at < time.time() # pylint: disable=no-member
assert task_ins.task.delivered_at == "" # pylint: disable=no-member
# Execute
state.store_task_ins(task_ins=task_ins)
task_ins_list = state.get_task_ins(node_id=node_id, limit=10)
# Assert
assert len(task_ins_list) == 1
actual_task_ins = task_ins_list[0]
assert actual_task_ins.task_id == task_ins.task_id # pylint: disable=no-member
assert actual_task_ins.HasField("task")
actual_task = actual_task_ins.task
assert actual_task.delivered_at != ""
assert datetime.fromisoformat(actual_task.delivered_at) > datetime(
2020, 1, 1, tzinfo=timezone.utc
)
assert actual_task.ttl > 0
def test_store_task_ins_invalid_node_id(self) -> None:
"""Test store_task_ins with invalid node_id."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
invalid_node_id = 61016 if node_id != 61016 else 61017
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=invalid_node_id, run_id=run_id)
task_ins2 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins2.task.producer.node_id = 61016
# Execute and assert
assert state.store_task_ins(task_ins) is None
assert state.store_task_ins(task_ins2) is None
def test_store_and_delete_tasks(self) -> None:
"""Test delete_tasks."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins_0 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins_1 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins_2 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
# Insert three TaskIns
task_id_0 = state.store_task_ins(task_ins=task_ins_0)
task_id_1 = state.store_task_ins(task_ins=task_ins_1)
task_id_2 = state.store_task_ins(task_ins=task_ins_2)
assert task_id_0
assert task_id_1
assert task_id_2
# Get TaskIns to mark them delivered
_ = state.get_task_ins(node_id=node_id, limit=None)
# Insert one TaskRes and retrive it to mark it as delivered
task_res_0 = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_id_0)],
run_id=run_id,
)
_ = state.store_task_res(task_res=task_res_0)
_ = state.get_task_res(task_ids={task_id_0})
# Insert one TaskRes, but don't retrive it
task_res_1: TaskRes = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_id_1)],
run_id=run_id,
)
_ = state.store_task_res(task_res=task_res_1)
# Situation now:
# - State has three TaskIns, all of them delivered
# - State has two TaskRes, one of the delivered, the other not
assert state.num_task_ins() == 3
assert state.num_task_res() == 2
state.delete_tasks({task_id_0})
assert state.num_task_ins() == 2
assert state.num_task_res() == 1
state.delete_tasks({task_id_1})
assert state.num_task_ins() == 1
assert state.num_task_res() == 0
state.delete_tasks({task_id_2})
assert state.num_task_ins() == 0
assert state.num_task_res() == 0
def test_get_task_ids_from_run_id(self) -> None:
"""Test get_task_ids_from_run_id."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id_0 = state.create_run(None, None, "8g13kl7", {}, ConfigsRecord())
# Insert tasks with the same run_id
task_ins_0 = create_task_ins(consumer_node_id=node_id, run_id=run_id_0)
task_ins_1 = create_task_ins(consumer_node_id=node_id, run_id=run_id_0)
# Insert a task with a different run_id to ensure it does not appear in result
run_id_1 = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins_2 = create_task_ins(consumer_node_id=node_id, run_id=run_id_1)
# Insert three TaskIns
task_id_0 = state.store_task_ins(task_ins=task_ins_0)
task_id_1 = state.store_task_ins(task_ins=task_ins_1)
task_id_2 = state.store_task_ins(task_ins=task_ins_2)
assert task_id_0
assert task_id_1
assert task_id_2
expected_task_ids = {task_id_0, task_id_1}
# Execute
result = state.get_task_ids_from_run_id(run_id_0)
bad_result = state.get_task_ids_from_run_id(15)
self.assertEqual(len(bad_result), 0)
self.assertSetEqual(result, expected_task_ids)
# Init tests
def test_init_state(self) -> None:
"""Test that state is initialized correctly."""
# Execute
state = self.state_factory()
# Assert
assert isinstance(state, LinkState)
def test_task_ins_store_identity_and_retrieve_identity(self) -> None:
"""Store identity TaskIns and retrieve it."""
# Prepare
state: LinkState = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
# Execute
task_ins_uuid = state.store_task_ins(task_ins)
task_ins_list = state.get_task_ins(node_id=node_id, limit=None)
# Assert
assert len(task_ins_list) == 1
retrieved_task_ins = task_ins_list[0]
assert retrieved_task_ins.task_id == str(task_ins_uuid)
def test_task_ins_store_delivered_and_fail_retrieving(self) -> None:
"""Fail retrieving delivered task."""
# Prepare
state: LinkState = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
# Execute
_ = state.store_task_ins(task_ins)
# 1st get: set to delivered
task_ins_list = state.get_task_ins(node_id=node_id, limit=None)
assert len(task_ins_list) == 1
# 2nd get: no TaskIns because it was already delivered before
task_ins_list = state.get_task_ins(2, limit=None)
# Assert
assert len(task_ins_list) == 0
def test_get_task_ins_limit_throws_for_limit_zero(self) -> None:
"""Fail call with limit=0."""
# Prepare
state: LinkState = self.state_factory()
# Execute & Assert
with self.assertRaises(AssertionError):
state.get_task_ins(node_id=2, limit=0)
def test_task_ins_store_invalid_run_id_and_fail(self) -> None:
"""Store TaskIns with invalid run_id and fail."""
# Prepare
state: LinkState = self.state_factory()
task_ins = create_task_ins(consumer_node_id=0, run_id=61016)
# Execute
task_id = state.store_task_ins(task_ins)
# Assert
assert task_id is None
# TaskRes tests
def test_task_res_store_and_retrieve_by_task_ins_id(self) -> None:
"""Store TaskRes retrieve it by task_ins_id."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(1e3)
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins_id = state.store_task_ins(task_ins)
task_res = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id)],
run_id=run_id,
)
# Execute
task_res_uuid = state.store_task_res(task_res)
assert task_ins_id
task_res_list = state.get_task_res(task_ids={task_ins_id})
# Assert
retrieved_task_res = task_res_list[0]
assert retrieved_task_res.task_id == str(task_res_uuid)
def test_node_ids_initial_state(self) -> None:
"""Test retrieving all node_ids and empty initial state."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
# Execute
retrieved_node_ids = state.get_nodes(run_id)
# Assert
assert len(retrieved_node_ids) == 0
def test_create_node_and_get_nodes(self) -> None:
"""Test creating a client node."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_ids = []
# Execute
for _ in range(10):
node_ids.append(state.create_node(ping_interval=10))
retrieved_node_ids = state.get_nodes(run_id)
# Assert
for i in retrieved_node_ids:
assert i in node_ids
def test_create_node_public_key(self) -> None:
"""Test creating a client node with public key."""
# Prepare
state: LinkState = self.state_factory()
public_key = b"mock"
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
# Execute
node_id = state.create_node(ping_interval=10)
state.set_node_public_key(node_id, public_key)
retrieved_node_ids = state.get_nodes(run_id)
retrieved_node_id = state.get_node_id(public_key)
# Assert
assert len(retrieved_node_ids) == 1
assert retrieved_node_id == node_id
def test_create_node_public_key_twice(self) -> None:
"""Test creating a client node with same public key twice."""
# Prepare
state: LinkState = self.state_factory()
public_key = b"mock"
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(ping_interval=10)
state.set_node_public_key(node_id, public_key)
# Execute
new_node_id = state.create_node(ping_interval=10)
try:
state.set_node_public_key(new_node_id, public_key)
except ValueError:
state.delete_node(new_node_id)
else:
raise AssertionError("Should have raised ValueError")
retrieved_node_ids = state.get_nodes(run_id)
retrieved_node_id = state.get_node_id(public_key)
# Assert
assert len(retrieved_node_ids) == 1
assert retrieved_node_id == node_id
# Assert node_ids and public_key_to_node_id are synced
if isinstance(state, InMemoryLinkState):
assert len(state.node_ids) == 1
assert len(state.public_key_to_node_id) == 1
def test_delete_node(self) -> None:
"""Test deleting a client node."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(ping_interval=10)
# Execute
state.delete_node(node_id)
retrieved_node_ids = state.get_nodes(run_id)
# Assert
assert len(retrieved_node_ids) == 0
def test_delete_node_public_key(self) -> None:
"""Test deleting a client node with public key."""
# Prepare
state: LinkState = self.state_factory()
public_key = b"mock"
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(ping_interval=10)
state.set_node_public_key(node_id, public_key)
# Execute
state.delete_node(node_id)
retrieved_node_ids = state.get_nodes(run_id)
retrieved_node_id = state.get_node_id(public_key)
# Assert
assert len(retrieved_node_ids) == 0
assert retrieved_node_id is None
def test_get_node_id_wrong_public_key(self) -> None:
"""Test retrieving a client node with wrong public key."""
# Prepare
state: LinkState = self.state_factory()
public_key = b"mock"
wrong_public_key = b"mock_mock"
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
# Execute
node_id = state.create_node(ping_interval=10)
state.set_node_public_key(node_id, public_key)
retrieved_node_ids = state.get_nodes(run_id)
retrieved_node_id = state.get_node_id(wrong_public_key)
# Assert
assert len(retrieved_node_ids) == 1
assert retrieved_node_id is None
def test_get_nodes_invalid_run_id(self) -> None:
"""Test retrieving all node_ids with invalid run_id."""
# Prepare
state: LinkState = self.state_factory()
state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
invalid_run_id = 61016
state.create_node(ping_interval=10)
# Execute
retrieved_node_ids = state.get_nodes(invalid_run_id)
# Assert
assert len(retrieved_node_ids) == 0
def test_num_task_ins(self) -> None:
"""Test if num_tasks returns correct number of not delivered task_ins."""
# Prepare
state: LinkState = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_0 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_1 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
# Store two tasks
state.store_task_ins(task_0)
state.store_task_ins(task_1)
# Execute
num = state.num_task_ins()
# Assert
assert num == 2
def test_num_task_res(self) -> None:
"""Test if num_tasks returns correct number of not delivered task_res."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(1e3)
task_ins_0 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins_1 = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins_id_0 = state.store_task_ins(task_ins_0)
task_ins_id_1 = state.store_task_ins(task_ins_1)
task_0 = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id_0)],
run_id=run_id,
)
task_1 = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id_1)],
run_id=run_id,
)
# Store two tasks
state.store_task_res(task_0)
state.store_task_res(task_1)
# Execute
num = state.num_task_res()
# Assert
assert num == 2
def test_clear_supernode_auth_keys_and_credentials(self) -> None:
"""Test clear_supernode_auth_keys_and_credentials from linkstate."""
# Prepare
state: LinkState = self.state_factory()
key_pairs = [generate_key_pairs() for _ in range(3)]
public_keys = {public_key_to_bytes(pair[1]) for pair in key_pairs}
# Execute (store)
state.store_node_public_keys(public_keys)
# Execute (clear)
state.clear_supernode_auth_keys()
node_public_keys = state.get_node_public_keys()
# Assert
assert node_public_keys == set()
def test_node_public_keys(self) -> None:
"""Test store_node_public_keys and get_node_public_keys from state."""
# Prepare
state: LinkState = self.state_factory()
key_pairs = [generate_key_pairs() for _ in range(3)]
public_keys = {public_key_to_bytes(pair[1]) for pair in key_pairs}
# Execute
state.store_node_public_keys(public_keys)
node_public_keys = state.get_node_public_keys()
# Assert
assert node_public_keys == public_keys
def test_node_public_key(self) -> None:
"""Test store_node_public_key and get_node_public_keys from state."""
# Prepare
state: LinkState = self.state_factory()
key_pairs = [generate_key_pairs() for _ in range(3)]
public_keys = {public_key_to_bytes(pair[1]) for pair in key_pairs}
# Execute
for public_key in public_keys:
state.store_node_public_key(public_key)
node_public_keys = state.get_node_public_keys()
# Assert
assert node_public_keys == public_keys
def test_acknowledge_ping(self) -> None:
"""Test if acknowledge_ping works and if get_nodes return online nodes."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_ids = [state.create_node(ping_interval=10) for _ in range(100)]
for node_id in node_ids[:70]:
state.acknowledge_ping(node_id, ping_interval=30)
for node_id in node_ids[70:]:
state.acknowledge_ping(node_id, ping_interval=90)
# Execute
current_time = time.time()
with patch("time.time", side_effect=lambda: current_time + 50):
actual_node_ids = state.get_nodes(run_id)
# Assert
self.assertSetEqual(actual_node_ids, set(node_ids[70:]))
def test_acknowledge_ping_failed(self) -> None:
"""Test that acknowledge_ping returns False when the ping fails."""
# Prepare
state: LinkState = self.state_factory()
# Execute
is_successful = state.acknowledge_ping(0, ping_interval=30)
# Assert
assert not is_successful
def test_store_task_res_task_ins_expired(self) -> None:
"""Test behavior of store_task_res when the TaskIns it references is expired."""
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(1e3)
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins.task.created_at = time.time() - task_ins.task.ttl + 0.5
task_ins_id = state.store_task_ins(task_ins)
with patch(
"time.time",
side_effect=lambda: task_ins.task.created_at + task_ins.task.ttl + 0.1,
): # Expired by 0.1 seconds
task = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id)],
run_id=run_id,
)
# Execute
result = state.store_task_res(task)
# Assert
assert result is None
def test_store_task_res_limit_ttl(self) -> None:
"""Test the behavior of store_task_res regarding the TTL limit of TaskRes."""
current_time = time.time()
test_cases = [
(
current_time - 5,
10,
current_time - 2,
6,
True,
), # TaskRes within allowed TTL
(
current_time - 5,
10,
current_time - 2,
15,
False,
), # TaskRes TTL exceeds max allowed TTL
]
for (
task_ins_created_at,
task_ins_ttl,
task_res_created_at,
task_res_ttl,
expected_store_result,
) in test_cases:
# Prepare
state: LinkState = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(1e3)
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins.task.created_at = task_ins_created_at
task_ins.task.ttl = task_ins_ttl
task_ins_id = state.store_task_ins(task_ins)
task_res = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id)],
run_id=run_id,
)
task_res.task.created_at = task_res_created_at
task_res.task.ttl = task_res_ttl
# Execute
res = state.store_task_res(task_res)
# Assert
if expected_store_result:
assert res is not None
else:
assert res is None
def test_get_task_ins_not_return_expired(self) -> None:
"""Test get_task_ins not to return expired tasks."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins.task.created_at = time.time() - 5
task_ins.task.ttl = 5.0
# Execute
state.store_task_ins(task_ins=task_ins)
# Assert
with patch("time.time", side_effect=lambda: task_ins.task.created_at + 6.1):
task_ins_list = state.get_task_ins(node_id=2, limit=None)
assert len(task_ins_list) == 0
def test_get_task_res_expired_task_ins(self) -> None:
"""Test get_task_res to return error TaskRes if its TaskIns has expired."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins.task.created_at = time.time() - 5
task_ins.task.ttl = 5.1
task_id = state.store_task_ins(task_ins=task_ins)
task_res = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_id)],
run_id=run_id,
)
task_res.task.ttl = 0.1
_ = state.store_task_res(task_res=task_res)
with patch("time.time", side_effect=lambda: task_ins.task.created_at + 6.1):
# Execute
assert task_id is not None
task_res_list = state.get_task_res(task_ids={task_id})
state.delete_tasks({task_id})
# Assert
assert len(task_res_list) == 1
assert task_res_list[0].task.HasField("error")
assert state.num_task_ins() == 0
assert state.num_task_res() == 0
def test_get_task_res_returns_empty_for_missing_taskins(self) -> None:
"""Test that get_task_res returns an empty result when the corresponding TaskIns
does not exist."""
# Prepare
state = self.state_factory()
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
node_id = state.create_node(1e3)
task_ins_id = "5b0a3fc2-edba-4525-a89a-04b83420b7c8"
task_res = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_ins_id)],
run_id=run_id,
)
_ = state.store_task_res(task_res=task_res)
# Execute
task_res_list = state.get_task_res(task_ids={UUID(task_ins_id)})
# Assert
assert len(task_res_list) == 1
assert task_res_list[0].task.HasField("error")
assert state.num_task_ins() == state.num_task_res() == 0
def test_get_task_res_return_if_not_expired(self) -> None:
"""Test get_task_res to return TaskRes if its TaskIns exists and is not
expired."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_ins.task.created_at = time.time() - 5
task_ins.task.ttl = 7.1
task_id = state.store_task_ins(task_ins=task_ins)
task_res = create_task_res(
producer_node_id=node_id,
ancestry=[str(task_id)],
run_id=run_id,
)
task_res.task.ttl = 0.1
_ = state.store_task_res(task_res=task_res)
with patch("time.time", side_effect=lambda: task_ins.task.created_at + 6.1):
# Execute
assert task_id is not None
task_res_list = state.get_task_res(task_ids={task_id})
# Assert
assert len(task_res_list) != 0
def test_store_task_res_fail_if_consumer_producer_id_mismatch(self) -> None:
"""Test store_task_res to fail if there is a mismatch between the
consumer_node_id of taskIns and the producer_node_id of taskRes."""
# Prepare
state = self.state_factory()
node_id = state.create_node(1e3)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
task_ins = create_task_ins(consumer_node_id=node_id, run_id=run_id)
task_id = state.store_task_ins(task_ins=task_ins)
task_res = create_task_res(
# Different than consumer_node_id
producer_node_id=100 if node_id != 100 else 101,
ancestry=[str(task_id)],
run_id=run_id,
)
# Execute
task_res_uuid = state.store_task_res(task_res=task_res)
# Assert
assert task_res_uuid is None
def test_get_set_serverapp_context(self) -> None:
"""Test get and set serverapp context."""
# Prepare
state: LinkState = self.state_factory()
context = Context(
run_id=1,
node_id=SUPERLINK_NODE_ID,
node_config={"mock": "mock"},
state=RecordSet(),
run_config={"test": "test"},
)
run_id = state.create_run(None, None, "9f86d08", {}, ConfigsRecord())
# Execute
init = state.get_serverapp_context(run_id)
state.set_serverapp_context(run_id, context)
retrieved_context = state.get_serverapp_context(run_id)
# Assert
assert init is None
assert retrieved_context == context
def test_set_context_invalid_run_id(self) -> None:
"""Test set_serverapp_context with invalid run_id."""
# Prepare
state: LinkState = self.state_factory()
context = Context(
run_id=1,
node_id=1234,
node_config={"mock": "mock"},
state=RecordSet(),
run_config={"test": "test"},
)
# Execute and assert
with self.assertRaises(ValueError):
state.set_serverapp_context(61016, context) # Invalid run_id
def test_add_serverapp_log_invalid_run_id(self) -> None: