Mercurial > hg > orthanc-tests
annotate Tests/Toolbox.py @ 220:7b1c976caa9b Orthanc-1.5.5
fix
author | Sebastien Jodogne <s.jodogne@gmail.com> |
---|---|
date | Mon, 25 Feb 2019 10:57:28 +0100 |
parents | af8e034f4262 |
children | 0f03ee6ffa80 |
rev | line source |
---|---|
0 | 1 #!/usr/bin/python |
2 | |
1 | 3 # Orthanc - A Lightweight, RESTful DICOM Store |
73 | 4 # Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics |
1 | 5 # Department, University Hospital of Liege, Belgium |
195 | 6 # Copyright (C) 2017-2019 Osimis S.A., Belgium |
1 | 7 # |
8 # This program is free software: you can redistribute it and/or | |
9 # modify it under the terms of the GNU General Public License as | |
10 # published by the Free Software Foundation, either version 3 of the | |
11 # License, or (at your option) any later version. | |
12 # | |
13 # This program is distributed in the hope that it will be useful, but | |
14 # WITHOUT ANY WARRANTY; without even the implied warranty of | |
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
16 # General Public License for more details. | |
17 # | |
18 # You should have received a copy of the GNU General Public License | |
19 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
0 | 20 |
21 | |
22 import hashlib | |
23 import httplib2 | |
24 import json | |
4 | 25 import os |
1 | 26 import re |
4 | 27 import signal |
1 | 28 import subprocess |
4 | 29 import threading |
83 | 30 import sys |
0 | 31 import time |
1 | 32 import zipfile |
0 | 33 |
3 | 34 from PIL import Image |
83 | 35 |
36 if (sys.version_info >= (3, 0)): | |
37 from urllib.parse import urlencode | |
38 from io import StringIO | |
39 from io import BytesIO | |
40 | |
41 else: | |
42 from urllib import urlencode | |
43 | |
44 # http://stackoverflow.com/a/1313868/881731 | |
45 try: | |
46 from cStringIO import StringIO | |
47 except: | |
48 from StringIO import StringIO | |
3 | 49 |
0 | 50 |
83 | 51 def _DecodeJson(s): |
52 t = s | |
53 | |
54 if (sys.version_info >= (3, 0)): | |
55 try: | |
56 t = s.decode() | |
57 except: | |
58 pass | |
59 | |
60 try: | |
61 return json.loads(t) | |
62 except: | |
63 return t | |
0 | 64 |
65 | |
13 | 66 def DefineOrthanc(server = 'localhost', |
67 restPort = 8042, | |
1 | 68 username = None, |
69 password = None, | |
70 aet = 'ORTHANC', | |
71 dicomPort = 4242): | |
13 | 72 #m = re.match(r'(http|https)://([^:]+):([^@]+)@([^@]+)', url) |
73 #if m != None: | |
74 # url = m.groups()[0] + '://' + m.groups()[3] | |
75 # username = m.groups()[1] | |
76 # password = m.groups()[2] | |
0 | 77 |
13 | 78 #if not url.endswith('/'): |
79 # url += '/' | |
0 | 80 |
1 | 81 return { |
13 | 82 'Server' : server, |
83 'Url' : 'http://%s:%d/' % (server, restPort), | |
1 | 84 'Username' : username, |
85 'Password' : password, | |
86 'DicomAet' : aet, | |
87 'DicomPort' : dicomPort | |
88 } | |
0 | 89 |
90 | |
91 def _SetupCredentials(orthanc, http): | |
1 | 92 if (orthanc['Username'] != None and |
93 orthanc['Password'] != None): | |
94 http.add_credentials(orthanc['Username'], orthanc['Password']) | |
0 | 95 |
28 | 96 def DoGetRaw(orthanc, uri, data = {}, body = None, headers = {}): |
0 | 97 d = '' |
98 if len(data.keys()) > 0: | |
99 d = '?' + urlencode(data) | |
100 | |
101 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
102 http.follow_redirects = False |
0 | 103 _SetupCredentials(orthanc, http) |
104 | |
1 | 105 resp, content = http.request(orthanc['Url'] + uri + d, 'GET', body = body, |
0 | 106 headers = headers) |
28 | 107 return (resp, content) |
108 | |
109 | |
110 def DoGet(orthanc, uri, data = {}, body = None, headers = {}): | |
111 (resp, content) = DoGetRaw(orthanc, uri, data = data, body = body, headers = headers) | |
112 | |
0 | 113 if not (resp.status in [ 200 ]): |
114 raise Exception(resp.status) | |
115 else: | |
83 | 116 return _DecodeJson(content) |
0 | 117 |
118 def _DoPutOrPost(orthanc, uri, method, data, contentType, headers): | |
119 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
120 http.follow_redirects = False |
0 | 121 _SetupCredentials(orthanc, http) |
122 | |
83 | 123 if isinstance(data, (str, bytearray, bytes)): |
0 | 124 body = data |
125 if len(contentType) != 0: | |
126 headers['content-type'] = contentType | |
127 else: | |
128 body = json.dumps(data) | |
129 headers['content-type'] = 'application/json' | |
130 | |
131 headers['expect'] = '' | |
132 | |
1 | 133 resp, content = http.request(orthanc['Url'] + uri, method, |
0 | 134 body = body, |
135 headers = headers) | |
136 if not (resp.status in [ 200, 302 ]): | |
137 raise Exception(resp.status) | |
138 else: | |
83 | 139 return _DecodeJson(content) |
0 | 140 |
141 def DoDelete(orthanc, uri): | |
142 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
143 http.follow_redirects = False |
0 | 144 _SetupCredentials(orthanc, http) |
145 | |
1 | 146 resp, content = http.request(orthanc['Url'] + uri, 'DELETE') |
0 | 147 if not (resp.status in [ 200 ]): |
148 raise Exception(resp.status) | |
149 else: | |
83 | 150 return _DecodeJson(content) |
0 | 151 |
152 def DoPut(orthanc, uri, data = {}, contentType = ''): | |
10 | 153 return _DoPutOrPost(orthanc, uri, 'PUT', data, contentType, {}) |
0 | 154 |
155 def DoPost(orthanc, uri, data = {}, contentType = '', headers = {}): | |
156 return _DoPutOrPost(orthanc, uri, 'POST', data, contentType, headers) | |
157 | |
13 | 158 def GetDatabasePath(filename): |
159 return os.path.join(os.path.dirname(__file__), '..', 'Database', filename) | |
160 | |
0 | 161 def UploadInstance(orthanc, filename): |
83 | 162 with open(GetDatabasePath(filename), 'rb') as f: |
163 d = f.read() | |
164 | |
0 | 165 return DoPost(orthanc, '/instances', d, 'application/dicom') |
166 | |
167 def UploadFolder(orthanc, path): | |
13 | 168 for i in os.listdir(GetDatabasePath(path)): |
1 | 169 try: |
170 UploadInstance(orthanc, os.path.join(path, i)) | |
171 except: | |
172 pass | |
0 | 173 |
174 def DropOrthanc(orthanc): | |
175 # Reset the Lua callbacks | |
176 DoPost(orthanc, '/tools/execute-script', 'function OnStoredInstance(instanceId, tags, metadata) end', 'application/lua') | |
177 | |
178 DoDelete(orthanc, '/exports') | |
179 | |
180 for s in DoGet(orthanc, '/patients'): | |
181 DoDelete(orthanc, '/patients/%s' % s) | |
182 | |
174 | 183 def InstallLuaScriptFromPath(orthanc, path): |
184 with open(GetDatabasePath(path), 'r') as f: | |
185 InstallLuaScript(orthanc, f.read()) | |
186 | |
187 def InstallLuaScript(orthanc, script): | |
188 DoPost(orthanc, '/tools/execute-script', script, 'application/lua') | |
189 | |
190 def UninstallLuaCallbacks(orthanc): | |
191 DoPost(orthanc, '/tools/execute-script', 'function OnStoredInstance() end', 'application/lua') | |
192 InstallLuaScriptFromPath(orthanc, 'Lua/TransferSyntaxEnable.lua') | |
193 | |
194 | |
0 | 195 def ComputeMD5(data): |
196 m = hashlib.md5() | |
197 m.update(data) | |
198 return m.hexdigest() | |
199 | |
59
84378ada15ab
test_decode_brainix_as_jpeg
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
44
diff
changeset
|
200 def GetImage(orthanc, uri, headers = {}): |
0 | 201 # http://www.pythonware.com/library/pil/handbook/introduction.htm |
59
84378ada15ab
test_decode_brainix_as_jpeg
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
44
diff
changeset
|
202 data = DoGet(orthanc, uri, headers = headers) |
83 | 203 if (sys.version_info >= (3, 0)): |
204 return Image.open(BytesIO(data)) | |
205 else: | |
206 return Image.open(StringIO(data)) | |
0 | 207 |
208 def GetArchive(orthanc, uri): | |
209 # http://stackoverflow.com/a/1313868/881731 | |
210 s = DoGet(orthanc, uri) | |
83 | 211 |
212 if (sys.version_info >= (3, 0)): | |
213 return zipfile.ZipFile(BytesIO(s), "r") | |
214 else: | |
215 return zipfile.ZipFile(StringIO(s), "r") | |
0 | 216 |
192 | 217 def PostArchive(orthanc, uri, body): |
218 # http://stackoverflow.com/a/1313868/881731 | |
219 s = DoPost(orthanc, uri, body) | |
220 | |
221 if (sys.version_info >= (3, 0)): | |
222 return zipfile.ZipFile(BytesIO(s), "r") | |
223 else: | |
224 return zipfile.ZipFile(StringIO(s), "r") | |
225 | |
1 | 226 def IsDefinedInLua(orthanc, name): |
0 | 227 s = DoPost(orthanc, '/tools/execute-script', 'print(type(%s))' % name, 'application/lua') |
228 return (s.strip() != 'nil') | |
229 | |
1 | 230 def WaitEmpty(orthanc): |
0 | 231 while True: |
1 | 232 if len(DoGet(orthanc, '/instances')) == 0: |
0 | 233 return |
234 time.sleep(0.1) | |
235 | |
137
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
236 def WaitJobDone(orthanc, job): |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
237 while True: |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
238 s = DoGet(orthanc, '/jobs/%s' % job) ['State'] |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
239 |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
240 if s == 'Success': |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
241 return True |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
242 elif s == 'Failure': |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
243 return False |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
244 |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
245 time.sleep(0.1) |
412d5f70447e
testing asynchronous c-move
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
130
diff
changeset
|
246 |
138 | 247 def MonitorJob(orthanc, func): # "func" is a lambda |
248 a = set(DoGet(orthanc, '/jobs')) | |
249 func() | |
250 b = set(DoGet(orthanc, '/jobs')) | |
251 | |
252 diff = list(b - a) | |
253 if len(diff) != 1: | |
254 print('No job was created!') | |
255 return False | |
256 else: | |
257 return WaitJobDone(orthanc, diff[0]) | |
258 | |
179
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
259 def MonitorJob2(orthanc, func): # "func" is a lambda |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
260 a = set(DoGet(orthanc, '/jobs')) |
181 | 261 job = func() |
179
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
262 b = set(DoGet(orthanc, '/jobs')) |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
263 |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
264 diff = list(b - a) |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
265 if len(diff) != 1: |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
266 print('No job was created!') |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
267 return None |
181 | 268 elif (not 'ID' in job or |
269 diff[0] != job['ID']): | |
270 print('Mismatch in the job ID') | |
271 return None | |
179
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
272 elif WaitJobDone(orthanc, diff[0]): |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
273 return diff[0] |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
274 else: |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
275 print('Error while executing the job') |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
276 return None |
8a2dd77d4035
testing split/merge
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
174
diff
changeset
|
277 |
220 | 278 def WaitAllNewJobsDone(orthanc, func): # "func" is a lambda |
279 a = set(DoGet(orthanc, '/jobs')) | |
280 func() | |
281 | |
282 first = True | |
283 | |
284 while True: | |
285 b = set(DoGet(orthanc, '/jobs')) | |
286 | |
287 diff = list(b - a) | |
288 if len(diff) == 0: | |
289 if first: | |
290 raise Exception('No job was created') | |
291 else: | |
292 return # We're done | |
293 else: | |
294 first = False | |
295 | |
296 if WaitJobDone(orthanc, diff[0]): | |
297 a.add(diff[0]) | |
298 else: | |
299 raise Exception('Error while executing the job') | |
300 | |
301 | |
1 | 302 def GetDockerHostAddress(): |
303 route = subprocess.check_output([ '/sbin/ip', 'route' ]) | |
304 m = re.search(r'default via ([0-9.]+)', route) | |
305 if m == None: | |
306 return 'localhost' | |
307 else: | |
308 return m.groups()[0] | |
4 | 309 |
44
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
310 def FindExecutable(name): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
311 p = os.path.join('/usr/local/bin', name) |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
312 if os.path.isfile(p): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
313 return p |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
314 |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
315 p = os.path.join('/usr/local/sbin', name) |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
316 if os.path.isfile(p): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
317 return p |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
318 |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
319 return name |
4 | 320 |
173 | 321 def IsOrthancVersionAbove(orthanc, major, minor, revision): |
322 v = DoGet(orthanc, '/system')['Version'] | |
323 | |
324 if v == 'mainline': | |
325 return True | |
326 else: | |
327 tmp = v.split('.') | |
328 a = int(tmp[0]) | |
329 b = int(tmp[1]) | |
330 c = int(tmp[2]) | |
331 return (a > major or | |
332 (a == major and b > minor) or | |
333 (a == major and b == minor and c >= revision)) | |
4 | 334 |
335 | |
336 class ExternalCommandThread: | |
337 @staticmethod | |
338 def ExternalCommandFunction(arg, stop_event, command, env): | |
339 external = subprocess.Popen(command, env = env) | |
340 | |
341 while (not stop_event.is_set()): | |
342 error = external.poll() | |
343 if error != None: | |
344 # http://stackoverflow.com/a/1489838/881731 | |
345 os._exit(-1) | |
346 stop_event.wait(0.1) | |
347 | |
83 | 348 print('Stopping the external command') |
4 | 349 external.terminate() |
9 | 350 external.communicate() # Wait for the command to stop |
4 | 351 |
352 def __init__(self, command, env = None): | |
353 self.thread_stop = threading.Event() | |
354 self.thread = threading.Thread(target = self.ExternalCommandFunction, | |
355 args = (10, self.thread_stop, command, env)) | |
9 | 356 #self.daemon = True |
4 | 357 self.thread.start() |
358 | |
359 def stop(self): | |
360 self.thread_stop.set() | |
361 self.thread.join() | |
220 | 362 |
363 | |
364 def AssertAlmostEqualRecursive(self, a, b, places = 7): | |
365 if type(a) is dict: | |
366 self.assertTrue(type(b) is dict) | |
367 self.assertEqual(a.keys(), b.keys()) | |
368 for key, value in a.items(): | |
369 AssertAlmostEqualRecursive(self, a[key], b[key], places) | |
370 | |
371 elif type(a) is list: | |
372 self.assertTrue(type(b) is list) | |
373 self.assertEqual(len(a), len(b)) | |
374 for i in range(len(a)): | |
375 AssertAlmostEqualRecursive(self, a[i], b[i], places) | |
376 | |
377 else: | |
378 self.assertAlmostEqual(a, b, places = places) |