def test_header_read_restore(self): # Test that reading a header restores the file position trk_fname = DATA['simple_trk_fname'] bio = BytesIO() bio.write(b'Along my very merry way') hdr_pos = bio.tell() hdr_from_fname = TrkFile._read_header(trk_fname) with open(trk_fname, 'rb') as fobj: bio.write(fobj.read()) bio.seek(hdr_pos) # Check header is as expected hdr_from_fname['_offset_data'] += hdr_pos # Correct for start position assert_arr_dict_equal(TrkFile._read_header(bio), hdr_from_fname) # Check fileobject file position has not changed assert_equal(bio.tell(), hdr_pos)
def test_is_supported_detect_format(): # Test is_supported and detect_format functions # Empty file/string f = BytesIO() assert_false(nib.streamlines.is_supported(f)) assert_false(nib.streamlines.is_supported("")) assert_true(nib.streamlines.detect_format(f) is None) assert_true(nib.streamlines.detect_format("") is None) # Valid file without extension for tfile_cls in nib.streamlines.FORMATS.values(): f = BytesIO() f.write(tfile_cls.MAGIC_NUMBER) f.seek(0, os.SEEK_SET) assert_true(nib.streamlines.is_supported(f)) assert_true(nib.streamlines.detect_format(f) is tfile_cls) # Wrong extension but right magic number for tfile_cls in nib.streamlines.FORMATS.values(): with tempfile.TemporaryFile(mode="w+b", suffix=".txt") as f: f.write(tfile_cls.MAGIC_NUMBER) f.seek(0, os.SEEK_SET) assert_true(nib.streamlines.is_supported(f)) assert_true(nib.streamlines.detect_format(f) is tfile_cls) # Good extension but wrong magic number for ext, tfile_cls in nib.streamlines.FORMATS.items(): with tempfile.TemporaryFile(mode="w+b", suffix=ext) as f: f.write(b"pass") f.seek(0, os.SEEK_SET) assert_false(nib.streamlines.is_supported(f)) assert_true(nib.streamlines.detect_format(f) is None) # Wrong extension, string only f = "my_tractogram.asd" assert_false(nib.streamlines.is_supported(f)) assert_true(nib.streamlines.detect_format(f) is None) # Good extension, string only for ext, tfile_cls in nib.streamlines.FORMATS.items(): f = "my_tractogram" + ext assert_true(nib.streamlines.is_supported(f)) assert_equal(nib.streamlines.detect_format(f), tfile_cls) # Extension should not be case-sensitive. for ext, tfile_cls in nib.streamlines.FORMATS.items(): f = "my_tractogram" + ext.upper() assert_true(nib.streamlines.detect_format(f) is tfile_cls)