Repository: nilearn/nilearn

Issue:
Choose better affine constant for plotting test data
At the time I was "just" refactoring code and started adding fixtures when doing so. So I did not have a close look at the exact content.

Digging into this now I realize we may have some inconsistency.

```python
from nilearn.plotting.img_plotting import MNI152TEMPLATE
mni_affine = MNI152TEMPLATE.get_affine()
print(mni_affine)
```

gives
```
[[   2.    0.    0.  -98.]
 [   0.    2.    0. -134.]
 [   0.    0.    2.  -72.]
 [   0.    0.    0.    1.]]
```

which does not quite match that in conf.py

```python
MNI_AFFINE = np.array(
    [
        [-2.0, 0.0, 0.0, 90.0],
        [0.0, 2.0, 0.0, -126.0],
        [0.0, 0.0, 2.0, -72.0],
        [0.0, 0.0, 0.0, 1.0],
    ]
)
```

_Originally posted by @Remi-Gau in https://github.com/nilearn/nilearn/issues/3172#issuecomment-1662060133_
            


Discussion:
OK for changing the one in conf.py.

Resolving patch:
diff --git a/nilearn/conftest.py b/nilearn/conftest.py
--- a/nilearn/conftest.py
+++ b/nilearn/conftest.py
@@ -81,14 +81,22 @@ def close_all():
 
 MNI_AFFINE = np.array(
     [
-        [-2.0, 0.0, 0.0, 90.0],
-        [0.0, 2.0, 0.0, -126.0],
+        [2.0, 0.0, 0.0, -98.0],
+        [0.0, 2.0, 0.0, -134.0],
         [0.0, 0.0, 2.0, -72.0],
         [0.0, 0.0, 0.0, 1.0],
     ]
 )
 
 
+def _mni_3d_img(affine=MNI_AFFINE):
+    data_positive = np.zeros((7, 7, 3))
+    rng = np.random.RandomState(42)
+    data_rng = rng.rand(7, 7, 3)
+    data_positive[1:-1, 2:-1, 1:] = data_rng[1:-1, 2:-1, 1:]
+    return Nifti1Image(data_positive, affine)
+
+
 @pytest.fixture()
 def mni_affine():
     """Return an affine corresponding to 2mm isotropic MNI template."""
@@ -96,15 +104,9 @@ def mni_affine():
 
 
 @pytest.fixture()
-def testdata_3d_for_plotting():
-    """A random 3D image for testing figures."""
-    data_positive = np.zeros((7, 7, 3))
-    rng = np.random.RandomState(42)
-    data_rng = rng.uniform(size=(7, 7, 3))
-    data_positive[1:-1, 2:-1, 1:] = data_rng[1:-1, 2:-1, 1:]
-    img_3d = Nifti1Image(data_positive, MNI_AFFINE)
-    # TODO: return img_3D directly and not a dict
-    return {"img": img_3d}
+def mni_3d_img():
+    """Fixture for a random 3D image in MNI space."""
+    return _mni_3d_img()
 
 
 @pytest.fixture()


Test patch:
diff --git a/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py b/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py
--- a/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py
+++ b/nilearn/plotting/tests/test_img_plotting/test_img_plotting.py
@@ -38,14 +38,14 @@
 PLOTTING_FUNCS_3D = ALL_PLOTTING_FUNCS.difference(PLOTTING_FUNCS_4D)
 
 
-def _test_data_with_nans(img):
+def _add_nans_to_img(img, mni_affine=MNI_AFFINE):
     """Add nans in test image data."""
     data = get_data(img)
     data[6, 5, 1] = np.nan
     data[1, 5, 2] = np.nan
     data[1, 3, 2] = np.nan
     data[6, 5, 2] = np.inf
-    return Nifti1Image(data, MNI_AFFINE)
+    return Nifti1Image(data, mni_affine)
 
 
 def test_mni152template_is_reordered():
