/
test_client.py
473 lines (413 loc) · 17.3 KB
/
test_client.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
# -*- coding: utf-8 -*-
"""
The obspy.clients.syngine test suite.
"""
import io
import re
from unittest import mock
import numpy as np
import pytest
import obspy
from obspy.core.util.base import NamedTemporaryFile
from obspy.clients.syngine import Client
from obspy.clients.base import DEFAULT_TESTING_USER_AGENT, ClientHTTPException
BASE_URL = "http://service.iris.edu/irisws/syngine/1"
pytestmark = pytest.mark.network
class RequestsMockResponse(object):
def __init__(self):
self.text = ""
self.content = b""
self.status_code = 200
self._json = {}
def json(self):
return self._json
class TestClient():
"""
Test cases for obspy.clients.iris.client.Client.
"""
c = Client(user_agent=DEFAULT_TESTING_USER_AGENT)
def test_get_model_info_mock(self):
"""
Mock test for the get_model_info() method.
"""
with mock.patch("requests.get") as p:
r = RequestsMockResponse()
r._json["slip"] = [0.0, 1.0, 2.0]
r._json["sliprate"] = [0.0, 1.0, 2.0]
p.return_value = r
self.c.get_model_info("test_model")
assert p.call_count == 1
assert p.call_args[1]["url"] == \
'http://service.iris.edu/irisws/syngine/1/info'
assert p.call_args[1]["params"] == {'model': 'test_model'}
assert p.call_args[1]["headers"] == \
{'User-Agent': DEFAULT_TESTING_USER_AGENT}
def test_get_model_info(self):
"""
Actual test for the get_model_info() method.
"""
info = self.c.get_model_info("test")
assert isinstance(info, obspy.core.AttribDict)
# Check two random keys.
assert info.dump_type == "displ_only"
assert info.time_scheme == "newmark2"
# Check that both arrays have been converted to numpy arrays.
assert isinstance(info.slip, np.ndarray)
assert isinstance(info.sliprate, np.ndarray)
def test_get_available_models_mock(self):
with mock.patch("requests.get") as p:
p.return_value = RequestsMockResponse()
self.c.get_available_models()
assert p.call_count == 1
assert p.call_args[1]["url"] == \
'http://service.iris.edu/irisws/syngine/1/models'
assert p.call_args[1]["params"] is None
assert p.call_args[1]["headers"] == \
{'User-Agent': DEFAULT_TESTING_USER_AGENT}
def test_get_available_models(self):
models = self.c.get_available_models()
assert isinstance(models, dict)
assert len(models) > 3
assert "ak135f_5s" in models
# Check random key.
assert models["ak135f_5s"]["components"] == "vertical and horizontal"
def test_get_service_version_mock(self):
with mock.patch("requests.get") as p:
p.return_value = RequestsMockResponse()
p.return_value.text = "1.2.3"
version = self.c.get_service_version()
assert version == "1.2.3"
assert p.call_count == 1
assert p.call_args[1]["url"] == \
'http://service.iris.edu/irisws/syngine/1/version'
assert p.call_args[1]["params"] is None
assert p.call_args[1]["headers"] == \
{'User-Agent': DEFAULT_TESTING_USER_AGENT}
def test_get_waveforms_mock(self):
"""
Test the queries from the IRIS syngine website and see if they
produce the correct URLS.
"""
r = RequestsMockResponse()
with io.BytesIO() as buf:
obspy.read()[0].write(buf, format="mseed")
buf.seek(0, 0)
r.content = buf.read()
# http://service.iris.edu/irisws/syngine/1/query?network=IU&
# station=ANMO&components=ZRT&eventid=GCMT:M110302J
with mock.patch("requests.get") as p:
p.return_value = r
st = self.c.get_waveforms(model="ak135f_5s",
network="IU", station="ANMO",
components="ZRT",
eventid="GCMT:M110302J")
assert isinstance(st, obspy.Stream)
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"components": "ZRT",
"eventid": "GCMT:M110302J",
"format": "miniseed",
"model": "ak135f_5s",
"network": "IU",
"station": "ANMO"}
assert p.call_args[1]["headers"] == \
{"User-Agent": DEFAULT_TESTING_USER_AGENT}
# http://service.iris.edu/irisws/syngine/1/query?network=_GSN&
# components=Z&eventid=GCMT:M110302J&endtime=1800
with mock.patch("requests.get") as p:
p.return_value = r
st = self.c.get_waveforms(model="ak135f_5s",
network="_GSN",
components="Z",
endtime=1800.0,
eventid="GCMT:M110302J")
assert isinstance(st, obspy.Stream)
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"components": "Z",
"endtime": 1800.0,
"eventid": "GCMT:M110302J",
"format": "miniseed",
"model": "ak135f_5s",
"network": "_GSN"}
assert p.call_args[1]["headers"] == \
{"User-Agent": DEFAULT_TESTING_USER_AGENT}
# http://service.iris.edu/irisws/syngine/1/query?network=_GSN&
# components=Z&eventid=GCMT:M110302J&starttime=P-10&endtime=ScS%2B60
with mock.patch("requests.get") as p:
p.return_value = r
st = self.c.get_waveforms(model="ak135f_5s",
network="_GSN",
components="Z",
starttime="P-10",
endtime="ScS+60",
eventid="GCMT:M110302J")
assert isinstance(st, obspy.Stream)
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"components": "Z",
"starttime": "P-10",
"endtime": "ScS+60",
"eventid": "GCMT:M110302J",
"format": "miniseed",
"model": "ak135f_5s",
"network": "_GSN"}
assert p.call_args[1]["headers"] == \
{"User-Agent": DEFAULT_TESTING_USER_AGENT}
def test_error_handling_arguments(self):
# Floating points value
with pytest.raises(ValueError):
self.c.get_waveforms(model="test", receiverlatitude="a")
# Int.
with pytest.raises(ValueError):
self.c.get_waveforms(model="test", kernelwidth="a")
# Time.
with pytest.raises(TypeError):
self.c.get_waveforms(model="test", origintime="a")
def test_source_mechanisms_mock(self):
r = RequestsMockResponse()
with io.BytesIO() as buf:
obspy.read()[0].write(buf, format="mseed")
buf.seek(0, 0)
r.content = buf.read()
with mock.patch("requests.get") as p:
p.return_value = r
self.c.get_waveforms(model="ak135f_5s",
sourcemomenttensor=[1, 2, 3, 4, 5, 6])
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"model": "ak135f_5s",
"format": "miniseed",
"sourcemomenttensor": "1,2,3,4,5,6"}
with mock.patch("requests.get") as p:
p.return_value = r
self.c.get_waveforms(model="ak135f_5s",
sourcedoublecouple=[1, 2, 3, 4])
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"model": "ak135f_5s",
"format": "miniseed",
"sourcedoublecouple": "1,2,3,4"}
with mock.patch("requests.get") as p:
p.return_value = r
self.c.get_waveforms(model="ak135f_5s",
sourceforce=[3.32, 4.23, 5.11])
assert p.call_count == 1
assert p.call_args[1]["url"] == \
"http://service.iris.edu/irisws/syngine/1/query"
assert p.call_args[1]["params"] == {
"model": "ak135f_5s",
"format": "miniseed",
"sourceforce": "3.32,4.23,5.11"}
def test_error_handling(self):
"""
Tests the error handling. The clients just pass on most things to
syngine and rely on the service for the error detection.
"""
# Wrong components.
msg = re.compile("HTTP code 400 when.*Unrecognized component",
re.DOTALL)
with pytest.raises(ClientHTTPException, match=msg):
self.c.get_waveforms(
model="ak135f_5s", eventid="GCMT:C201002270634A",
station="ANMO", network="IU", components="ABC")
def test_bulk_waveform_download_mock(self):
"""
Mock the bulk download requests to test the payload generation.
"""
r = RequestsMockResponse()
with io.BytesIO() as buf:
obspy.read()[0].write(buf, format="mseed")
buf.seek(0, 0)
r.content = buf.read()
payload = []
def side_effect(*args, **kwargs):
payload[:] = [kwargs["data"].decode()]
return r
# Test simple lists first.
with mock.patch("requests.post") as p:
p.side_effect = side_effect
self.c.get_waveforms_bulk(
model="ak135f_5s", bulk=[
[1.0, 2.0],
(2.0, 3.0),
("AA", "BB")])
assert payload[0] == "\n".join([
"model=ak135f_5s",
"format=miniseed",
"1.0 2.0",
"2.0 3.0",
"AA BB\n"])
# A couple more parameters
with mock.patch("requests.post") as p:
p.side_effect = side_effect
self.c.get_waveforms_bulk(
model="ak135f_5s", bulk=[
[1.0, 2.0],
(2.0, 3.0),
("AA", "BB")],
format="miniseed",
sourcemomenttensor=[1, 2, 3, 4, 5, 6])
assert payload[0] == "\n".join([
"model=ak135f_5s",
"format=miniseed",
"sourcemomenttensor=1,2,3,4,5,6",
"1.0 2.0",
"2.0 3.0",
"AA BB\n"])
# A couple of dictionaries.
with mock.patch("requests.post") as p:
p.side_effect = side_effect
self.c.get_waveforms_bulk(
model="ak135f_5s", bulk=[
{"network": "IU", "station": "ANMO"},
{"latitude": 12, "longitude": 13.1},
{"latitude": 12, "longitude": 13.1, "networkcode": "IU"},
{"latitude": 12, "longitude": 13.1, "stationcode": "ANMO"},
{"latitude": 12, "longitude": 13.1, "locationcode": "00"},
{"latitude": 12, "longitude": 13.1, "networkcode": "IU",
"stationcode": "ANMO", "locationcode": "00"}],
format="miniseed", eventid="GCMT:C201002270634A")
assert payload[0] == "\n".join([
"model=ak135f_5s",
"eventid=GCMT:C201002270634A",
"format=miniseed",
"IU ANMO",
"12 13.1",
"12 13.1 NETCODE=IU",
"12 13.1 STACODE=ANMO",
"12 13.1 LOCCODE=00",
"12 13.1 NETCODE=IU STACODE=ANMO LOCCODE=00\n"])
def test_get_waveforms(self):
"""
Test get_waveforms() and get_waveforms_bulk() by actually downloading
some things.
Use the 'test' model which does not produce useful seismograms but
is quick to test.
"""
st = self.c.get_waveforms(model="test", network="IU", station="ANMO",
eventid="GCMT:C201002270634A",
components="Z")
assert len(st) == 1
# Download exactly the same with a bulk request and check the result
# is the same!
st_bulk = self.c.get_waveforms_bulk(
model="test", bulk=[("IU", "ANMO")],
eventid="GCMT:C201002270634A", components="Z")
assert len(st_bulk) == 1
assert st == st_bulk
# Test phase relative times. This tests that everything is correctly
# encoded and what not.
st = self.c.get_waveforms(model="test", network="IU", station="ANMO",
eventid="GCMT:C201002270634A",
starttime="P-10", endtime="P+20",
components="Z")
assert len(st) == 1
st_bulk = self.c.get_waveforms_bulk(
model="test", bulk=[("IU", "ANMO")],
starttime="P-10", endtime="P+20",
eventid="GCMT:C201002270634A", components="Z")
assert len(st_bulk) == 1
assert st == st_bulk
# One to test a source mechanism
st = self.c.get_waveforms(model="test", network="IU", station="ANMO",
sourcemomenttensor=[1, 2, 3, 4, 5, 6],
sourcelatitude=10, sourcelongitude=20,
sourcedepthinmeters=100,
components="Z")
assert len(st) == 1
st_bulk = self.c.get_waveforms_bulk(
model="test", bulk=[("IU", "ANMO")],
sourcemomenttensor=[1, 2, 3, 4, 5, 6],
sourcelatitude=10, sourcelongitude=20,
sourcedepthinmeters=100,
components="Z")
assert len(st_bulk) == 1
assert st == st_bulk
# One more to test actual time values.
st = self.c.get_waveforms(
model="test", network="IU", station="ANMO",
origintime=obspy.UTCDateTime(2015, 1, 2, 3, 0, 5),
starttime=obspy.UTCDateTime(2015, 1, 2, 3, 4, 5),
endtime=obspy.UTCDateTime(2015, 1, 2, 3, 10, 5),
sourcemomenttensor=[1, 2, 3, 4, 5, 6],
sourcelatitude=10, sourcelongitude=20,
sourcedepthinmeters=100,
components="Z")
assert len(st) == 1
st_bulk = self.c.get_waveforms_bulk(
model="test", bulk=[("IU", "ANMO")],
origintime=obspy.UTCDateTime(2015, 1, 2, 3, 0, 5),
starttime=obspy.UTCDateTime(2015, 1, 2, 3, 4, 5),
endtime=obspy.UTCDateTime(2015, 1, 2, 3, 10, 5),
sourcemomenttensor=[1, 2, 3, 4, 5, 6],
sourcelatitude=10, sourcelongitude=20,
sourcedepthinmeters=100,
components="Z")
assert len(st_bulk) == 1
assert st == st_bulk
def test_saving_directly_to_file(self):
# Save to a filename.
with NamedTemporaryFile() as tf:
filename = tf.name
st = self.c.get_waveforms(
model="test", network="IU", station="ANMO",
eventid="GCMT:C201002270634A", starttime="P-10",
endtime="P+10", components="Z", filename=tf)
# No return value.
assert st is None
st = obspy.read(filename)
assert len(st) == 1
# Save to an open file-like object.
with io.BytesIO() as buf:
st = self.c.get_waveforms(
model="test", network="IU", station="ANMO",
eventid="GCMT:C201002270634A", starttime="P-10",
endtime="P+10", components="Z", filename=buf)
# No return value.
assert st is None
buf.seek(0, 0)
st = obspy.read(buf)
assert len(st) == 1
def test_reading_saczip_files(self):
st = self.c.get_waveforms(
model="test", network="IU", station="ANMO",
eventid="GCMT:C201002270634A", starttime="P-10",
endtime="P+10", components="Z", format="saczip")
assert len(st) == 1
# Same with bulk request.
st_bulk = self.c.get_waveforms_bulk(
model="test", bulk=[("IU", "ANMO")],
eventid="GCMT:C201002270634A", starttime="P-10",
endtime="P+10", components="Z", format="saczip")
assert len(st_bulk) == 1
assert st == st_bulk
def test_bulk_waveform_send_custom_payload(self):
"""
The get_waveforms_bulk() method can send a custom payload.
"""
r = RequestsMockResponse()
with io.BytesIO() as buf:
obspy.read()[0].write(buf, format="mseed")
buf.seek(0, 0)
r.content = buf.read()
payload = []
def side_effect(*args, **kwargs):
payload[:] = [kwargs["data"]]
return r
# Test simple lists first.
with mock.patch("requests.post") as p:
p.side_effect = side_effect
self.c.get_waveforms_bulk(
model="ak135f_5s", bulk=[], data=b"1234\n5678")
assert payload[0] == b"1234\n5678"