Coverage for nilearn/_utils/tests/test_testing.py: 0%

32 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-20 10:58 +0200

1import numpy as np 

2import pytest 

3from nibabel import Nifti1Image 

4 

5from nilearn._utils.testing import ( 

6 assert_memory_less_than, 

7 with_memory_profiler, 

8 write_imgs_to_path, 

9) 

10 

11 

12def create_object(size): 

13 """Just create and return an object containing `size` bytes.""" 

14 mem_use = b"a" * size 

15 return mem_use 

16 

17 

18@with_memory_profiler 

19def test_memory_usage(): 

20 # Valid measures (larger objects) 

21 for mem in (500, 200): 

22 assert_memory_less_than(mem, 0.1, create_object, mem * 1024**2) 

23 

24 # Ensure an exception is raised with too small objects as 

25 # memory_profiler can return non trustable memory measure in this case. 

26 with pytest.raises( 

27 ValueError, match="Memory profiler measured an untrustable memory" 

28 ): 

29 assert_memory_less_than(50, 0.1, create_object, 25 * 1024**2) 

30 

31 # Ensure ValueError is raised if memory used is above expected memory 

32 # limit. 

33 with pytest.raises(ValueError, match="Memory consumption measured"): 

34 assert_memory_less_than(100, 0.1, create_object, 200 * 1024**2) 

35 

36 

37def test_int64_niftis(affine_eye, tmp_path): 

38 data = np.ones((3, 3, 3), dtype=bool) 

39 for dtype in "uint8", "int32", "float32": 

40 img = Nifti1Image(data.astype(dtype), affine_eye) 

41 img.to_filename(tmp_path.joinpath("img.nii.gz")) 

42 for dtype in "int64", "uint64": 

43 with pytest.raises(AssertionError): 

44 Nifti1Image(data.astype(dtype), affine_eye) 

45 

46 

47@pytest.mark.parametrize("create_files", [True, False]) 

48@pytest.mark.parametrize("use_wildcards", [True, False]) 

49def test_write_tmp_imgs_default( 

50 monkeypatch, tmp_path, img_3d_mni, create_files, use_wildcards 

51): 

52 """Write imgs to default location.""" 

53 monkeypatch.chdir(tmp_path) 

54 

55 write_imgs_to_path( 

56 img_3d_mni, 

57 create_files=create_files, 

58 use_wildcards=use_wildcards, 

59 ) 

60 

61 

62@pytest.mark.parametrize("create_files", [True, False]) 

63@pytest.mark.parametrize("use_wildcards", [True, False]) 

64def test_write_tmp_imgs_set_path( 

65 tmp_path, img_3d_mni, create_files, use_wildcards 

66): 

67 """Write imgs to a specified location.""" 

68 write_imgs_to_path( 

69 img_3d_mni, 

70 file_path=tmp_path, 

71 create_files=create_files, 

72 use_wildcards=use_wildcards, 

73 )