|
25 | 25 | from importlib import reload |
26 | 26 | from pathlib import Path |
27 | 27 |
|
| 28 | +import pytest |
28 | 29 | import requests |
29 | 30 |
|
| 31 | +from templateflow import api as tf |
30 | 32 | from templateflow import conf as tfc |
31 | 33 |
|
| 34 | +from .data import load_data |
| 35 | + |
32 | 36 |
|
33 | 37 | def test_get_skel_file(tmp_path, monkeypatch): |
34 | 38 | """Exercise the skeleton file generation.""" |
@@ -87,3 +91,61 @@ def test_update_s3(tmp_path, monkeypatch): |
87 | 91 | for p in (newhome / 'tpl-MNI152NLin6Sym').glob('*.nii.gz'): |
88 | 92 | p.unlink() |
89 | 93 | assert tfc._s3.update(newhome, local=False, overwrite=False) |
| 94 | + |
| 95 | + |
| 96 | +def mock_get(*args, **kwargs): |
| 97 | + class MockResponse: |
| 98 | + status_code = 400 |
| 99 | + |
| 100 | + return MockResponse() |
| 101 | + |
| 102 | + |
| 103 | +def test_s3_400_error(monkeypatch): |
| 104 | + """Simulate a 400 error when fetching the skeleton file.""" |
| 105 | + |
| 106 | + reload(tfc) |
| 107 | + reload(tf) |
| 108 | + |
| 109 | + monkeypatch.setattr(requests, 'get', mock_get) |
| 110 | + with pytest.raises(RuntimeError, match=r'Failed to download .* code 400'): |
| 111 | + tf._s3_get( |
| 112 | + Path(tfc.TF_LAYOUT.root) |
| 113 | + / 'tpl-MNI152NLin2009cAsym/tpl-MNI152NLin2009cAsym_res-02_T1w.nii.gz' |
| 114 | + ) |
| 115 | + |
| 116 | + |
| 117 | +def test_bad_skeleton(tmp_path, monkeypatch): |
| 118 | + newhome = (tmp_path / 's3-update').resolve() |
| 119 | + monkeypatch.setattr(tfc, 'TF_USE_DATALAD', False) |
| 120 | + monkeypatch.setattr(tfc, 'TF_HOME', newhome) |
| 121 | + monkeypatch.setattr(tfc, 'TF_LAYOUT', None) |
| 122 | + |
| 123 | + tfc._init_cache() |
| 124 | + tfc.init_layout() |
| 125 | + |
| 126 | + assert tfc.TF_LAYOUT is not None |
| 127 | + assert tfc.TF_LAYOUT.root == str(newhome) |
| 128 | + |
| 129 | + # Instead of reloading |
| 130 | + monkeypatch.setattr(tf, 'TF_LAYOUT', tfc.TF_LAYOUT) |
| 131 | + |
| 132 | + paths = tf.ls('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None) |
| 133 | + assert paths |
| 134 | + path = Path(paths[0]) |
| 135 | + assert path.read_bytes() == b'' |
| 136 | + |
| 137 | + error_file = load_data.readable('error_response.xml') |
| 138 | + path.write_bytes(error_file.read_bytes()) |
| 139 | + |
| 140 | + # Test directly before testing through API paths |
| 141 | + tf._truncate_s3_errors(paths) |
| 142 | + assert path.read_bytes() == b'' |
| 143 | + |
| 144 | + path.write_bytes(error_file.read_bytes()) |
| 145 | + |
| 146 | + monkeypatch.setattr(requests, 'get', mock_get) |
| 147 | + with pytest.raises(RuntimeError): |
| 148 | + tf.get('MNI152NLin2009cAsym', resolution='02', suffix='T1w', desc=None) |
| 149 | + |
| 150 | + # Running get clears bad files before attempting to download |
| 151 | + assert path.read_bytes() == b'' |
0 commit comments