Mercurial > hg > orthanc-tests
annotate Tests/Toolbox.py @ 73:97acfdf0dbce
2016
author | Sebastien Jodogne <s.jodogne@gmail.com> |
---|---|
date | Mon, 04 Jan 2016 13:27:26 +0100 |
parents | 84378ada15ab |
children | 3f2170efa8d2 |
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 |
6 # | |
7 # This program is free software: you can redistribute it and/or | |
8 # modify it under the terms of the GNU General Public License as | |
9 # published by the Free Software Foundation, either version 3 of the | |
10 # License, or (at your option) any later version. | |
11 # | |
12 # This program is distributed in the hope that it will be useful, but | |
13 # WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
15 # General Public License for more details. | |
16 # | |
17 # You should have received a copy of the GNU General Public License | |
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
0 | 19 |
20 | |
21 import hashlib | |
22 import httplib2 | |
23 import json | |
4 | 24 import os |
1 | 25 import re |
4 | 26 import signal |
1 | 27 import subprocess |
4 | 28 import threading |
0 | 29 import time |
1 | 30 import zipfile |
0 | 31 |
3 | 32 from PIL import Image |
33 from urllib import urlencode | |
34 | |
0 | 35 |
36 # http://stackoverflow.com/a/1313868/881731 | |
37 try: | |
38 from cStringIO import StringIO | |
39 except: | |
40 from StringIO import StringIO | |
41 | |
42 | |
13 | 43 def DefineOrthanc(server = 'localhost', |
44 restPort = 8042, | |
1 | 45 username = None, |
46 password = None, | |
47 aet = 'ORTHANC', | |
48 dicomPort = 4242): | |
13 | 49 #m = re.match(r'(http|https)://([^:]+):([^@]+)@([^@]+)', url) |
50 #if m != None: | |
51 # url = m.groups()[0] + '://' + m.groups()[3] | |
52 # username = m.groups()[1] | |
53 # password = m.groups()[2] | |
0 | 54 |
13 | 55 #if not url.endswith('/'): |
56 # url += '/' | |
0 | 57 |
1 | 58 return { |
13 | 59 'Server' : server, |
60 'Url' : 'http://%s:%d/' % (server, restPort), | |
1 | 61 'Username' : username, |
62 'Password' : password, | |
63 'DicomAet' : aet, | |
64 'DicomPort' : dicomPort | |
65 } | |
0 | 66 |
67 | |
68 def _SetupCredentials(orthanc, http): | |
1 | 69 if (orthanc['Username'] != None and |
70 orthanc['Password'] != None): | |
71 http.add_credentials(orthanc['Username'], orthanc['Password']) | |
0 | 72 |
28 | 73 def DoGetRaw(orthanc, uri, data = {}, body = None, headers = {}): |
0 | 74 d = '' |
75 if len(data.keys()) > 0: | |
76 d = '?' + urlencode(data) | |
77 | |
78 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
79 http.follow_redirects = False |
0 | 80 _SetupCredentials(orthanc, http) |
81 | |
1 | 82 resp, content = http.request(orthanc['Url'] + uri + d, 'GET', body = body, |
0 | 83 headers = headers) |
28 | 84 return (resp, content) |
85 | |
86 | |
87 def DoGet(orthanc, uri, data = {}, body = None, headers = {}): | |
88 (resp, content) = DoGetRaw(orthanc, uri, data = data, body = body, headers = headers) | |
89 | |
0 | 90 if not (resp.status in [ 200 ]): |
91 raise Exception(resp.status) | |
92 else: | |
93 try: | |
94 return json.loads(content) | |
95 except: | |
96 return content | |
97 | |
98 def _DoPutOrPost(orthanc, uri, method, data, contentType, headers): | |
99 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
100 http.follow_redirects = False |
0 | 101 _SetupCredentials(orthanc, http) |
102 | |
103 if isinstance(data, str): | |
104 body = data | |
105 if len(contentType) != 0: | |
106 headers['content-type'] = contentType | |
107 else: | |
108 body = json.dumps(data) | |
109 headers['content-type'] = 'application/json' | |
110 | |
111 headers['expect'] = '' | |
112 | |
1 | 113 resp, content = http.request(orthanc['Url'] + uri, method, |
0 | 114 body = body, |
115 headers = headers) | |
116 if not (resp.status in [ 200, 302 ]): | |
117 raise Exception(resp.status) | |
118 else: | |
119 try: | |
120 return json.loads(content) | |
121 except: | |
122 return content | |
123 | |
124 def DoDelete(orthanc, uri): | |
125 http = httplib2.Http() | |
21
2a29bcff60a7
tests of image decoding
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
13
diff
changeset
|
126 http.follow_redirects = False |
0 | 127 _SetupCredentials(orthanc, http) |
128 | |
1 | 129 resp, content = http.request(orthanc['Url'] + uri, 'DELETE') |
0 | 130 if not (resp.status in [ 200 ]): |
131 raise Exception(resp.status) | |
132 else: | |
133 try: | |
134 return json.loads(content) | |
135 except: | |
136 return content | |
137 | |
138 def DoPut(orthanc, uri, data = {}, contentType = ''): | |
10 | 139 return _DoPutOrPost(orthanc, uri, 'PUT', data, contentType, {}) |
0 | 140 |
141 def DoPost(orthanc, uri, data = {}, contentType = '', headers = {}): | |
142 return _DoPutOrPost(orthanc, uri, 'POST', data, contentType, headers) | |
143 | |
13 | 144 def GetDatabasePath(filename): |
145 return os.path.join(os.path.dirname(__file__), '..', 'Database', filename) | |
146 | |
0 | 147 def UploadInstance(orthanc, filename): |
13 | 148 f = open(GetDatabasePath(filename), 'rb') |
0 | 149 d = f.read() |
150 f.close() | |
151 return DoPost(orthanc, '/instances', d, 'application/dicom') | |
152 | |
153 def UploadFolder(orthanc, path): | |
13 | 154 for i in os.listdir(GetDatabasePath(path)): |
1 | 155 try: |
156 UploadInstance(orthanc, os.path.join(path, i)) | |
157 except: | |
158 pass | |
0 | 159 |
160 def DropOrthanc(orthanc): | |
161 # Reset the Lua callbacks | |
162 DoPost(orthanc, '/tools/execute-script', 'function OnStoredInstance(instanceId, tags, metadata) end', 'application/lua') | |
163 | |
164 DoDelete(orthanc, '/exports') | |
165 | |
166 for s in DoGet(orthanc, '/patients'): | |
167 DoDelete(orthanc, '/patients/%s' % s) | |
168 | |
169 def ComputeMD5(data): | |
170 m = hashlib.md5() | |
171 m.update(data) | |
172 return m.hexdigest() | |
173 | |
59
84378ada15ab
test_decode_brainix_as_jpeg
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
44
diff
changeset
|
174 def GetImage(orthanc, uri, headers = {}): |
0 | 175 # 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
|
176 data = DoGet(orthanc, uri, headers = headers) |
0 | 177 return Image.open(StringIO(data)) |
178 | |
179 def GetArchive(orthanc, uri): | |
180 # http://stackoverflow.com/a/1313868/881731 | |
181 s = DoGet(orthanc, uri) | |
182 return zipfile.ZipFile(StringIO(s), "r") | |
183 | |
1 | 184 def IsDefinedInLua(orthanc, name): |
0 | 185 s = DoPost(orthanc, '/tools/execute-script', 'print(type(%s))' % name, 'application/lua') |
186 return (s.strip() != 'nil') | |
187 | |
1 | 188 def WaitEmpty(orthanc): |
0 | 189 while True: |
1 | 190 if len(DoGet(orthanc, '/instances')) == 0: |
0 | 191 return |
192 time.sleep(0.1) | |
193 | |
1 | 194 def GetDockerHostAddress(): |
195 route = subprocess.check_output([ '/sbin/ip', 'route' ]) | |
196 m = re.search(r'default via ([0-9.]+)', route) | |
197 if m == None: | |
198 return 'localhost' | |
199 else: | |
200 return m.groups()[0] | |
4 | 201 |
44
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
202 def FindExecutable(name): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
203 p = os.path.join('/usr/local/bin', name) |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
204 if os.path.isfile(p): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
205 return p |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
206 |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
207 p = os.path.join('/usr/local/sbin', name) |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
208 if os.path.isfile(p): |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
209 return p |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
210 |
ffa542cce638
Toolbox.FindExecutable()
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
28
diff
changeset
|
211 return name |
4 | 212 |
213 | |
214 | |
215 class ExternalCommandThread: | |
216 @staticmethod | |
217 def ExternalCommandFunction(arg, stop_event, command, env): | |
218 external = subprocess.Popen(command, env = env) | |
219 | |
220 while (not stop_event.is_set()): | |
221 error = external.poll() | |
222 if error != None: | |
223 # http://stackoverflow.com/a/1489838/881731 | |
224 os._exit(-1) | |
225 stop_event.wait(0.1) | |
226 | |
227 print 'Stopping the external command' | |
228 external.terminate() | |
9 | 229 external.communicate() # Wait for the command to stop |
4 | 230 |
231 def __init__(self, command, env = None): | |
232 self.thread_stop = threading.Event() | |
233 self.thread = threading.Thread(target = self.ExternalCommandFunction, | |
234 args = (10, self.thread_stop, command, env)) | |
9 | 235 #self.daemon = True |
4 | 236 self.thread.start() |
237 | |
238 def stop(self): | |
239 self.thread_stop.set() | |
240 self.thread.join() |