|
30 | 30 | Nifti1Image,
|
31 | 31 | Nifti1Pair,
|
32 | 32 | Nifti1PairHeader,
|
| 33 | + NiftiJSONExtension, |
33 | 34 | data_type_codes,
|
34 | 35 | extension_codes,
|
35 | 36 | load,
|
@@ -1414,6 +1415,56 @@ def test_nifti_dicom_extension():
|
1414 | 1415 | Nifti1DicomExtension(2, 0)
|
1415 | 1416 |
|
1416 | 1417 |
|
| 1418 | +def test_json_extension(tmp_path): |
| 1419 | + nim = load(image_file) |
| 1420 | + hdr = nim.header |
| 1421 | + exts_container = hdr.extensions |
| 1422 | + |
| 1423 | + # Test basic functionality |
| 1424 | + json_ext = NiftiJSONExtension('ignore', b'{"key": "value"}') |
| 1425 | + assert json_ext.get_content() == {'key': 'value'} |
| 1426 | + byte_content = json_ext._mangle(json_ext.get_content()) |
| 1427 | + assert byte_content == b'{"key": "value"}' |
| 1428 | + json_obj = json_ext._unmangle(byte_content) |
| 1429 | + assert json_obj == {'key': 'value'} |
| 1430 | + size = 16 * ((len(byte_content) + 7) // 16 + 1) |
| 1431 | + assert json_ext.get_sizeondisk() == size |
| 1432 | + |
| 1433 | + def ext_to_bytes(ext, byteswap=False): |
| 1434 | + bio = BytesIO() |
| 1435 | + ext.write_to(bio, byteswap) |
| 1436 | + return bio.getvalue() |
| 1437 | + |
| 1438 | + # Check serialization |
| 1439 | + bytestring = ext_to_bytes(json_ext) |
| 1440 | + assert bytestring[:8] == struct.pack('<2I', size, extension_codes['ignore']) |
| 1441 | + assert bytestring[8:].startswith(byte_content) |
| 1442 | + assert len(bytestring) == size |
| 1443 | + |
| 1444 | + # Save to file and read back |
| 1445 | + exts_container.append(json_ext) |
| 1446 | + nim.to_filename(tmp_path / 'test.nii') |
| 1447 | + |
| 1448 | + # We used ignore, so it comes back as a Nifti1Extension |
| 1449 | + rt_img = Nifti1Image.from_filename(tmp_path / 'test.nii') |
| 1450 | + assert len(rt_img.header.extensions) == 3 |
| 1451 | + rt_ext = rt_img.header.extensions[-1] |
| 1452 | + assert rt_ext.get_code() == extension_codes['ignore'] |
| 1453 | + assert rt_ext.get_content() == byte_content |
| 1454 | + |
| 1455 | + # MRS is currently the only JSON extension |
| 1456 | + json_ext._code = extension_codes['mrs'] |
| 1457 | + nim.to_filename(tmp_path / 'test.nii') |
| 1458 | + |
| 1459 | + # Check that the extension is read back as a NiftiJSONExtension |
| 1460 | + rt_img = Nifti1Image.from_filename(tmp_path / 'test.nii') |
| 1461 | + assert len(rt_img.header.extensions) == 3 |
| 1462 | + rt_ext = rt_img.header.extensions[-1] |
| 1463 | + assert rt_ext.get_code() == extension_codes['mrs'] |
| 1464 | + assert isinstance(rt_ext, NiftiJSONExtension) |
| 1465 | + assert rt_ext.get_content() == json_obj |
| 1466 | + |
| 1467 | + |
1417 | 1468 | class TestNifti1General:
|
1418 | 1469 | """Test class to test nifti1 in general
|
1419 | 1470 |
|
|
0 commit comments