Skip to content

Commit c373a8d

Browse files
committed
test: Check for HTTP error and clearing old errors
1 parent 1c3565e commit c373a8d

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

templateflow/tests/test_s3.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@
2525
from importlib import reload
2626
from pathlib import Path
2727

28+
import pytest
2829
import requests
2930

31+
from templateflow import api as tf
3032
from templateflow import conf as tfc
3133

34+
from .data import load_data
35+
3236

3337
def test_get_skel_file(tmp_path, monkeypatch):
3438
"""Exercise the skeleton file generation."""
@@ -87,3 +91,66 @@ def test_update_s3(tmp_path, monkeypatch):
8791
for p in (newhome / 'tpl-MNI152NLin6Sym').glob('*.nii.gz'):
8892
p.unlink()
8993
assert tfc._s3.update(newhome, local=False, overwrite=False)
94+
95+
96+
def test_s3_400_error(monkeypatch):
97+
"""Simulate a 400 error when fetching the skeleton file."""
98+
99+
reload(tfc)
100+
101+
def mock_get(*args, **kwargs):
102+
class MockResponse:
103+
status_code = 400
104+
105+
return MockResponse()
106+
107+
monkeypatch.setattr(requests, 'get', mock_get)
108+
with pytest.raises(RuntimeError):
109+
tf._s3_get(
110+
Path(tfc.TF_LAYOUT.root)
111+
/ 'tpl-MNI152NLin2009cAsym/tpl-MNI152NLin2009cAsym_res-02_T1w.nii.gz'
112+
)
113+
114+
115+
def test_bad_skeleton(tmp_path, monkeypatch):
116+
newhome = (tmp_path / 's3-update').resolve()
117+
monkeypatch.setattr(tfc, 'TF_USE_DATALAD', False)
118+
monkeypatch.setattr(tfc, 'TF_HOME', newhome)
119+
monkeypatch.setattr(tfc, 'TF_LAYOUT', None)
120+
121+
tfc._init_cache()
122+
tfc.init_layout()
123+
124+
assert tfc.TF_LAYOUT is not None
125+
assert tfc.TF_LAYOUT.root == str(newhome)
126+
127+
# Instead of reloading
128+
monkeypatch.setattr(tf, 'TF_LAYOUT', tfc.TF_LAYOUT)
129+
130+
paths = tf.ls('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None)
131+
assert paths
132+
path = Path(paths[0])
133+
assert path.read_bytes() == b''
134+
135+
error_file = load_data.readable('error_response.xml')
136+
path.write_bytes(error_file.read_bytes())
137+
138+
# Test directly before testing through API paths
139+
tf._truncate_s3_errors(paths)
140+
assert path.read_bytes() == b''
141+
142+
path.write_bytes(error_file.read_bytes())
143+
144+
# Run full get but mock 400 to avoid actual network call
145+
def mock_get(*args, **kwargs):
146+
class MockResponse:
147+
status_code = 400
148+
149+
return MockResponse()
150+
151+
monkeypatch.setattr(requests, 'get', mock_get)
152+
with pytest.raises(RuntimeError):
153+
tf.get('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None)
154+
155+
# Running get clears bad files before attempting to download
156+
assert path.read_bytes() == b''

0 commit comments

Comments
 (0)