|
30 | 30 | Nifti1Image,
|
31 | 31 | Nifti1Pair,
|
32 | 32 | Nifti1PairHeader,
|
| 33 | + NiftiJSONExtension, |
33 | 34 | data_type_codes,
|
34 | 35 | extension_codes,
|
35 | 36 | load,
|
@@ -1388,6 +1389,56 @@ def test_nifti_dicom_extension():
|
1388 | 1389 | Nifti1DicomExtension(2, 0)
|
1389 | 1390 |
|
1390 | 1391 |
|
| 1392 | +def test_json_extension(tmp_path): |
| 1393 | + nim = load(image_file) |
| 1394 | + hdr = nim.header |
| 1395 | + exts_container = hdr.extensions |
| 1396 | + |
| 1397 | + # Test basic functionality |
| 1398 | + json_ext = NiftiJSONExtension('ignore', b'{"key": "value"}') |
| 1399 | + assert json_ext.get_content() == {'key': 'value'} |
| 1400 | + byte_content = json_ext._mangle(json_ext.get_content()) |
| 1401 | + assert byte_content == b'{"key": "value"}' |
| 1402 | + json_obj = json_ext._unmangle(byte_content) |
| 1403 | + assert json_obj == {'key': 'value'} |
| 1404 | + size = 16 * ((len(byte_content) + 7) // 16 + 1) |
| 1405 | + assert json_ext.get_sizeondisk() == size |
| 1406 | + |
| 1407 | + def ext_to_bytes(ext, byteswap=False): |
| 1408 | + bio = BytesIO() |
| 1409 | + ext.write_to(bio, byteswap) |
| 1410 | + return bio.getvalue() |
| 1411 | + |
| 1412 | + # Check serialization |
| 1413 | + bytestring = ext_to_bytes(json_ext) |
| 1414 | + assert bytestring[:8] == struct.pack('<2I', size, extension_codes['ignore']) |
| 1415 | + assert bytestring[8:].startswith(byte_content) |
| 1416 | + assert len(bytestring) == size |
| 1417 | + |
| 1418 | + # Save to file and read back |
| 1419 | + exts_container.append(json_ext) |
| 1420 | + nim.to_filename(tmp_path / 'test.nii') |
| 1421 | + |
| 1422 | + # We used ignore, so it comes back as a Nifti1Extension |
| 1423 | + rt_img = Nifti1Image.from_filename(tmp_path / 'test.nii') |
| 1424 | + assert len(rt_img.header.extensions) == 3 |
| 1425 | + rt_ext = rt_img.header.extensions[-1] |
| 1426 | + assert rt_ext.get_code() == extension_codes['ignore'] |
| 1427 | + assert rt_ext.get_content() == byte_content |
| 1428 | + |
| 1429 | + # MRS is currently the only JSON extension |
| 1430 | + json_ext._code = extension_codes['mrs'] |
| 1431 | + nim.to_filename(tmp_path / 'test.nii') |
| 1432 | + |
| 1433 | + # Check that the extension is read back as a NiftiJSONExtension |
| 1434 | + rt_img = Nifti1Image.from_filename(tmp_path / 'test.nii') |
| 1435 | + assert len(rt_img.header.extensions) == 3 |
| 1436 | + rt_ext = rt_img.header.extensions[-1] |
| 1437 | + assert rt_ext.get_code() == extension_codes['mrs'] |
| 1438 | + assert isinstance(rt_ext, NiftiJSONExtension) |
| 1439 | + assert rt_ext.get_content() == json_obj |
| 1440 | + |
| 1441 | + |
1391 | 1442 | class TestNifti1General:
|
1392 | 1443 | """Test class to test nifti1 in general
|
1393 | 1444 |
|
|
0 commit comments