-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_acasclient.py
4868 lines (4356 loc) · 230 KB
/
test_acasclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Tests for `acasclient` package."""
from functools import wraps
import unittest
from acasclient import acasclient
from pathlib import Path
import tempfile
import shutil
import uuid
import json
import operator
import signal
import requests
from typing import List, Dict, Any, Optional
from csv import DictReader
from acasclient.experiment import Experiment
from acasclient.acasclient import (get_entity_value_by_state_type_kind_value_type_kind)
import zipfile
from acasclient.selfile import Generic
# Import project ls thing
from datetime import datetime
# Constants
from tests.project_thing import (
NAME_KEY, IS_RESTRICTED_KEY, STATUS_KEY, START_DATE_KEY, ACTIVE, PROJECT_NAME,
Project
)
EMPTY_MOL = """
Mrv1818 02242010372D
0 0 0 0 0 0 999 V2000
M END
"""
ACAS_NODEAPI_BASE_URL = "http://localhost:3001"
BASIC_EXPERIMENT_LOAD_EXPERIMENT_NAME = "BLAH"
STEREO_CATEGORY="Unknown"
class Timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
# Code to anonymize experiments for testing
def remove_common(object):
# Remove fields which are subject to change and are commmon for groups, states, values classes
object["id"] = None
object["recordedDate"] = None
object["modifiedDate"] = None
object["lsTransaction"] = None
object["version"] = None
return object
def remove_common_group(group):
# Remove fields which are subject to change and are in common for group classes
remove_common(group)
group["codeName"] = None
return group
def remove_common_state(state):
# Remove fields which are subject to change and are in common for all state classes
remove_common(state)
return state
def remove_common_value(value):
# Remove fields which are subject to change and are in common for all value classes
remove_common(value)
value["analysisGroupCode"] = None
value["analysisGroupId"] = None
value["stateId"] = None
# Round numeric values to 5 digits for comparison on different systems where calculations like EC50 might be different
if value['lsType'] == "numericValue":
if value["numericValue"] is not None:
value["numericValue"] = round(value["numericValue"], 5)
# Round uncertainty values as their calculations may vary from system to system
if 'uncertainty' in value and value['uncertainty'] is not None:
value["uncertainty"] = round(value["uncertainty"], 5)
def clean_group(group):
group['key'] = None
remove_common_group(group)
for state in group["lsStates"]:
remove_common_state(state)
for value in state["lsValues"]:
remove_common_value(value)
# If key is curve id it is subject to change so just set it to a standard name for testing
if value['lsKind'] == "curve id":
value["stringValue"] = "FakeCurveIDJustForTesting"
# If there is a "Key" lsKind in the lsValues then we set it on the groups so that we can sort the groups
# later by the key (this is for diffing puroses as part of the test)
elif value['lsKind'] == "Key":
group['key'] = value['numericValue']
state["lsValues"] = sorted(state["lsValues"], key=operator.itemgetter('lsKind','ignored'))
group["lsStates"] = sorted(group["lsStates"], key=operator.itemgetter('lsType','lsKind','ignored'))
return group
def anonymize_experiment_dict(experiment):
# Anonymizes an experiment by removing keys which are subject to change each time the experiment is loaded
# It also sorts the analysis groups by an analysis group value lsKind "Key" if present in the upload file
# This key was added to the Dose Response upload file for these testing purposes
for analysis_group in experiment["analysisGroups"]:
clean_group(analysis_group)
# TODO: Treatment and Subject groups are not included in the diff because it was difficult to get them sorted
# correctly. One way to do this is might be to sort the keys by dose and response values.
analysis_group["treatmentGroups"] = None
# Leaving this code as reference for future when we want to sort the groups by some key
# for tg in analysis_group["treatmentGroups"]:
# clean_group(tg)
# for sg in tg["subjects"]:
# clean_group(sg)
experiment["analysisGroups"] = sorted(experiment["analysisGroups"], key=operator.itemgetter('key'))
return experiment
def create_project_thing(code, name=None, alias=None):
if name is None:
name = code
if alias is None:
alias = name
ls_thing = {
"lsType": "project",
"lsKind": "project",
"recordedBy": "bob",
"recordedDate": 1586877284571,
"lsLabels": [
{
"lsType": "name",
"lsKind": "project name",
"labelText": name,
"ignored": False,
"preferred": True,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"physicallyLabled": False,
"thingType": "project",
"thingKind": "project"
},
{
"lsType": "name",
"lsKind": "project alias",
"labelText": alias,
"ignored": False,
"preferred": False,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"physicallyLabled": False,
"thingType": "project",
"thingKind": "project"
}
],
"lsStates": [
{
"lsType": "metadata",
"lsKind": "project metadata",
"lsValues": [
{
"lsType": "dateValue",
"lsKind": "start date",
"ignored": False,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"dateValue": 1586877284571
}, {
"lsType": "codeValue",
"lsKind": "project status",
"ignored": False,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"codeKind": "status",
"codeType": "project",
"codeOrigin": "ACAS DDICT",
"codeValue": "active"
}, {
"lsType": "codeValue",
"lsKind": "is restricted",
"ignored": False,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"codeKind": "restricted",
"codeType": "project",
"codeOrigin": "ACAS DDICT",
"codeValue": "false"
}
],
"ignored": False,
"recordedDate": 1586877284571,
"recordedBy": "bob"
}
],
"lsTags": [],
"codeName": code
}
return ls_thing
def create_thing_with_blob_value(code):
# Function for creating a thing with a blob value
# Returns a thing, file name and bytes_array for unit testing purposes
# Get a file to load
file_name = 'blob_test.png'
blob_test_path = Path(__file__).resolve().parent\
.joinpath('test_acasclient', file_name)
f = open(blob_test_path, "rb")
bytes_array = f.read()
# Need to save blob value as an int array not bytes
int_array_to_save = [x for x in bytes_array]
f.close()
# Create an Ls thing and add the blob value
# comments should be the file name
code = str(uuid.uuid4())
ls_thing = create_project_thing(code)
blob_value = {
"lsType": "blobValue",
"blobValue": int_array_to_save,
"lsKind": "my file",
"ignored": False,
"recordedDate": 1586877284571,
"recordedBy": "bob",
"comments": file_name
}
ls_thing["lsStates"][0]["lsValues"].append(blob_value)
# Return thing file and bytes array for testing
return ls_thing, file_name, bytes_array
def requires_node_api(func):
"""
Decorator to skip tests if the node API is not available
"""
@wraps(func)
def wrapper(*args, **kwargs):
try:
requests.get(ACAS_NODEAPI_BASE_URL)
except requests.exceptions.ConnectionError:
print('WARNING: ACAS Node API is not available. Skipping tests which require it.')
raise unittest.SkipTest("Node API is not available")
return func(*args, **kwargs)
return wrapper
@requires_node_api
def delete_backdoor_user(username):
""" Deletes a backdoor user created for testing purposes """
r = requests.delete(ACAS_NODEAPI_BASE_URL + "/api/systemTest/deleteTestUser/" + username)
r.raise_for_status()
@requires_node_api
def create_backdoor_user(username, password, acas_user=True, acas_admin=False, creg_user=False, creg_admin=False, project_names=None):
""" Creates a backdoor user for testing purposes """
body = {
"username": username,
"password": password,
"acasUser": acas_user,
"acasAdmin": acas_admin,
"cmpdregUser": creg_user,
"cmpdregAdmin": creg_admin,
"projectNames": project_names or []
}
r = requests.post(ACAS_NODEAPI_BASE_URL + "/api/systemTest/getOrCreateTestUser", json=body)
r.raise_for_status()
return r.json()
@requires_node_api
def get_or_create_global_project():
""" Creates a global project for testing purposes """
r = requests.get(ACAS_NODEAPI_BASE_URL + "/api/systemTest/getOrCreateGlobalProject")
r.raise_for_status()
output = r.json()
return output["messages"]
def delete_all_lots_and_experiments(self):
""" Deletes all lots and experiments """
lots = self.client.get_all_lots()
if len(lots) > 0:
self.delete_all_experiments()
self.delete_all_cmpd_reg_bulk_load_files()
# Check lots again
lots = self.client.get_all_lots()
if len(lots) > 0:
# Delete any remaining lots not from bulk loads
for lot in lots:
self.client.delete_lot(lot['lotCorpName'])
def requires_basic_cmpd_reg_load(func):
"""
Decorator to load the basic cmpdreg data if it is not already loaded
"""
@wraps(func)
def wrapper(self):
if self.client.get_meta_lot('CMPD-0000001-001') is None or self.client.get_meta_lot('CMPD-0000002-001') is None:
# Delete everything to be safe
delete_all_lots_and_experiments(self)
response = self.basic_cmpd_reg_load()
# Verify they were loaded
self.assertIn('New compounds: 2', response['summary'])
if self.client.get_meta_lot('CMPD-0000001-001') is None or self.client.get_meta_lot('CMPD-0000002-001') is None:
raise AssertionError(f"Expected compound lots were not found after basic_cmpd_reg_load. Something has gone seriously wrong! Bulk load response: {response}")
return func(self)
return wrapper
def requires_absent_basic_cmpd_reg_load(func):
"""
Decorator to load the basic cmpdreg data if it is not already loaded
"""
@wraps(func)
def wrapper(self):
delete_all_lots_and_experiments(self)
return func(self)
return wrapper
def requires_basic_experiment_load(func):
"""
Decorator to load the basic experiment data if it is not already loaded, returns None as a fallback if the experiment is not loaded
"""
@requires_basic_cmpd_reg_load
@wraps(func)
def wrapper(self):
# Get experiments with the expected experiment name
experiments = self.client.get_experiment_by_name(BASIC_EXPERIMENT_LOAD_EXPERIMENT_NAME)
# If there is one already loaded then thats the one we want.
current_experiment = None
for experiment in experiments:
if experiment['ignored'] == False and experiment['deleted'] == False:
current_experiment = experiment
break
# If we don't have one already loaded, then load it
if current_experiment is None:
self.basic_experiment_load()
experiments = self.client.get_experiment_by_name(BASIC_EXPERIMENT_LOAD_EXPERIMENT_NAME)
# Verify that th eexperiment is loaded and return it
for experiment in experiments:
if experiment['ignored'] == False and experiment['deleted'] == False:
current_experiment = experiment
break
return func(self, current_experiment)
return wrapper
def read_registered_csv(bulk_loader_response: dict) -> List[dict]:
"""
Reads the registered.csv file from the bulk loader response and returns a list of dicts
"""
report_files = bulk_loader_response['report_files']
for report_file in report_files:
if report_file['name'].endswith('registered.csv'):
reader = DictReader(report_file['content'].decode('utf-8').splitlines())
return list(reader)
return []
class BaseAcasClientTest(unittest.TestCase):
""" Base class for ACAS Client tests """
# To run before EVERY test using this class
def setUp(self):
self.tempdir = tempfile.mkdtemp()
# To run after EVERY test using this class
def tearDown(self):
"""Tear down test fixtures, if any."""
shutil.rmtree(self.tempdir)
# To run ONCE before running tests using this class
@classmethod
def setUpClass(self):
"""Set up test fixtures, if any."""
creds = acasclient.get_default_credentials()
self.test_usernames = []
try:
self.client = acasclient.client(creds)
except RuntimeError:
# Create the default user if it doesn't exist
if creds.get('username'):
self.test_usernames.append(creds.get('username'))
create_backdoor_user(creds.get('username'), creds.get('password'), acas_user=True, acas_admin=True, creg_user=True, creg_admin=True)
# Login again
self.client = acasclient.client(creds)
# Ensure Global project is there
projects = self.client.projects()
global_project = [p for p in projects if p.get('name') == 'Global']
if not global_project:
# Create the global project
global_project = get_or_create_global_project()
else:
global_project = global_project[0]
self.global_project_code = global_project["code"]
# Set TestCase - maxDiff to None to allow for a full diff output when comparing large dictionaries
self.maxDiff = None
# To run ONCE after running tests using this class
@classmethod
def tearDownClass(self):
""" Delete all experiments and bulk load files
"""
try:
self.delete_all_experiments(self)
print("Successfully deleted all experiments")
except Exception as e:
print("Error deleting experiments in tear down: " + str(e))
try:
self.delete_all_cmpd_reg_bulk_load_files(self)
print("Successfully deleted all cmpdreg bulk load files")
except Exception as e:
print("Error deleting bulkloaded files in tear down: " + str(e))
try:
self.delete_all_projects(self)
print("Successfully deleted all projects (except Global)")
except Exception as e:
print("Error deleting all projects in tear down: " + str(e))
try:
for username in self.test_usernames:
delete_backdoor_user(username)
finally:
self.client.close()
@requires_node_api
def create_and_connect_backdoor_user(self, username = None, password = None, prefix = "acas-user-", **kwargs):
""" Creates a backdoor user and connects them to the ACAS node API """
if username is None:
username = prefix+str(uuid.uuid4())
if password is None:
password = str(uuid.uuid4())
create_backdoor_user(username = username, password = password, **kwargs)
self.test_usernames.append(username)
user_creds = {
'username': username,
'password': password,
'url': self.client.url
}
user_client = acasclient.client(user_creds)
return user_client
def verify_file_and_content_equal(self, file_path, content):
""" Compare the content to the file contents"""
mode = 'rb' if isinstance(content, bytes) else 'r'
with open(file_path, mode) as f:
self.assertEqual(content, f.read())
# Helper for testing an experiment upload was successful
def experiment_load_test(self, data_file_to_upload, dry_run_mode, expect_failure=False, report_file_to_upload=None, images_file_to_upload=None):
response = self.client.\
experiment_loader(data_file_to_upload, "bob", dry_run_mode, report_file_to_upload, images_file_to_upload)
self.assertIn('results', response)
self.assertIn('htmlSummary', response['results'])
self.assertIn('errorMessages', response)
self.assertIn('hasError', response)
self.assertIn('hasWarning', response)
self.assertIn('transactionId', response)
if response['hasError'] and not expect_failure:
raise ValueError(f"Experiment load failed unexpectedly with errorMessages: {response['errorMessages']}")
if dry_run_mode:
self.assertIsNone(response['transactionId'])
else:
self.assertIsNotNone(response['transactionId'])
self.assertIsNotNone(response['results']['experimentCode'])
experimentCode = response['results']['experimentCode']
experiment_dict = self.client.get_experiment_by_code(experimentCode)
experiment = Experiment(experiment_dict, self.client)
# Make sure the file was moved to the experiment folder by checking the file path
self.assertIn(experimentCode, experiment.source_file)
# Get the experiment source file
# Compare the source file['content'] to the data_file_to_upload content
# If the file['content'] is bytes then read the data_file_to_upload as bytes
# If the file['content'] is string then read the data_file_to_upload as string
source_file = experiment.get_source_file()
self.verify_file_and_content_equal(data_file_to_upload, source_file['content'])
if report_file_to_upload is not None:
report_file = experiment.get_report_file()
# Make sure the file was moved to the experiment folder by checking the file path
self.assertIn(experimentCode, experiment.report_file)
# Verify matching file content
self.verify_file_and_content_equal(report_file_to_upload, report_file['content'])
if images_file_to_upload is not None:
# The images file isn't saved as a file in the experiment, but rather each image file is saved as an analysis group value
# So we need to get the analysis group values and compare them to the images files
# Get the full experiment
experiment_dict = self.client.get_experiment_by_code(experimentCode, full=True)
# Use simple experiment to read the file we uploaded
simple_experiment = Generic()
simple_experiment.loadFile(data_file_to_upload)
# Loop through the simple_experiment._datatype and if the value is "Image File" then get the key of the image file (lsType)
image_file_kinds = [k for k, v in simple_experiment._datatype.items() if v == "Image File"]
image_values_to_match = []
for image_file_kind in image_file_kinds:
image_file_values = simple_experiment.calculated_results_df[image_file_kind]
image_values_to_match.extend(image_file_values)
# Now we verify that each of the imagesToMatch is in the experiment and that we can fetch the image file and it matches what we uploaded
experiment_value_matches = 0
image_zip_reconstruction_matches = 0
with zipfile.ZipFile(images_file_to_upload, 'r') as original_zip_ref:
# We also want to verify we can reconstruct the zip from using experiment.get_images_file()
saved_images_zip = experiment.get_images_file()
with zipfile.ZipFile(saved_images_zip, 'r') as saved_zip_ref:
# First match the experiment images to the zip file and compare the bytes and ls kinds
original_zip_images = [f for f in original_zip_ref.namelist() if f.endswith(".png")]
# Get all analysis group values where there is an lsType "inlineFileValue" using get_entity_value_by_state_type_kind_value_type_kind
analysis_groups = experiment_dict["analysisGroups"]
for ag in analysis_groups:
for image_file_kind in image_file_kinds:
inline_file_value = get_entity_value_by_state_type_kind_value_type_kind(ag, "data", "results", "inlineFileValue", image_file_kind)
if inline_file_value is not None:
file_path = inline_file_value['fileValue']
# Assert that the experiment code name is in the file path to make sure it was uploaded correctly
self.assertIn(experimentCode, file_path)
# Fetch the file from the API
file = self.client.get_file("/dataFiles/{}"
.format(file_path))
# Match the file name to the zip file name by file name and compare the bytes
baseName = Path(file_path).name
# Get the matching zip file
zipFile = [f for f in original_zip_images if f.endswith(baseName)]
if len(zipFile) == 0:
raise AssertionError("Could not find file {} in zip file".format(baseName))
# Read the zipFile bytes
with original_zip_ref.open(zipFile[0]) as f:
zip_bytes = f.read()
self.assertEqual(file['content'], zip_bytes)
experiment_value_matches += 1
# Now verify we can reconstruct the image zip from the experiment and make sure the zip images match the original zip images
saved_zip_images = saved_zip_ref.namelist()
for original_image_to_match in original_zip_images:
for saved_image in saved_zip_images:
if Path(original_image_to_match).name.upper() == saved_image.upper():
# Verify that the bytes match
with original_zip_ref.open(original_image_to_match) as f:
zip_bytes = f.read()
with saved_zip_ref.open(saved_image) as saved_f:
saved_zip_bytes = saved_f.read()
self.assertEqual(zip_bytes, saved_zip_bytes)
image_zip_reconstruction_matches += 1
break
# Here we make sure we match the experiment values to the image values in the upload (which may contain multiple references to the same file)
self.assertEqual(experiment_value_matches, len(image_values_to_match))
# Here we match the unique set of image values as we are constructing a unique set of files in the zip
self.assertEqual(image_zip_reconstruction_matches, len(set(image_values_to_match)))
return response
def delete_all_experiments(self):
""" Deletes all experiments """
# Currently search is the only way to get all protocols
self.basic_experiment_load_code = None
protocols = self.client.protocol_search("*")
for protocol in protocols:
for experiment in protocol["experiments"]:
if experiment["ignored"] == False and experiment["deleted"] == False:
self.client.delete_experiment(experiment["codeName"])
# Verify all experiments are now gone for this protocol
all_protocols = self.client.protocol_search("*")
not_deleted_experiments = []
for protocol in all_protocols:
# Loop through all experiments and make sure they are either deleted or ignored
for experiment in protocol["experiments"]:
if experiment["ignored"] == False and experiment["deleted"] == False:
not_deleted_experiments.append(experiment["codeName"])
if len(not_deleted_experiments) > 0:
raise Exception("Failed to delete all experiments: " + str(not_deleted_experiments))
def delete_all_cmpd_reg_bulk_load_files(self):
""" Deletes all cmpdreg bulk load files in order by id """
files = self.client.\
get_cmpdreg_bulk_load_files()
# sort by id in reverse order to delete most recent first
files.sort(key=lambda x: x['id'], reverse=True)
for file in files:
response = self.client.purge_cmpdreg_bulk_load_file(file['id'])
# Verify all files are now gone
files = self.client.\
get_cmpdreg_bulk_load_files()
if len(files) > 0:
# Get the ids of all the files
ids = [file['id'] for file in files]
# Throw exception not failure
raise ValueError(f"Failed to delete some cmpd reg bulk load files: {ids}")
def delete_all_projects(self):
""" Deletes all projects except Global (PROJ-00000001) """
# Currently search is the only way to get all protocols
projects = self.client.get_ls_things_by_type_and_kind('project', 'project')
projects_to_delete = []
for project in projects:
if project['codeName'] != "PROJ-00000001" and project['deleted'] == False and project['ignored'] == False:
project['deleted'] = True
project['ignored'] = True
projects_to_delete.append(project)
if len(projects_to_delete) > 0:
self.client.update_ls_thing_list(projects_to_delete)
projects = self.client.get_ls_things_by_type_and_kind('project', 'project')
not_deleted_projects = []
for project in projects:
if project['codeName'] != "PROJ-00000001" and project['deleted'] == False and project['ignored'] == False:
not_deleted_projects.append(project['codeName'])
if len(not_deleted_projects) > 0:
raise Exception("Failed to delete all projects: " + str(not_deleted_projects))
def create_basic_project_with_roles(self):
""" Creates a basic project with roles """
project_name = str(uuid.uuid4())
meta_dict = {
NAME_KEY: project_name,
IS_RESTRICTED_KEY: True,
STATUS_KEY: ACTIVE,
START_DATE_KEY: datetime.now()
}
newProject = Project(recorded_by=self.client.username, **meta_dict)
newProject.save(self.client)
# Create a new role to go along with the project
role_kind = {
"typeName": "Project",
"kindName": newProject.code_name
}
self.client.setup_items("rolekinds", [role_kind])
ls_role = {
"lsType": "Project",
"lsKind": newProject.code_name,
"roleName": "User"
}
self.client.setup_items("lsroles", [ls_role])
return newProject
def basic_experiment_load(self):
data_file_to_upload = Path(__file__).resolve()\
.parent.joinpath('test_acasclient', 'uniform-commas-with-quoted-text.csv')
response = self.client.\
experiment_loader(data_file_to_upload, "bob", False)
return response
def basic_cmpd_reg_load(self, project_code = None, file = None):
""" Loads the basic cmpdreg data end result being CMPD-0000001-001 and CMPD-0000002-001 are loaded """
if project_code is None:
project_code = self.global_project_code
if file is None:
file = Path(__file__).resolve().parent\
.joinpath('test_acasclient', 'test_012_register_sdf.sdf')
mappings = [
{
"dbProperty": "Parent Common Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Parent Common Name"
},
{
"dbProperty": "Parent Corp Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Parent Corp Name"
},
{
"dbProperty": "Lot Barcode",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Barcode"
},
{
"dbProperty": "Lot Amount",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Amount"
},
{
"dbProperty": "Lot Amount Units",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Amount Units"
},
{
"dbProperty": "Lot Color",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Appearance"
},
{
"dbProperty": "Lot Synthesis Date",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Date Prepared"
},
{
"dbProperty": "Lot Notebook Page",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Notebook"
},
{
"dbProperty": "Lot Corp Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Corp Name"
},
{
"dbProperty": "Lot Number",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Number"
},
{
"dbProperty": "Lot Purity",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Purity"
},
{
"dbProperty": "Lot Comments",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Register Comment"
},
{
"dbProperty": "Lot Chemist",
"defaultVal": "bob",
"required": True,
"sdfProperty": "Lot Scientist"
},
{
"dbProperty": "Lot Solution Amount",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Solution Amount"
},
{
"dbProperty": "Lot Solution Amount Units",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Solution Amount Units"
},
{
"dbProperty": "Lot Supplier",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Source"
},
{
"dbProperty": "Lot Supplier ID",
"defaultVal": None,
"required": False,
"sdfProperty": "Source ID"
},
{
"dbProperty": "CAS Number",
"defaultVal": None,
"required": False,
"sdfProperty": "CAS"
},
{
"dbProperty": "Project",
"defaultVal": project_code,
"required": True,
"sdfProperty": "Project Code Name"
},
{
"dbProperty": "Parent Common Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Name"
},
{
"dbProperty": "Parent Stereo Category",
"defaultVal": STEREO_CATEGORY,
"required": True,
"sdfProperty": "Parent Stereo Category"
},
{
"dbProperty": "Parent Stereo Comment",
"defaultVal": None,
"required": False,
"sdfProperty": "Parent Stereo Comment"
},
{
"dbProperty": "Lot Is Virtual",
"defaultVal": "False",
"required": False,
"sdfProperty": "Lot Is Virtual"
},
{
"dbProperty": "Lot Supplier Lot",
"defaultVal": None,
"required": False,
"sdfProperty": "Sample ID2"
},
{
"dbProperty": "Lot Salt Abbrev",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Salt Name"
},
{
"dbProperty": "Lot Salt Equivalents",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Salt Equivalents"
},
{
"dbProperty": "Parent Alias",
"defaultVal": None,
"required": False,
"sdfProperty": "Parent Alias"
}
]
response = self.client.register_sdf(file, "bob",
mappings)
return response
def _get_or_create_codetable(self, get_method, create_method, code, name):
"""
Utility function to test creation of simple entities
"""
# Get all
codetables = get_method()
already_exists = code.lower() in [ct['code'].lower() for ct in codetables]
# Return it if it already exists
if already_exists:
result = [ct for ct in codetables if ct['code'].lower() == code.lower()][0]
else:
# Create and expect success
result = create_method(code=code, name=name)
self.assertIsNotNone(result.get('id'))
return result
def _create_dupe_codetable(self, create_method, code, name):
with self.assertRaises(requests.HTTPError) as context:
resp = create_method(code=code, name=name)
self.assertIn('409 Client Error: Conflict', str(context.exception))
def create_restricted_lot(self, project_code):
# Bulk load a compound to the restricted project
response = self.basic_cmpd_reg_load(project_code)
# Assert that the are no errors in the response results level
all_lots = self.client.get_all_lots()
# Sort lots by id and get the latest corp id
# This is because we dont' get the corp id in the response from the bulkload
all_lots = sorted(all_lots, key=lambda lot: lot['id'])
global_project_parent_corp_name = all_lots[0]['parentCorpName']
# Find the lot that was bulk loaded with the same corp name as the global project
restricted_project_lot = [lot for lot in all_lots if lot['parentCorpName'] == global_project_parent_corp_name][-1]
restricted_lot_corp_name = restricted_project_lot["lotCorpName"]
return restricted_lot_corp_name
def check_lot_exists_in_experiment(self, lot_corp_name, experiment_code_name):
experiment = self.client.get_experiment_by_code(experiment_code_name, full = True)
# when experiment is deleted, the analysis groups for the lot are deleted
for analysis_group in experiment["analysisGroups"]:
if analysis_group["deleted"] == True or analysis_group["ignored"] == True:
continue
for state in analysis_group["lsStates"]:
for value in state["lsValues"]:
if value["lsKind"] == "batch code" and value["codeValue"] == lot_corp_name:
return True
return False
class TestAcasclient(BaseAcasClientTest):
"""Tests for `acasclient` package."""
def test_000_creds_from_file(self):
"""Test creds from file."""
file_credentials = Path(__file__).resolve().\
parent.joinpath('test_acasclient',
'test_000_creds_from_file_credentials')
creds = acasclient.creds_from_file(
file_credentials,
'acas')
self.assertIn("username", creds)
self.assertIn("password", creds)
self.assertIn("url", creds)
self.assertEqual(creds['username'], 'bob')
self.assertEqual(creds['password'], 'secret')
creds = acasclient.creds_from_file(file_credentials,
'different')
self.assertIn("username", creds)
self.assertIn("password", creds)
self.assertIn("url", creds)
self.assertEqual(creds['username'], 'differentuser')
self.assertEqual(creds['password'], 'secret')
def test_001_get_default_credentials(self):
"""Test get default credentials."""
acasclient.get_default_credentials()
def test_002_client_initialization(self):
"""Test initializing client."""
creds = acasclient.get_default_credentials()
client = acasclient.client(creds)
client.close()
# Verify bad creds 401 response
bad_creds = acasclient.get_default_credentials()
bad_creds['password'] = 'badpassword'
with self.assertRaises(RuntimeError) as context:
acasclient.client(bad_creds)
self.assertIn('Failed to login. Please check credentials.', str(context.exception))
def test_003_projects(self):
"""Test projects."""
projects = self.client.projects()
self.assertGreater(len(projects), 0)
self.assertIn('active', projects[0])
self.assertIn('code', projects[0])
self.assertIn('id', projects[0])
self.assertIn('isRestricted', projects[0])
self.assertIn('name', projects[0])
def test_004_upload_files(self):
"""Test upload files."""
test_003_upload_file_file = Path(__file__).resolve().parent.\
joinpath('test_acasclient', '1_1_Generic.xlsx')
files = self.client.upload_files([test_003_upload_file_file])
self.assertIn('files', files)
self.assertIn('name', files['files'][0])
self.assertIn('originalName', files['files'][0])
self.assertEqual(files['files'][0]["originalName"], '1_1_Generic.xlsx')
@requires_absent_basic_cmpd_reg_load
def test_005_register_sdf_request(self):
"""Test register sdf request."""
test_012_upload_file_file = Path(__file__).resolve().parent\
.joinpath('test_acasclient', 'test_012_register_sdf.sdf')
files = self.client.upload_files([test_012_upload_file_file])
request = {
"fileName": files['files'][0]["name"],
"userName": "bob",
"mappings": [
{
"dbProperty": "Parent Common Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Name"
},
{
"dbProperty": "Parent Corp Name",
"defaultVal": None,
"required": False,
"sdfProperty": "Parent Corp Name"
},
{
"dbProperty": "Lot Amount",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Amount Prepared"
},
{
"dbProperty": "Lot Amount Units",
"defaultVal": None,
"required": False,
"sdfProperty": "Lot Amount Units"
},