@@ -57,24 +57,20 @@ def test_mni152template_is_reordered():
 
 
 @pytest.mark.parametrize("plot_func", PLOTTING_FUNCS_3D)
-def test_plot_functions_3d_default_params(
-    plot_func, testdata_3d_for_plotting, tmpdir
-):
+def test_plot_functions_3d_default_params(plot_func, mni_3d_img, tmpdir):
     """Smoke tests for 3D plotting functions with default parameters."""
     filename = str(tmpdir.join("temp.png"))
-    plot_func(testdata_3d_for_plotting["img"], output_file=filename)
+    plot_func(mni_3d_img, output_file=filename)
     plt.close()
 
 
 @pytest.mark.parametrize("plot_func", PLOTTING_FUNCS_3D)
 @pytest.mark.parametrize("cbar_tick_format", ["%f", "%i"])
-def test_cbar_tick_format(
-    plot_func, testdata_3d_for_plotting, cbar_tick_format, tmpdir
-):
+def test_cbar_tick_format(plot_func, mni_3d_img, cbar_tick_format, tmpdir):
     """Test different colorbar tick format with 3D plotting functions."""
     filename = str(tmpdir.join("temp.png"))
     plot_func(
-        testdata_3d_for_plotting["img"],
+        mni_3d_img,
         output_file=filename,
         colorbar=True,
         cbar_tick_format=cbar_tick_format,
@@ -84,7 +80,7 @@ def test_cbar_tick_format(
 
 @pytest.mark.parametrize("plot_func", PLOTTING_FUNCS_4D)
 def test_plot_functions_4d_default_params(
-    plot_func, testdata_3d_for_plotting, testdata_4d_for_plotting, tmpdir
+    plot_func, mni_3d_img, testdata_4d_for_plotting, tmpdir
 ):
     """Smoke-test for 4D plotting functions with default arguments."""
     filename = str(tmpdir.join("temp.png"))
@@ -92,7 +88,7 @@ def test_plot_functions_4d_default_params(
     if plot_func == plot_carpet:
         kwargs["mask_img"] = testdata_4d_for_plotting["img_mask"]
     else:
-        kwargs["bg_img"] = testdata_3d_for_plotting["img"]
+        kwargs["bg_img"] = mni_3d_img
     plot_func(testdata_4d_for_plotting["img_4d"], **kwargs)
     plt.close()
 
@@ -101,12 +97,10 @@ def test_plot_functions_4d_default_params(
     "plot_func", PLOTTING_FUNCS_3D.difference({plot_glass_brain})
 )
 @pytest.mark.parametrize("cut_coords", [None, 5, (5, 4, 3)])
-def test_plot_functions_mosaic_mode(
-    plot_func, cut_coords, testdata_3d_for_plotting
-):
+def test_plot_functions_mosaic_mode(plot_func, cut_coords, mni_3d_img):
     """Smoke-test for plotting functions in mosaic mode."""
     plot_func(
-        testdata_3d_for_plotting["img"],
+        mni_3d_img,
         display_mode="mosaic",
         title="mosaic mode",
         cut_coords=cut_coords,
@@ -115,7 +109,7 @@ def test_plot_functions_mosaic_mode(
 
 
 @pytest.mark.parametrize("plot_func", [plot_stat_map, plot_glass_brain])
-def test_plot_threshold_for_uint8(plot_func, testdata_3d_for_plotting):
+def test_plot_threshold_for_uint8(plot_func):
     """Mask was applied in [-threshold, threshold] which is problematic
     for uint8 data. See https://github.com/nilearn/nilearn/issues/611
     for more details.
@@ -171,7 +165,7 @@ def test_invalid_cut_coords_with_display_mode(
     plot_func,
     display_mode,
     cut_coords,
-    testdata_3d_for_plotting,
+    mni_3d_img,
     expected_error_message,
 ):
     """Tests for invalid combinations of cut_coords and display_mode."""
@@ -179,16 +173,16 @@ def test_invalid_cut_coords_with_display_mode(
         return
     with pytest.raises(ValueError, match=expected_error_message):
         plot_func(
-            testdata_3d_for_plotting["img"],
+            mni_3d_img,
             display_mode=display_mode,
             cut_coords=cut_coords,
         )
 
 
 @pytest.mark.parametrize("plot_func", PLOTTING_FUNCS_3D)
-def test_plot_with_nans(plot_func, testdata_3d_for_plotting):
+def test_plot_with_nans(plot_func, mni_3d_img):
     """Smoke test for plotting functions with nans in data image."""
-    plot_func(_test_data_with_nans(testdata_3d_for_plotting["img"]))
+    plot_func(_add_nans_to_img(mni_3d_img))
 
 
 @pytest.mark.parametrize(
@@ -202,27 +196,23 @@ def test_plotting_functions_with_cmaps(plot_func, cmap):
 
 
 @pytest.mark.parametrize("plot_func", [plot_anat, plot_roi, plot_stat_map])
-def test_plotting_functions_with_nans_in_bg_img(
-    plot_func, testdata_3d_for_plotting
-):
+def test_plotting_functions_with_nans_in_bg_img(plot_func, mni_3d_img):
     """Smoke test for plotting functions with nans in background image."""
-    bg_img = _test_data_with_nans(testdata_3d_for_plotting["img"])
+    bg_img = _add_nans_to_img(mni_3d_img)
     if plot_func == plot_anat:
         plot_func(bg_img)
     else:
-        plot_func(testdata_3d_for_plotting["img"], bg_img=bg_img)
+        plot_func(mni_3d_img, bg_img=bg_img)
     plt.close()
 
 
 @pytest.mark.parametrize("plot_func", [plot_stat_map, plot_anat, plot_img])
-def test_plotting_functions_with_display_mode_tiled(
-    plot_func, testdata_3d_for_plotting
-):
+def test_plotting_functions_with_display_mode_tiled(plot_func, mni_3d_img):
     """Smoke test for plotting functions with tiled display mode."""
     if plot_func == plot_anat:
         plot_func(display_mode="tiled")
     else:
-        plot_func(testdata_3d_for_plotting["img"], display_mode="tiled")
+        plot_func(mni_3d_img, display_mode="tiled")
     plt.close()
 
 
@@ -237,10 +227,8 @@ def test_plotting_functions_with_display_mode_tiled(
         plot_glass_brain,
     ],
 )
-def test_plotting_functions_radiological_view(
-    testdata_3d_for_plotting, plotting_func
-):
+def test_plotting_functions_radiological_view(mni_3d_img, plotting_func):
     """Smoke test for radiological view."""
-    result = plotting_func(testdata_3d_for_plotting["img"], radiological=True)
+    result = plotting_func(mni_3d_img, radiological=True)
     assert result.axes.get("y").radiological is True
     plt.close()
diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py b/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py
--- a/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py
+++ b/nilearn/plotting/tests/test_img_plotting/test_plot_anat.py
@@ -33,10 +33,10 @@ def test_plot_anat_colorbar(anat_img, display_mode, cbar_tick_format, tmpdir):
     plt.close()
 
 
-def test_plot_anat_3d_img(testdata_3d_for_plotting, tmpdir):
+def test_plot_anat_3d_img(mni_3d_img, tmpdir):
     """Smoke test for plot_anat."""
     filename = str(tmpdir.join("test.png"))
-    slicer = plot_anat(testdata_3d_for_plotting["img"], dim="auto")
+    slicer = plot_anat(mni_3d_img, dim="auto")
     slicer.savefig(filename)
     plt.close()
 
diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_glass_brain.py b/nilearn/plotting/tests/test_img_plotting/test_plot_glass_brain.py
--- a/nilearn/plotting/tests/test_img_plotting/test_plot_glass_brain.py
+++ b/nilearn/plotting/tests/test_img_plotting/test_plot_glass_brain.py
@@ -9,21 +9,25 @@
 from nilearn.plotting import plot_glass_brain
 
 
-def test_plot_glass_brain(testdata_3d_for_plotting, tmpdir):
+def test_plot_glass_brain(mni_3d_img):
     """Smoke tests for plot_glass_brain with colorbar and negative values."""
-    img = testdata_3d_for_plotting["img"]
-    plot_glass_brain(img, colorbar=True, resampling_interpolation="nearest")
+    plot_glass_brain(
+        mni_3d_img, colorbar=True, resampling_interpolation="nearest"
+    )
     # test plot_glass_brain with negative values
     plot_glass_brain(
-        img, colorbar=True, plot_abs=False, resampling_interpolation="nearest"
+        mni_3d_img,
+        colorbar=True,
+        plot_abs=False,
+        resampling_interpolation="nearest",
     )
 
 
-def test_plot_glass_brain_file_output(testdata_3d_for_plotting, tmpdir):
+def test_plot_glass_brain_file_output(mni_3d_img, tmpdir):
     """Smoke-test for hemispheric glass brain with file output."""
     filename = str(tmpdir.join("test.png"))
     plot_glass_brain(
-        testdata_3d_for_plotting["img"],
+        mni_3d_img,
         output_file=filename,
         display_mode="lzry",
     )
@@ -89,9 +93,9 @@ def test_add_markers_using_plot_glass_brain():
         )
 
 
-def test_plot_glass_brain_colorbar_having_nans(testdata_3d_for_plotting):
+def test_plot_glass_brain_colorbar_having_nans(mni_3d_img):
     """Smoke-test for plot_glass_brain and nans in the data image."""
-    data = get_data(testdata_3d_for_plotting["img"])
+    data = get_data(mni_3d_img)
     data[6, 5, 2] = np.inf
     plot_glass_brain(Nifti1Image(data, np.eye(4)), colorbar=True)
     plt.close()
diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_img.py b/nilearn/plotting/tests/test_img_plotting/test_plot_img.py
--- a/nilearn/plotting/tests/test_img_plotting/test_plot_img.py
+++ b/nilearn/plotting/tests/test_img_plotting/test_plot_img.py
@@ -29,24 +29,22 @@ def _testdata_3d_for_plotting_for_resampling(img, binary):
     return Nifti1Image(data, affine)
 
 
-def test_display_methods(testdata_3d_for_plotting):
+def test_display_methods(mni_3d_img):
     """Tests display methods."""
-    img = testdata_3d_for_plotting["img"]
-    display = plot_img(img)
-    display.add_overlay(img, threshold=0)
-    display.add_edges(img, color="c")
+    display = plot_img(mni_3d_img)
+    display.add_overlay(mni_3d_img, threshold=0)
+    display.add_edges(mni_3d_img, color="c")
     display.add_contours(
-        img, contours=2, linewidth=4, colors=["limegreen", "yellow"]
+        mni_3d_img, contours=2, linewidth=4, colors=["limegreen", "yellow"]
     )
 
 
-def test_plot_with_axes_or_figure(testdata_3d_for_plotting):
+def test_plot_with_axes_or_figure(mni_3d_img):
     """Smoke tests for plot_img with providing figure or Axes."""
-    img = testdata_3d_for_plotting["img"]
     figure = plt.figure()
-    plot_img(img, figure=figure)
+    plot_img(mni_3d_img, figure=figure)
     ax = plt.subplot(111)
-    plot_img(img, axes=ax)
+    plot_img(mni_3d_img, axes=ax)
     plt.close()
 
 
@@ -60,7 +58,7 @@ def test_plot_empty_slice(mni_affine):
 
 
 @pytest.mark.parametrize("display_mode", ["x", "y", "z"])
-def test_plot_img_with_auto_cut_coords(display_mode, testdata_3d_for_plotting):
+def test_plot_img_with_auto_cut_coords(display_mode):
     """Smoke test for plot_img with cut_coords set in auto mode."""
     data = np.zeros((20, 20, 20))
     data[3:-3, 3:-3, 3:-3] = 1
@@ -70,11 +68,9 @@ def test_plot_img_with_auto_cut_coords(display_mode, testdata_3d_for_plotting):
 
 
 @pytest.mark.parametrize("binary_img", [True, False])
-def test_plot_img_with_resampling(binary_img, testdata_3d_for_plotting):
+def test_plot_img_with_resampling(binary_img, mni_3d_img):
     """Tests for plot_img with resampling of the data image."""
-    img = _testdata_3d_for_plotting_for_resampling(
-        testdata_3d_for_plotting["img"], binary_img
-    )
+    img = _testdata_3d_for_plotting_for_resampling(mni_3d_img, binary_img)
     if binary_img:
         assert _is_binary_niimg(img)
     else:
@@ -88,12 +84,11 @@ def test_plot_img_with_resampling(binary_img, testdata_3d_for_plotting):
     plt.close()
 
 
-def test_display_methods_with_display_mode_tiled(testdata_3d_for_plotting):
+def test_display_methods_with_display_mode_tiled(mni_3d_img):
     """Smoke tests for display methods with tiled display mode."""
-    img = testdata_3d_for_plotting["img"]
-    display = plot_img(img, display_mode="tiled")
-    display.add_overlay(img, threshold=0)
-    display.add_edges(img, color="c")
+    display = plot_img(mni_3d_img, display_mode="tiled")
+    display.add_overlay(mni_3d_img, threshold=0)
+    display.add_edges(mni_3d_img, color="c")
     display.add_contours(
-        img, contours=2, linewidth=4, colors=["limegreen", "yellow"]
+        mni_3d_img, contours=2, linewidth=4, colors=["limegreen", "yellow"]
     )
diff --git a/nilearn/plotting/tests/test_img_plotting/test_plot_stat_map.py b/nilearn/plotting/tests/test_img_plotting/test_plot_stat_map.py
--- a/nilearn/plotting/tests/test_img_plotting/test_plot_stat_map.py
+++ b/nilearn/plotting/tests/test_img_plotting/test_plot_stat_map.py
@@ -12,12 +12,12 @@
 from nilearn.plotting.find_cuts import find_cut_slices
 
 
-def test_plot_stat_map_bad_input(testdata_3d_for_plotting, tmpdir):
+def test_plot_stat_map_bad_input(mni_3d_img, tmpdir):
     """Test for bad input arguments (cf. #510)."""
     filename = str(tmpdir.join("temp.png"))
     ax = plt.subplot(111, rasterized=True)
     plot_stat_map(
-        testdata_3d_for_plotting["img"],
+        mni_3d_img,
         symmetric_cbar=True,
         output_file=filename,
         axes=ax,
@@ -29,14 +29,12 @@ def test_plot_stat_map_bad_input(testdata_3d_for_plotting, tmpdir):
 @pytest.mark.parametrize(
     "params", [{}, {"display_mode": "x", "cut_coords": 3}]
 )
-def test_save_plot_stat_map(params, testdata_3d_for_plotting, tmpdir):
+def test_save_plot_stat_map(params, mni_3d_img, tmpdir):
     """Test saving figure to file in different ways."""
     filename = str(tmpdir.join("test.png"))
-    display = plot_stat_map(
-        testdata_3d_for_plotting["img"], output_file=filename, **params
-    )
+    display = plot_stat_map(mni_3d_img, output_file=filename, **params)
     assert display is None
-    display = plot_stat_map(testdata_3d_for_plotting["img"], **params)
+    display = plot_stat_map(mni_3d_img, **params)
     display.savefig(filename)
     plt.close()
 
@@ -46,7 +44,7 @@ def test_save_plot_stat_map(params, testdata_3d_for_plotting, tmpdir):
     [("ortho", (80, -120, -60)), ("y", 2), ("yx", None)],
 )
 def test_plot_stat_map_cut_coords_and_display_mode(
-    display_mode, cut_coords, testdata_3d_for_plotting
+    display_mode, cut_coords, mni_3d_img
 ):
     """Smoke-tests for plot_stat_map.
 
@@ -54,17 +52,17 @@ def test_plot_stat_map_cut_coords_and_display_mode(
     and `display_mode`.
     """
     plot_stat_map(
-        testdata_3d_for_plotting["img"],
+        mni_3d_img,
         display_mode=display_mode,
         cut_coords=cut_coords,
     )
     plt.close()
 
 
-def test_plot_stat_map_with_masked_image(testdata_3d_for_plotting, mni_affine):
+def test_plot_stat_map_with_masked_image(mni_3d_img, mni_affine):
     """Smoke test coordinate finder with mask."""
     masked_img = Nifti1Image(
-        np.ma.masked_equal(get_data(testdata_3d_for_plotting["img"]), 0),
+        np.ma.masked_equal(get_data(mni_3d_img), 0),
         mni_affine,
     )
     plot_stat_map(masked_img, display_mode="x")
@@ -125,12 +123,9 @@ def test_plot_stat_map_threshold_for_affine_with_rotation():
         {"colorbar": False},
     ],
 )
-def test_plot_stat_map_colorbar_variations(
-    params, testdata_3d_for_plotting, mni_affine
-):
+def test_plot_stat_map_colorbar_variations(params, mni_3d_img, mni_affine):
     """Smoke test for plot_stat_map with different colorbar configurations."""
-    img_positive = testdata_3d_for_plotting["img"]
-    data_positive = get_data(img_positive)
+    data_positive = get_data(mni_3d_img)
     rng = np.random.RandomState(42)
     data_negative = -data_positive
     data_heterogeneous = data_positive * rng.standard_normal(
@@ -138,7 +133,7 @@ def test_plot_stat_map_colorbar_variations(
     )
     img_negative = Nifti1Image(data_negative, mni_affine)
     img_heterogeneous = Nifti1Image(data_heterogeneous, mni_affine)
-    for img in [img_positive, img_negative, img_heterogeneous]:
+    for img in [mni_3d_img, img_negative, img_heterogeneous]:
         plot_stat_map(img, cut_coords=(80, -120, -60), **params)
         plt.close()
 
@@ -179,7 +174,7 @@ def test_outlier_cut_coords():
     plot_stat_map(img, display_mode="z", cut_coords=cuts[-4:], bg_img=bg_img)
 
 
-def test_plotting_functions_with_dim_invalid_input(testdata_3d_for_plotting):
+def test_plotting_functions_with_dim_invalid_input(mni_3d_img):
     """Test whether error raises with bad error to input."""
     with pytest.raises(ValueError):
-        plot_stat_map(testdata_3d_for_plotting["img"], dim="-10")
+        plot_stat_map(mni_3d_img, dim="-10")
diff --git a/nilearn/plotting/tests/test_surf_plotting.py b/nilearn/plotting/tests/test_surf_plotting.py
--- a/nilearn/plotting/tests/test_surf_plotting.py
+++ b/nilearn/plotting/tests/test_surf_plotting.py
@@ -5,7 +5,6 @@
 import unittest.mock as mock
 
 import matplotlib.pyplot as plt
-import nibabel
 import numpy as np
 import pytest
 from matplotlib.figure import Figure
@@ -13,7 +12,6 @@
 
 from nilearn.datasets import fetch_surf_fsaverage
 from nilearn.plotting.displays import PlotlySurfaceFigure
-from nilearn.plotting.img_plotting import MNI152TEMPLATE
 from nilearn.plotting.surf_plotting import (
     VALID_HEMISPHERES,
     VALID_VIEWS,
@@ -820,18 +818,8 @@ def test_plot_surf_roi_error(engine):
         plot_surf_roi(mesh, roi_map=roi_idx, engine=engine)
 
 
-def _generate_img():
-    mni_affine = MNI152TEMPLATE.get_affine()
-    data_positive = np.zeros((7, 7, 3))
-    rng = np.random.RandomState(42)
-    data_rng = rng.uniform(size=(7, 7, 3))
-    data_positive[1:-1, 2:-1, 1:] = data_rng[1:-1, 2:-1, 1:]
-    nii = nibabel.Nifti1Image(data_positive, mni_affine)
-    return nii
-
-
-def test_plot_img_on_surf_hemispheres_and_orientations():
-    nii = _generate_img()
+def test_plot_img_on_surf_hemispheres_and_orientations(mni_3d_img):
+    nii = mni_3d_img
     # Check that all combinations of 1D or 2D hemis and orientations work.
     plot_img_on_surf(nii, hemispheres=['right'], views=['lateral'])
     plot_img_on_surf(nii, hemispheres=['left', 'right'], views=['lateral'])
@@ -847,8 +835,8 @@ def test_plot_img_on_surf_hemispheres_and_orientations():
                      views=[(210.0, 90.0), (15.0, -45.0)])
 
 
-def test_plot_img_on_surf_colorbar():
-    nii = _generate_img()
+def test_plot_img_on_surf_colorbar(mni_3d_img):
+    nii = mni_3d_img
     plot_img_on_surf(nii, hemispheres=['right'], views=['lateral'],
                      colorbar=True, vmax=5, threshold=3)
     plot_img_on_surf(nii, hemispheres=['right'], views=['lateral'],
@@ -859,14 +847,14 @@ def test_plot_img_on_surf_colorbar():
                      colorbar=True, cmap='roy_big_bl', vmax=2)
 
 
-def test_plot_img_on_surf_inflate():
-    nii = _generate_img()
+def test_plot_img_on_surf_inflate(mni_3d_img):
+    nii = mni_3d_img
     plot_img_on_surf(nii, hemispheres=['right'], views=['lateral'],
                      inflate=True)
 
 
-def test_plot_img_on_surf_surf_mesh():
-    nii = _generate_img()
+def test_plot_img_on_surf_surf_mesh(mni_3d_img):
+    nii = mni_3d_img
     plot_img_on_surf(nii, hemispheres=['right', 'left'], views=['lateral'])
     plot_img_on_surf(nii, hemispheres=['right', 'left'], views=['lateral'],
                      surf_mesh='fsaverage5')
@@ -875,9 +863,9 @@ def test_plot_img_on_surf_surf_mesh():
                      surf_mesh=surf_mesh)
 
 
-def test_plot_img_on_surf_with_invalid_orientation():
+def test_plot_img_on_surf_with_invalid_orientation(mni_3d_img):
     kwargs = {"hemisphere": ["right"], "inflate": True}
-    nii = _generate_img()
+    nii = mni_3d_img
     with pytest.raises(ValueError):
         plot_img_on_surf(nii, views=['latral'], **kwargs)
     with pytest.raises(ValueError):
@@ -888,8 +876,8 @@ def test_plot_img_on_surf_with_invalid_orientation():
         plot_img_on_surf(nii, views=['medial', {'a': 'a'}], **kwargs)
 
 
-def test_plot_img_on_surf_with_invalid_hemisphere():
-    nii = _generate_img()
+def test_plot_img_on_surf_with_invalid_hemisphere(mni_3d_img):
+    nii = mni_3d_img
     with pytest.raises(ValueError):
         plot_img_on_surf(
             nii, views=['lateral'], inflate=True, hemispheres=["lft]"]
@@ -907,8 +895,8 @@ def test_plot_img_on_surf_with_invalid_hemisphere():
         )
 
 
-def test_plot_img_on_surf_with_figure_kwarg():
-    nii = _generate_img()
+def test_plot_img_on_surf_with_figure_kwarg(mni_3d_img):
+    nii = mni_3d_img
     with pytest.raises(ValueError):
         plot_img_on_surf(
             nii,
@@ -918,8 +906,8 @@ def test_plot_img_on_surf_with_figure_kwarg():
         )
 
 
-def test_plot_img_on_surf_with_axes_kwarg():
-    nii = _generate_img()
+def test_plot_img_on_surf_with_axes_kwarg(mni_3d_img):
+    nii = mni_3d_img
     with pytest.raises(ValueError):
         plot_img_on_surf(
             nii,
@@ -930,8 +918,8 @@ def test_plot_img_on_surf_with_axes_kwarg():
         )
 
 
-def test_plot_img_on_surf_title():
-    nii = _generate_img()
+def test_plot_img_on_surf_title(mni_3d_img):
+    nii = mni_3d_img
     title = "Title"
     fig, axes = plot_img_on_surf(
         nii, hemispheres=['right'], views=['lateral']
@@ -944,8 +932,8 @@ def test_plot_img_on_surf_title():
     assert fig._suptitle.get_text() == title, "Title text not assigned."
 
 
-def test_plot_img_on_surf_output_file(tmp_path):
-    nii = _generate_img()
+def test_plot_img_on_surf_output_file(tmp_path, mni_3d_img):
+    nii = mni_3d_img
     fname = tmp_path / 'tmp.png'
     return_value = plot_img_on_surf(nii,
                                     hemispheres=['right'],
diff --git a/nilearn/reporting/tests/test_glm_reporter.py b/nilearn/reporting/tests/test_glm_reporter.py
--- a/nilearn/reporting/tests/test_glm_reporter.py
+++ b/nilearn/reporting/tests/test_glm_reporter.py
@@ -1,6 +1,5 @@
 import warnings
 
-import nibabel as nib
 import numpy as np
 import pandas as pd
 import pytest
@@ -219,28 +218,10 @@ def test_make_headings_with_contrasts_none_title_custom():
     assert actual_output == expected_output
 
 
-def _generate_img():
-    mni_affine = np.array(
-        [
-            [-2.0, 0.0, 0.0, 90.0],
-            [0.0, 2.0, 0.0, -126.0],
-            [0.0, 0.0, 2.0, -72.0],
-            [0.0, 0.0, 0.0, 1.0],
-        ]
-    )
-
-    data_positive = np.zeros((7, 7, 3))
-    rng = np.random.RandomState(42)
-    data_rng = rng.rand(7, 7, 3)
-    data_positive[1:-1, 2:-1, 1:] = data_rng[1:-1, 2:-1, 1:]
-
-    return nib.Nifti1Image(data_positive, mni_affine)
-
-
 @pytest.mark.parametrize("cut_coords", [None, (5, 4, 3)])
-def test_stat_map_to_svg_slice_z(cut_coords):
+def test_stat_map_to_svg_slice_z(mni_3d_img, cut_coords):
     with InTemporaryDirectory():
-        img = _generate_img()
+        img = mni_3d_img
         table_details = pd.DataFrame.from_dict({"junk": 0}, orient="index")
         glmr._stat_map_to_svg(
             stat_img=img,
@@ -253,9 +234,9 @@ def test_stat_map_to_svg_slice_z(cut_coords):
 
 
 @pytest.mark.parametrize("cut_coords", [None, (5, 4, 3)])
-def test_stat_map_to_svg_glass_z(cut_coords):
+def test_stat_map_to_svg_glass_z(mni_3d_img, cut_coords):
     with InTemporaryDirectory():
-        img = _generate_img()
+        img = mni_3d_img
         table_details = pd.DataFrame.from_dict({"junk": 0}, orient="index")
         glmr._stat_map_to_svg(
             stat_img=img,
@@ -268,9 +249,9 @@ def test_stat_map_to_svg_glass_z(cut_coords):
 
 
 @pytest.mark.parametrize("cut_coords", [None, (5, 4, 3)])
-def test_stat_map_to_svg_invalid_plot_type(cut_coords):
+def test_stat_map_to_svg_invalid_plot_type(mni_3d_img, cut_coords):
     with InTemporaryDirectory():
-        img = _generate_img()
+        img = mni_3d_img
         expected_error = ValueError(
             "Invalid plot type provided. Acceptable options are"
             "'slice' or 'glass'."