-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_run_class.py
More file actions
1192 lines (1030 loc) · 38.7 KB
/
test_run_class.py
File metadata and controls
1192 lines (1030 loc) · 38.7 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 json
import logging
import os
import pytest
import pytest_mock
import time
import typing
import contextlib
import inspect
import tempfile
import threading
import uuid
import psutil
import pathlib
import concurrent.futures
import random
import datetime
import simvue
from simvue.api.objects import Alert, Metrics
from simvue.eco.api_client import CO2SignalData, CO2SignalResponse
from simvue.exception import SimvueRunError
from simvue.eco.emissions_monitor import TIME_FORMAT, CO2Monitor
import simvue.run as sv_run
import simvue.client as sv_cl
import simvue.sender as sv_send
import simvue.config.user as sv_cfg
from simvue.api.objects import Run as RunObject
if typing.TYPE_CHECKING:
from .conftest import CountingLogHandler
@pytest.mark.run
def test_created_run() -> None:
with sv_run.Run() as run_created:
run_created.init(running=False, retention_period="1 min")
_run = RunObject(identifier=run_created.id)
assert _run.status == "created"
@pytest.mark.run
def test_check_run_initialised_decorator() -> None:
with sv_run.Run(mode="offline") as run:
for method_name, method in inspect.getmembers(run, inspect.ismethod):
if not method.__name__.endswith("init_locked"):
continue
with pytest.raises(RuntimeError) as e:
getattr(run, method_name)()
assert "Simvue Run must be initialised" in str(e.value)
@pytest.mark.run
@pytest.mark.eco
@pytest.mark.online
def test_run_with_emissions_online(speedy_heartbeat, mock_co2_signal, create_plain_run) -> None:
run_created, _ = create_plain_run
run_created._user_config.eco.co2_signal_api_token = "test_token"
run_created.config(enable_emission_metrics=True)
time.sleep(5)
_run = RunObject(identifier=run_created.id)
_metric_names = [item[0] for item in _run.metrics]
client = sv_cl.Client()
for _metric in ["emissions", "energy_consumed"]:
_total_metric_name = f"sustainability.{_metric}.total"
_delta_metric_name = f"sustainability.{_metric}.delta"
assert _total_metric_name in _metric_names
assert _delta_metric_name in _metric_names
_metric_values = client.get_metric_values(
metric_names=[_total_metric_name, _delta_metric_name],
xaxis="time",
output_format="dataframe",
run_ids=[run_created.id],
)
# Check that total = previous total + latest delta
_total_values = _metric_values[_total_metric_name].tolist()
_delta_values = _metric_values[_delta_metric_name].tolist()
assert len(_total_values) > 1
for i in range(1, len(_total_values)):
assert _total_values[i] == _total_values[i - 1] + _delta_values[i]
@pytest.mark.run
@pytest.mark.eco
@pytest.mark.offline
def test_run_with_emissions_offline(speedy_heartbeat, mock_co2_signal, create_plain_run_offline, monkeypatch) -> None:
run_created, _ = create_plain_run_offline
run_created.config(enable_emission_metrics=True)
time.sleep(5)
# Run should continue, but fail to log metrics until sender runs and creates file
id_mapping = sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"])
_run = RunObject(identifier=id_mapping[run_created.id])
_metric_names = [item[0] for item in _run.metrics]
for _metric in ["emissions", "energy_consumed"]:
_total_metric_name = f"sustainability.{_metric}.total"
_delta_metric_name = f"sustainability.{_metric}.delta"
assert _total_metric_name not in _metric_names
assert _delta_metric_name not in _metric_names
# Sender should now have made a local file, and the run should be able to use it to create emissions metrics
time.sleep(5)
id_mapping = sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"])
_run.refresh()
_metric_names = [item[0] for item in _run.metrics]
client = sv_cl.Client()
for _metric in ["emissions", "energy_consumed"]:
_total_metric_name = f"sustainability.{_metric}.total"
_delta_metric_name = f"sustainability.{_metric}.delta"
assert _total_metric_name in _metric_names
assert _delta_metric_name in _metric_names
_metric_values = client.get_metric_values(
metric_names=[_total_metric_name, _delta_metric_name],
xaxis="time",
output_format="dataframe",
run_ids=[id_mapping[run_created.id]],
)
# Check that total = previous total + latest delta
_total_values = _metric_values[_total_metric_name].tolist()
_delta_values = _metric_values[_delta_metric_name].tolist()
assert len(_total_values) > 1
for i in range(1, len(_total_values)):
assert _total_values[i] == _total_values[i - 1] + _delta_values[i]
@pytest.mark.run
@pytest.mark.parametrize(
"timestamp",
(datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f"), None),
ids=("timestamp", "no_timestamp"),
)
@pytest.mark.parametrize("overload_buffer", (True, False), ids=("overload", "normal"))
@pytest.mark.parametrize(
"visibility", ("bad_option", "tenant", "public", ["user01"], None)
)
def test_log_metrics(
overload_buffer: bool,
timestamp: str | None,
mocker: pytest_mock.MockerFixture,
request: pytest.FixtureRequest,
visibility: typing.Literal["public", "tenant"] | list[str] | None,
) -> None:
METRICS = {"a": 10, "b": 1.2}
# Have to create the run outside of fixtures because the resources dispatch
# occurs immediately and is not captured by the handler when using the fixture
run = sv_run.Run()
run.config(suppress_errors=False)
metrics_spy = mocker.spy(Metrics, "new")
system_metrics_spy = mocker.spy(sv_run.Run, "_get_internal_metrics")
if visibility == "bad_option":
with pytest.raises(SimvueRunError, match="visibility") as e:
run.init(
name=f"test_run_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
visibility=visibility,
)
run.config(system_metrics_interval=1)
return
run.init(
name=f"test_run_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
visibility=visibility,
retention_period="1 hour",
)
run.config(system_metrics_interval=1)
# Speed up the read rate for this test
run._dispatcher._max_buffer_size = 10
run._dispatcher._max_read_rate *= 10
if overload_buffer:
for i in range(run._dispatcher._max_buffer_size * 3):
run.log_metrics({key: i for key in METRICS}, timestamp=timestamp)
else:
run.log_metrics(METRICS, timestamp=timestamp)
time.sleep(2.0 if overload_buffer else 1.0)
run.close()
client = sv_cl.Client()
_data = client.get_metric_values(
run_ids=[run._id],
metric_names=list(METRICS.keys()),
xaxis="step",
aggregate=False,
)
with contextlib.suppress(RuntimeError):
client.delete_run(run._id)
assert _data
assert sorted(set(METRICS.keys())) == sorted(set(_data.keys()))
_steps = []
for entry in _data.values():
_steps += [i[0] for i in entry.keys()]
_steps = set(_steps)
assert len(_steps) == (
run._dispatcher._max_buffer_size * 3 if overload_buffer else 1
)
if overload_buffer:
assert metrics_spy.call_count > 2
else:
assert metrics_spy.call_count <= 2
# Check heartbeat has been called at least once (so sysinfo sent)
assert system_metrics_spy.call_count >= 1
@pytest.mark.run
@pytest.mark.offline
def test_log_metrics_offline(create_plain_run_offline: tuple[sv_run.Run, dict]) -> None:
METRICS = {"a": 10, "b": 1.2, "c": 2}
run, _ = create_plain_run_offline
run_name = run._name
run.log_metrics(METRICS)
time.sleep(1)
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
run.close()
client = sv_cl.Client()
_data = client.get_metric_values(
run_ids=[client.get_run_id_from_name(run_name)],
metric_names=list(METRICS.keys()),
xaxis="step",
aggregate=False,
)
assert sorted(set(METRICS.keys())) == sorted(set(_data.keys()))
_steps = []
for entry in _data.values():
_steps += [i[0] for i in entry.keys()]
_steps = set(_steps)
assert len(_steps) == 1
@pytest.mark.run
@pytest.mark.parametrize(
"visibility", ("bad_option", "tenant", "public", ["user01"], None)
)
def test_visibility_online(
request: pytest.FixtureRequest,
visibility: typing.Literal["public", "tenant"] | list[str] | None,
) -> None:
run = sv_run.Run()
run.config(suppress_errors=False)
if visibility == "bad_option":
with pytest.raises(SimvueRunError, match="visibility") as e:
run.init(
name=f"test_visibility_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
visibility=visibility,
)
return
run.init(
name=f"test_visibility_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
visibility=visibility,
retention_period="1 hour",
)
time.sleep(1)
_id = run._id
run.close()
_retrieved_run = RunObject(identifier=_id)
if visibility == "tenant":
assert _retrieved_run.visibility.tenant
elif visibility == "public":
assert _retrieved_run.visibility.public
elif not visibility:
assert not _retrieved_run.visibility.tenant and not _retrieved_run.visibility.public
else:
assert _retrieved_run.visibility.users == visibility
@pytest.mark.run
@pytest.mark.offline
@pytest.mark.parametrize(
"visibility", ("bad_option", "tenant", "public", ["user01"], None)
)
def test_visibility_offline(
request: pytest.FixtureRequest,
monkeypatch,
visibility: typing.Literal["public", "tenant"] | list[str] | None,
) -> None:
with tempfile.TemporaryDirectory() as tempd:
os.environ["SIMVUE_OFFLINE_DIRECTORY"] = tempd
run = sv_run.Run(mode="offline")
run.config(suppress_errors=False)
if visibility == "bad_option":
with pytest.raises(SimvueRunError, match="visibility") as e:
run.init(
name=f"test_visibility_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
visibility=visibility,
)
return
run.init(
name=f"test_visibility_{str(uuid.uuid4()).split('-', 1)[0]}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
visibility=visibility,
retention_period="1 hour",
)
time.sleep(1)
_id = run._id
_id_mapping = sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
run.close()
_retrieved_run = RunObject(identifier=_id_mapping.get(_id))
if visibility == "tenant":
assert _retrieved_run.visibility.tenant
elif visibility == "public":
assert _retrieved_run.visibility.public
elif not visibility:
assert not _retrieved_run.visibility.tenant and not _retrieved_run.visibility.public
else:
assert _retrieved_run.visibility.users == visibility
@pytest.mark.run
def test_log_events_online(create_test_run: tuple[sv_run.Run, dict]) -> None:
EVENT_MSG = "Hello world!"
run, _ = create_test_run
run.log_event(EVENT_MSG)
time.sleep(1.0)
run.close()
client = sv_cl.Client()
event_data = client.get_events(run.id, count_limit=1)
assert event_data[0].get("message", EVENT_MSG)
@pytest.mark.run
@pytest.mark.offline
def test_log_events_offline(create_plain_run_offline: tuple[sv_run.Run, dict]) -> None:
EVENT_MSG = "Hello offline world!"
run, _ = create_plain_run_offline
run_name = run._name
run.log_event(EVENT_MSG)
time.sleep(1)
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
run.close()
client = sv_cl.Client()
event_data = client.get_events(client.get_run_id_from_name(run_name), count_limit=1)
assert event_data[0].get("message", EVENT_MSG)
@pytest.mark.run
@pytest.mark.offline
def test_offline_tags(create_plain_run_offline: tuple[sv_run.Run, dict]) -> None:
run, run_data = create_plain_run_offline
time.sleep(1.0)
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
run.close()
client = sv_cl.Client()
tags = client.get_tags()
# Find tag
run_tags = [tag for tag in tags if tag[1].name == run_data["tags"][-1]]
assert len(run_tags) == 1
client.delete_tag(run_tags[0][0])
@pytest.mark.run
def test_update_metadata_running(create_test_run: tuple[sv_run.Run, dict]) -> None:
METADATA = {"a": 1, "b": 1.2, "c": "word", "d": "new"}
run, _ = create_test_run
# Add an initial set of metadata
run.update_metadata({"a": 10, "b": 1.2, "c": "word"})
# Try updating a second time, check original dict isnt overwritten
run.update_metadata({"d": "new"})
# Try updating an already defined piece of metadata
run.update_metadata({"a": 1})
run.close()
time.sleep(1.0)
client = sv_cl.Client()
run_info = client.get_run(run.id)
for key, value in METADATA.items():
assert run_info.metadata.get(key) == value
@pytest.mark.run
def test_update_metadata_created(create_pending_run: tuple[sv_run.Run, dict]) -> None:
METADATA = {"a": 1, "b": 1.2, "c": "word", "d": "new"}
run, _ = create_pending_run
# Add an initial set of metadata
run.update_metadata({"a": 10, "b": 1.2, "c": "word"})
# Try updating a second time, check original dict isnt overwritten
run.update_metadata({"d": "new"})
# Try updating an already defined piece of metadata
run.update_metadata({"a": 1})
time.sleep(1.0)
client = sv_cl.Client()
run_info = client.get_run(run.id)
for key, value in METADATA.items():
assert run_info.metadata.get(key) == value
@pytest.mark.run
@pytest.mark.offline
def test_update_metadata_offline(
create_plain_run_offline: tuple[sv_run.Run, dict],
) -> None:
METADATA = {"a": 1, "b": 1.2, "c": "word", "d": "new"}
run, _ = create_plain_run_offline
run_name = run._name
# Add an initial set of metadata
run.update_metadata({"a": 10, "b": 1.2, "c": "word"})
# Try updating a second time, check original dict isnt overwritten
run.update_metadata({"d": "new"})
# Try updating an already defined piece of metadata
run.update_metadata({"a": 1})
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
run.close()
time.sleep(1.0)
client = sv_cl.Client()
run_info = client.get_run(client.get_run_id_from_name(run_name))
for key, value in METADATA.items():
assert run_info.metadata.get(key) == value
@pytest.mark.run
@pytest.mark.parametrize("multi_threaded", (True, False), ids=("multi", "single"))
def test_runs_multiple_parallel(
multi_threaded: bool, request: pytest.FixtureRequest
) -> None:
N_RUNS: int = 2
if multi_threaded:
def thread_func(index: int) -> tuple[int, list[dict[str, typing.Any]], str]:
with sv_run.Run() as run:
run.config(suppress_errors=False)
run.init(
name=f"test_runs_multiple_{index + 1}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
)
metrics = []
for _ in range(10):
time.sleep(1)
metric = {f"var_{index + 1}": random.random()}
metrics.append(metric)
run.log_metrics(metric)
return index, metrics, run._id
with concurrent.futures.ThreadPoolExecutor(max_workers=N_RUNS) as executor:
futures = [executor.submit(thread_func, i) for i in range(N_RUNS)]
time.sleep(1)
client = sv_cl.Client()
for future in concurrent.futures.as_completed(futures):
id, metrics, run_id = future.result()
assert metrics
assert client.get_metric_values(
run_ids=[run_id],
metric_names=[f"var_{id + 1}"],
xaxis="step",
output_format="dict",
aggregate=False,
)
with contextlib.suppress(RuntimeError):
client.delete_run(run_id)
else:
with sv_run.Run() as run_1:
with sv_run.Run() as run_2:
run_1.config(suppress_errors=False)
run_1.init(
name="test_runs_multiple_unthreaded_1",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
)
run_2.config(suppress_errors=False)
run_2.init(
name="test_runs_multiple_unthreaded_2",
tags=["simvue_client_unit_tests", "test_multi_run_unthreaded"],
folder="/simvue_unit_testing",
retention_period="1 hour",
)
metrics_1 = []
metrics_2 = []
for _ in range(10):
time.sleep(1)
for index, (metrics, run) in enumerate(
zip((metrics_1, metrics_2), (run_1, run_2))
):
metric = {f"var_{index}": random.random()}
metrics.append(metric)
run.log_metrics(metric)
time.sleep(1)
client = sv_cl.Client()
for i, run_id in enumerate((run_1._id, run_2._id)):
assert metrics
assert client.get_metric_values(
run_ids=[run_id],
metric_names=[f"var_{i}"],
xaxis="step",
output_format="dict",
aggregate=False,
)
with contextlib.suppress(RuntimeError):
client.delete_run(run_1._id)
client.delete_run(run_2._id)
@pytest.mark.run
def test_runs_multiple_series(request: pytest.FixtureRequest) -> None:
N_RUNS: int = 2
metrics = []
run_ids = []
for index in range(N_RUNS):
with sv_run.Run() as run:
run_metrics = []
run.config(suppress_errors=False)
run.init(
name=f"test_runs_multiple_series_{index}",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
folder="/simvue_unit_testing",
retention_period="1 hour",
)
run_ids.append(run._id)
for _ in range(10):
time.sleep(1)
metric = {f"var_{index}": random.random()}
run_metrics.append(metric)
run.log_metrics(metric)
metrics.append(run_metrics)
time.sleep(1)
client = sv_cl.Client()
for i, run_id in enumerate(run_ids):
assert metrics[i]
assert client.get_metric_values(
run_ids=[run_id],
metric_names=[f"var_{i}"],
xaxis="step",
output_format="dict",
aggregate=False,
)
with contextlib.suppress(RuntimeError):
for run_id in run_ids:
client.delete_run(run_id)
@pytest.mark.run
@pytest.mark.parametrize("post_init", (True, False), ids=("pre-init", "post-init"))
def test_suppressed_errors(
setup_logging: "CountingLogHandler", post_init: bool, request: pytest.FixtureRequest
) -> None:
logging.getLogger("simvue").setLevel(logging.DEBUG)
setup_logging.captures = ["Skipping call to"]
with sv_run.Run(mode="offline") as run:
decorated_funcs = [
name
for name, method in inspect.getmembers(run, inspect.ismethod)
if hasattr(method, "__fail_safe")
]
if post_init:
decorated_funcs.remove("init")
run.init(
name="test_suppressed_errors",
folder="/simvue_unit_testing",
tags=[
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
],
retention_period="1 hour",
)
run.config(suppress_errors=True)
run._error("Oh dear this error happened :(")
if run._dispatcher:
assert run._dispatcher.empty
for func in decorated_funcs:
assert not getattr(run, func)()
if post_init:
assert setup_logging.counts[0] == len(decorated_funcs) + 1
else:
assert setup_logging.counts[0] == len(decorated_funcs)
@pytest.mark.run
def test_bad_run_arguments() -> None:
with sv_run.Run() as run:
with pytest.raises(RuntimeError):
run.init("sdas", [34])
@pytest.mark.run
def test_set_folder_details(request: pytest.FixtureRequest) -> None:
with sv_run.Run() as run:
folder_name: str = "/simvue_unit_tests"
description: str = "test description"
tags: list[str] = [
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
]
run.init(folder=folder_name)
run.set_folder_details(tags=tags, description=description)
client = sv_cl.Client()
_folder = client.get_folder(folder_path=folder_name)
assert _folder.tags
assert sorted(_folder.tags) == sorted(tags)
assert _folder.description == description
@pytest.mark.run
@pytest.mark.parametrize(
"valid_mimetype,preserve_path,name,allow_pickle,empty_file,category",
[
(True, False, None, False, False, "input"),
(False, True, None, False, False, "output"),
(False, False, "test_file", False, False, "code"),
(False, False, None, True, False, "input"),
(False, False, None, False, True, "code"),
],
ids=[f"scenario_{i}" for i in range(1, 6)],
)
def test_save_file_online(
create_plain_run: typing.Tuple[sv_run.Run, dict],
valid_mimetype: bool,
preserve_path: bool,
name: str | None,
allow_pickle: bool,
empty_file: bool,
category: typing.Literal["input", "output", "code"],
capfd,
) -> None:
simvue_run, _ = create_plain_run
file_type: str = "text/plain" if valid_mimetype else "text/text"
with tempfile.TemporaryDirectory() as tempd:
with open(
(out_name := pathlib.Path(tempd).joinpath("test_file.txt")),
"w",
) as out_f:
out_f.write("" if empty_file else "test data entry")
if valid_mimetype:
simvue_run.save_file(
out_name,
category=category,
file_type=file_type,
preserve_path=preserve_path,
name=name,
)
else:
with pytest.raises(RuntimeError):
simvue_run.save_file(
out_name,
category=category,
file_type=file_type,
preserve_path=preserve_path,
)
return
variable = capfd.readouterr()
simvue_run.close()
time.sleep(1.0)
os.remove(out_name)
client = sv_cl.Client()
base_name = name or out_name.name
if preserve_path:
out_loc = pathlib.Path(tempd) / out_name.parent
stored_name = out_name.parent / pathlib.Path(base_name)
else:
out_loc = pathlib.Path(tempd)
stored_name = pathlib.Path(base_name)
out_file = out_loc.joinpath(name or out_name.name)
client.get_artifact_as_file(
run_id=simvue_run.id, name=f"{name or stored_name}", output_dir=tempd
)
assert out_loc.joinpath(name or out_name.name).exists()
@pytest.mark.run
@pytest.mark.offline
@pytest.mark.parametrize(
"preserve_path,name,allow_pickle,empty_file,category",
[
(False, None, False, False, "input"),
(True, None, False, False, "output"),
(False, "test_file", False, False, "code"),
(False, None, True, False, "input"),
(False, None, False, True, "code"),
],
ids=[f"scenario_{i}" for i in range(1, 6)],
)
def test_save_file_offline(
create_plain_run_offline: typing.Tuple[sv_run.Run, dict],
preserve_path: bool,
name: str | None,
allow_pickle: bool,
empty_file: bool,
category: typing.Literal["input", "output", "code"],
capfd,
) -> None:
simvue_run, _ = create_plain_run_offline
run_name = simvue_run._name
file_type: str = "text/plain"
with tempfile.TemporaryDirectory() as tempd:
with open(
(out_name := pathlib.Path(tempd).joinpath("test_file.txt")),
"w",
) as out_f:
out_f.write("test data entry")
simvue_run.save_file(
out_name,
category=category,
file_type=file_type,
preserve_path=preserve_path,
name=name,
)
simvue_run.save_file(
out_name,
category=category,
preserve_path=preserve_path,
name=name,
)
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
simvue_run.close()
time.sleep(1.0)
os.remove(out_name)
client = sv_cl.Client()
base_name = name or out_name.name
if preserve_path:
out_loc = pathlib.Path(tempd) / out_name.parent
stored_name = out_name.parent / pathlib.Path(base_name)
else:
out_loc = pathlib.Path(tempd)
stored_name = pathlib.Path(base_name)
out_file = out_loc.joinpath(name or out_name.name)
client.get_artifact_as_file(
run_id=client.get_run_id_from_name(run_name),
name=f"{name or stored_name}",
output_dir=tempd,
)
assert out_loc.joinpath(name or out_name.name).exists()
@pytest.mark.run
def test_update_tags_running(
create_plain_run: typing.Tuple[sv_run.Run, dict],
request: pytest.FixtureRequest,
) -> None:
simvue_run, _ = create_plain_run
tags = [
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
]
simvue_run.set_tags(tags)
time.sleep(1)
client = sv_cl.Client()
run_data = client.get_run(simvue_run._id)
assert sorted(run_data.tags) == sorted(tags)
simvue_run.update_tags(["additional"])
time.sleep(1)
run_data = client.get_run(simvue_run._id)
assert sorted(run_data.tags) == sorted(tags + ["additional"])
@pytest.mark.run
def test_update_tags_created(
create_pending_run: typing.Tuple[sv_run.Run, dict],
request: pytest.FixtureRequest,
) -> None:
simvue_run, _ = create_pending_run
tags = [
"simvue_client_unit_tests",
request.node.name.replace("[", "_").replace("]", "_"),
]
simvue_run.set_tags(tags)
time.sleep(1)
client = sv_cl.Client()
run_data = client.get_run(simvue_run._id)
assert sorted(run_data.tags) == sorted(tags)
simvue_run.update_tags(["additional"])
time.sleep(1)
run_data = client.get_run(simvue_run._id)
assert sorted(run_data.tags) == sorted(tags + ["additional"])
@pytest.mark.offline
@pytest.mark.run
def test_update_tags_offline(
create_plain_run_offline: typing.Tuple[sv_run.Run, dict],
) -> None:
simvue_run, _ = create_plain_run_offline
run_name = simvue_run._name
simvue_run.set_tags(
[
"simvue_client_unit_tests",
]
)
simvue_run.update_tags(["additional"])
sv_send.sender(os.environ["SIMVUE_OFFLINE_DIRECTORY"], 2, 10)
simvue_run.close()
time.sleep(1.0)
client = sv_cl.Client()
run_data = client.get_run(client.get_run_id_from_name(run_name))
time.sleep(1)
run_data = client.get_run(simvue_run._id)
assert sorted(run_data.tags) == sorted(["simvue_client_unit_tests", "additional"])
@pytest.mark.run
@pytest.mark.parametrize("object_type", ("DataFrame", "ndarray"))
def test_save_object(
create_plain_run: typing.Tuple[sv_run.Run, dict], object_type: str
) -> None:
simvue_run, _ = create_plain_run
if object_type == "DataFrame":
try:
from pandas import DataFrame
except ImportError:
pytest.skip("Pandas is not installed")
save_obj = DataFrame({"x": [1, 2, 3, 4], "y": [2, 4, 6, 8]})
elif object_type == "ndarray":
try:
from numpy import array
except ImportError:
pytest.skip("Numpy is not installed")
save_obj = array([1, 2, 3, 4])
simvue_run.save_object(save_obj, "input", f"test_object_{object_type}")
@pytest.mark.run
def test_add_alerts() -> None:
_uuid = f"{uuid.uuid4()}".split("-")[0]
run = sv_run.Run()
run.init(
name="test_add_alerts",
folder="/simvue_unit_tests",
retention_period="1 min",
tags=["test_add_alerts"],
visibility="tenant",
)
_expected_alerts = []
# Create alerts, have them attach to run automatically
_id = run.create_event_alert(
name=f"event_alert_{_uuid}",
pattern="test",
)
_expected_alerts.append(_id)
time.sleep(1)
# Retrieve run, check if alert has been added
_online_run = RunObject(identifier=run._id)
assert _id in _online_run.alerts
# Create another alert and attach to run
_id = run.create_metric_range_alert(
name=f"metric_range_alert_{_uuid}",
metric="test",
range_low=10,
range_high=100,
rule="is inside range",
)
_expected_alerts.append(_id)
time.sleep(1)
# Retrieve run, check both alerts have been added
_online_run.refresh()
assert sorted(_online_run.alerts) == sorted(_expected_alerts)
# Create another alert, do not attach to run
_id = run.create_metric_threshold_alert(
name=f"metric_threshold_alert_{_uuid}",
metric="test",
threshold=10,
rule="is above",
attach_to_run=False,
)
time.sleep(1)
# Retrieve run, check alert has NOT been added
_online_run.refresh()
assert sorted(_online_run.alerts) == sorted(_expected_alerts)
# Try adding all three alerts using add_alerts
_expected_alerts.append(_id)
run.add_alerts(
names=[
f"event_alert_{_uuid}",
f"metric_range_alert_{_uuid}",
f"metric_threshold_alert_{_uuid}",
]
)
time.sleep(1)
# Check that there is no duplication
_online_run.refresh()
assert sorted(_online_run.alerts) == sorted(_expected_alerts)
# Create another run without adding to run
_id = run.create_user_alert(name=f"user_alert_{_uuid}", attach_to_run=False)
time.sleep(1)
# Check alert is not added
_online_run.refresh()
assert sorted(_online_run.alerts) == sorted(_expected_alerts)
# Try adding alerts with IDs, check there is no duplication
_expected_alerts.append(_id)
run.add_alerts(ids=_expected_alerts)
time.sleep(1)
_online_run.refresh()
assert sorted(_online_run.alerts) == sorted(_expected_alerts)
run.close()
client = sv_cl.Client()
client.delete_run(run._id)
for _id in _expected_alerts:
client.delete_alert(_id)
@pytest.mark.run
def test_log_alert() -> None:
_uuid = f"{uuid.uuid4()}".split("-")[0]
run = sv_run.Run()
run.init(
name="test_log_alerts",
folder="/simvue_unit_tests",