Skip to content

Commit 55e4569

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

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

templateflow/tests/test_s3.py

Lines changed: 65 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,64 @@ 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+
def mock_get(*args, **kwargs):
100+
class MockResponse:
101+
status_code = 400
102+
103+
return MockResponse()
104+
105+
monkeypatch.setattr(requests, 'get', mock_get)
106+
with pytest.raises(RuntimeError):
107+
tf._s3_get(
108+
Path(tfc.TF_LAYOUT.root)
109+
/ 'tpl-MNI152NLin2009cAsym/tpl-MNI152NLin2009cAsym_res-02_T1w.nii.gz'
110+
)
111+
112+
113+
def test_bad_skeleton(tmp_path, monkeypatch):
114+
newhome = (tmp_path / 's3-update').resolve()
115+
monkeypatch.setattr(tfc, 'TF_USE_DATALAD', False)
116+
monkeypatch.setattr(tfc, 'TF_HOME', newhome)
117+
monkeypatch.setattr(tfc, 'TF_LAYOUT', None)
118+
119+
tfc._init_cache()
120+
tfc.init_layout()
121+
122+
assert tfc.TF_LAYOUT is not None
123+
assert tfc.TF_LAYOUT.root == str(newhome)
124+
125+
# Instead of reloading
126+
monkeypatch.setattr(tf, 'TF_LAYOUT', tfc.TF_LAYOUT)
127+
128+
paths = tf.ls('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None)
129+
assert paths
130+
path = Path(paths[0])
131+
assert path.read_bytes() == b''
132+
133+
error_file = load_data.readable('error_response.xml')
134+
path.write_bytes(error_file.read_bytes())
135+
136+
# Test directly before testing through API paths
137+
tf._truncate_s3_errors(paths)
138+
assert path.read_bytes() == b''
139+
140+
path.write_bytes(error_file.read_bytes())
141+
142+
# Run full get but mock 400 to avoid actual network call
143+
def mock_get(*args, **kwargs):
144+
class MockResponse:
145+
status_code = 400
146+
147+
return MockResponse()
148+
149+
monkeypatch.setattr(requests, 'get', mock_get)
150+
with pytest.raises(RuntimeError):
151+
tf.get('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None)
152+
153+
# Running get clears bad files before attempting to download
154+
assert path.read_bytes() == b''

0 commit comments

Comments
 (0)