def test_open_report(tmp_path): """Test the open_report function.""" tempdir = str(tmp_path) hdf5 = op.join(tempdir, 'report.h5') # Test creating a new report through the open_report function fig1 = _get_example_figures()[0] with open_report(hdf5, subjects_dir=subjects_dir) as report: assert report.subjects_dir == subjects_dir assert report.fname == hdf5 report.add_figure(fig=fig1, title='evoked response') # Exiting the context block should have triggered saving to HDF5 assert op.exists(hdf5) # Load the HDF5 version of the report and check equivalence report2 = open_report(hdf5) assert report2.fname == hdf5 assert report2.subjects_dir == report.subjects_dir assert report2.html == report.html assert report2.__getstate__() == report.__getstate__() assert '_fname' not in report2.__getstate__() # Check parameters when loading a report pytest.raises(ValueError, open_report, hdf5, foo='bar') # non-existing pytest.raises(ValueError, open_report, hdf5, subjects_dir='foo') open_report(hdf5, subjects_dir=subjects_dir) # This should work # Check that the context manager doesn't swallow exceptions with pytest.raises(ZeroDivisionError): with open_report(hdf5, subjects_dir=subjects_dir) as report: 1 / 0
def test_render_mne_qt_browser(tmp_path, browser_backend): """Test adding a mne_qt_browser (and matplotlib) raw plot.""" report = Report() info = create_info(1, 1000., 'eeg') data = np.zeros((1, 1000)) raw = RawArray(data, info) fig = raw.plot() name = fig.__class__.__name__ if browser_backend.name == 'matplotlib': assert 'MNEBrowseFigure' in name else: assert 'MNEQtBrowser' in name or 'PyQtGraphBrowser' in name report.add_figure(fig, title='raw')
def test_add_custom_js(tmp_path): """Test adding custom JavaScript to the report.""" tempdir = str(tmp_path) fname = op.join(tempdir, 'report.html') fig = plt.figure() # Empty figure report = Report() report.add_figure(fig=fig, title='Test section') custom_js = ('function hello() {\n' ' alert("Hello, report!");\n' '}') report.add_custom_js(js=custom_js) assert custom_js in report.include report.save(fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert custom_js in html
def test_add_custom_css(tmp_path): """Test adding custom CSS rules to the report.""" tempdir = str(tmp_path) fname = op.join(tempdir, 'report.html') fig = plt.figure() # Empty figure report = Report() report.add_figure(fig=fig, title='Test section') custom_css = '.report_custom { color: red; }' report.add_custom_css(css=custom_css) assert custom_css in report.include report.save(fname, open_browser=False) html = Path(fname).read_text(encoding='utf-8') assert custom_css in html
def test_render_add_sections(renderer, tmp_path): """Test adding figures/images to section.""" tempdir = str(tmp_path) report = Report(subjects_dir=subjects_dir) # Check add_figure functionality fig = plt.plot([1, 2], [1, 2])[0].figure report.add_figure(fig=fig, title='evoked response', image_format='svg') assert 'caption' not in report._content[-1].html report.add_figure(fig=fig, title='evoked with caption', caption='descr') assert 'caption' in report._content[-1].html # Check add_image with png img_fname = op.join(tempdir, 'testimage.png') fig.savefig(img_fname) report.add_image(image=img_fname, title='evoked response') with pytest.raises(FileNotFoundError, match='No such file or directory'): report.add_image(image='foobar.xxx', title='H') evoked = read_evokeds(evoked_fname, condition='Left Auditory', baseline=(-0.2, 0.0)) fig = plot_alignment(evoked.info, trans_fname, subject='sample', subjects_dir=subjects_dir) report.add_figure(fig=fig, title='random image') assert (repr(report)) fname = op.join(str(tmp_path), 'test.html') report.save(fname, open_browser=False) assert len(report) == 4
def test_multiple_figs(tmpdir): """Test adding a slider with a series of figures to a Report.""" tempdir = str(tmpdir) report = Report(info_fname=raw_fname, subject='sample', subjects_dir=subjects_dir) figs = _get_example_figures() report.add_figure(fig=figs, title='my title') assert report._content[0].name == 'my title' report.save(op.join(tempdir, 'report.html'), open_browser=False) with pytest.raises(ValueError): report.add_figure(fig=figs, title='title', caption=['wug']) with pytest.raises(ValueError, match='Number of captions.*must be equal to.*figures'): report.add_figure(fig=figs, title='title', caption='wug') # Smoke test that SVG with unicode can be added report = Report() fig, ax = plt.subplots() ax.set_xlabel('µ') report.add_figure(fig=[fig] * 2, title='title', image_format='svg')
def test_render_report(renderer_pyvistaqt, tmp_path, invisible_fig): """Test rendering *.fif files for mne report.""" tempdir = str(tmp_path) raw_fname_new = op.join(tempdir, 'temp_raw.fif') raw_fname_new_bids = op.join(tempdir, 'temp_meg.fif') ms_fname_new = op.join(tempdir, 'temp_ms_raw.fif') event_fname_new = op.join(tempdir, 'temp_raw-eve.fif') cov_fname_new = op.join(tempdir, 'temp_raw-cov.fif') proj_fname_new = op.join(tempdir, 'temp_ecg-proj.fif') fwd_fname_new = op.join(tempdir, 'temp_raw-fwd.fif') inv_fname_new = op.join(tempdir, 'temp_raw-inv.fif') nirs_fname_new = op.join(tempdir, 'temp_raw-nirs.snirf') for a, b in [[raw_fname, raw_fname_new], [raw_fname, raw_fname_new_bids], [ms_fname, ms_fname_new], [events_fname, event_fname_new], [cov_fname, cov_fname_new], [ecg_proj_fname, proj_fname_new], [fwd_fname, fwd_fname_new], [inv_fname, inv_fname_new], [nirs_fname, nirs_fname_new]]: shutil.copyfile(a, b) # create and add -epo.fif and -ave.fif files epochs_fname = op.join(tempdir, 'temp-epo.fif') evoked_fname = op.join(tempdir, 'temp-ave.fif') # Speed it up by picking channels raw = read_raw_fif(raw_fname_new) raw.pick_channels(['MEG 0111', 'MEG 0121', 'EEG 001', 'EEG 002']) raw.del_proj() raw.set_eeg_reference(projection=True).load_data() epochs = Epochs(raw, read_events(events_fname), 1, -0.2, 0.2) epochs.save(epochs_fname, overwrite=True) # This can take forever, so let's make it fast # Also, make sure crop range is wide enough to avoid rendering bug evoked = epochs.average() with pytest.warns(RuntimeWarning, match='tmax is not in Evoked'): evoked.crop(0.1, 0.2) evoked.save(evoked_fname) report = Report(info_fname=raw_fname_new, subjects_dir=subjects_dir, projs=False, image_format='png') with pytest.warns(RuntimeWarning, match='Cannot render MRI'): report.parse_folder(data_path=tempdir, on_error='raise', n_time_points_evokeds=2, raw_butterfly=False, stc_plot_kwargs=stc_plot_kwargs, topomap_kwargs=topomap_kwargs) assert repr(report) # Check correct paths and filenames fnames = glob.glob(op.join(tempdir, '*.fif')) fnames.extend(glob.glob(op.join(tempdir, '*.snirf'))) titles = [op.basename(x) for x in fnames if not x.endswith('-ave.fif')] titles.append(f'{op.basename(evoked_fname)}: {evoked.comment}') content_names = [element.name for element in report._content] for title in titles: assert title in content_names assert (''.join(report.html).find(title) != -1) assert len(report._content) == len(fnames) # Check saving functionality report.data_path = tempdir fname = op.join(tempdir, 'report.html') report.save(fname=fname, open_browser=False) assert (op.isfile(fname)) html = Path(fname).read_text(encoding='utf-8') # Evoked in `evoked_fname` assert f'{op.basename(evoked_fname)}: {evoked.comment}' in html assert 'Topographies' in html assert 'Global field power' in html assert len(report._content) == len(fnames) # Check saving same report to new filename report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False) assert (op.isfile(op.join(tempdir, 'report2.html'))) # Check overwriting file report.save(fname=op.join(tempdir, 'report.html'), open_browser=False, overwrite=True) assert (op.isfile(op.join(tempdir, 'report.html'))) # Check pattern matching with multiple patterns pattern = ['*proj.fif', '*eve.fif'] with pytest.warns(RuntimeWarning, match='Cannot render MRI'): report.parse_folder(data_path=tempdir, pattern=pattern, raw_butterfly=False) assert (repr(report)) fnames = glob.glob(op.join(tempdir, '*.raw')) + \ glob.glob(op.join(tempdir, '*.raw')) content_names = [element.name for element in report._content] for fname in fnames: assert (op.basename(fname) in [op.basename(x) for x in content_names]) assert (''.join(report.html).find(op.basename(fname)) != -1) with pytest.raises(ValueError, match='Invalid value'): Report(image_format='foo') with pytest.raises(ValueError, match='Invalid value'): Report(image_format=None) # ndarray support smoke test report.add_figure(fig=np.zeros((2, 3, 3)), title='title') with pytest.raises(TypeError, match='It seems you passed a path'): report.add_figure(fig='foo', title='title')