File: test_logging.py

package info (click to toggle)
python-mne 1.3.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 100,172 kB
  • sloc: python: 166,349; pascal: 3,602; javascript: 1,472; sh: 334; makefile: 236
file content (243 lines) | stat: -rw-r--r-- 8,499 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import os
import os.path as op
import re
import warnings

import numpy as np
import pytest

from mne import read_evokeds, Epochs, create_info
from mne.io import read_raw_fif, RawArray
from mne.utils import (warn, set_log_level, set_log_file, filter_out_warnings,
                       verbose, _get_call_line, use_log_level, catch_logging,
                       logger, check)
from mne.utils._logging import _frame_info

base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
fname_raw = op.join(base_dir, 'test_raw.fif')
fname_evoked = op.join(base_dir, 'test-ave.fif')
fname_log = op.join(base_dir, 'test-ave.log')
fname_log_2 = op.join(base_dir, 'test-ave-2.log')


@verbose
def _fun(verbose=None):
    logger.debug('Test')


def test_frame_info(capsys, monkeypatch):
    """Test _frame_info."""
    stack = _frame_info(100)
    assert 2 < len(stack) < 100
    this, pytest_line = stack[:2]
    assert re.match('^test_logging:[1-9][0-9]$', this) is not None, this
    assert 'pytest' in pytest_line
    capsys.readouterr()
    with use_log_level('debug', add_frames=4):
        _fun()
    out, _ = capsys.readouterr()
    out = out.replace('\n', ' ')
    assert re.match(
        '.*pytest'
        '.*test_logging:[2-9][0-9] '
        '.*test_logging:[1-9][0-9] :.*Test', out) is not None, this
    monkeypatch.setattr('inspect.currentframe', lambda: None)
    assert _frame_info(1) == ['unknown']


def test_how_to_deal_with_warnings():
    """Test filter some messages out of warning records."""
    with pytest.warns(UserWarning, match='bb') as w:
        warnings.warn("aa warning", UserWarning)
        warnings.warn("bb warning", UserWarning)
        warnings.warn("bb warning", RuntimeWarning)
        warnings.warn("aa warning", UserWarning)
    filter_out_warnings(w, category=UserWarning, match='aa')
    filter_out_warnings(w, category=RuntimeWarning)
    assert len(w) == 1


def clean_lines(lines=[]):
    """Scrub filenames for checking logging output (in test_logging)."""
    return [line if 'Reading ' not in line else 'Reading test file'
            for line in lines]


def test_logging_options(tmp_path):
    """Test logging (to file)."""
    with use_log_level(None):  # just ensure it's set back
        with pytest.raises(ValueError, match="Invalid value for the 'verbose"):
            set_log_level('foo')
        tempdir = str(tmp_path)
        test_name = op.join(tempdir, 'test.log')
        with open(fname_log, 'r') as old_log_file:
            # [:-1] used to strip an extra "No baseline correction applied"
            old_lines = clean_lines(old_log_file.readlines())
            old_lines.pop(-1)
        with open(fname_log_2, 'r') as old_log_file_2:
            old_lines_2 = clean_lines(old_log_file_2.readlines())
            old_lines_2.pop(14)
            old_lines_2.pop(-1)

        if op.isfile(test_name):
            os.remove(test_name)
        # test it one way (printing default off)
        set_log_file(test_name)
        set_log_level('WARNING')
        # should NOT print
        evoked = read_evokeds(fname_evoked, condition=1)
        with open(test_name) as fid:
            assert (fid.readlines() == [])
        # should NOT print
        evoked = read_evokeds(fname_evoked, condition=1, verbose=False)
        with open(test_name) as fid:
            assert (fid.readlines() == [])
        # should NOT print
        evoked = read_evokeds(fname_evoked, condition=1, verbose='WARNING')
        with open(test_name) as fid:
            assert (fid.readlines() == [])
        # SHOULD print
        evoked = read_evokeds(fname_evoked, condition=1, verbose=True)
        with open(test_name, 'r') as new_log_file:
            new_lines = clean_lines(new_log_file.readlines())
        assert new_lines == old_lines
        set_log_file(None)  # Need to do this to close the old file
        os.remove(test_name)

        # now go the other way (printing default on)
        set_log_file(test_name)
        set_log_level('INFO')
        # should NOT print
        evoked = read_evokeds(fname_evoked, condition=1, verbose='WARNING')
        with open(test_name) as fid:
            assert (fid.readlines() == [])
        # should NOT print
        evoked = read_evokeds(fname_evoked, condition=1, verbose=False)
        with open(test_name) as fid:
            assert (fid.readlines() == [])
        # SHOULD print
        evoked = read_evokeds(fname_evoked, condition=1)
        with open(test_name, 'r') as new_log_file:
            new_lines = clean_lines(new_log_file.readlines())
        assert new_lines == old_lines
        # check to make sure appending works (and as default, raises a warning)
        set_log_file(test_name, overwrite=False)
        with pytest.warns(RuntimeWarning, match='appended to the file'):
            set_log_file(test_name)
        evoked = read_evokeds(fname_evoked, condition=1)
        with open(test_name, 'r') as new_log_file:
            new_lines = clean_lines(new_log_file.readlines())
        assert new_lines == old_lines_2

        # make sure overwriting works
        set_log_file(test_name, overwrite=True)
        # this line needs to be called to actually do some logging
        evoked = read_evokeds(fname_evoked, condition=1)
        del evoked
        with open(test_name, 'r') as new_log_file:
            new_lines = clean_lines(new_log_file.readlines())
        assert new_lines == old_lines
    with catch_logging() as log:
        pass
    assert log.getvalue() == ''


@pytest.mark.parametrize('verbose', (True, False))
def test_verbose_method(verbose):
    """Test for gh-8772."""
    # raw
    raw = read_raw_fif(fname_raw, verbose=verbose)
    with catch_logging() as log:
        raw.load_data(verbose=True)
    log = log.getvalue()
    assert 'Reading 0 ... 14399' in log
    with catch_logging() as log:
        raw.load_data(verbose=False)
    log = log.getvalue()
    assert log == ''
    # epochs
    events = np.array([[raw.first_samp + 200, 0, 1]], int)
    epochs = Epochs(raw, events, verbose=verbose)
    with catch_logging() as log:
        epochs.drop_bad(verbose=True)
    log = log.getvalue()
    assert '0 bad epochs dropped' in log
    epochs = Epochs(raw, events, verbose=verbose)
    with catch_logging() as log:
        epochs.drop_bad(verbose=False)
    log = log.getvalue()
    assert log == ''


def test_warn(capsys, tmp_path, monkeypatch):
    """Test the smart warn() function."""
    with pytest.warns(RuntimeWarning, match='foo'):
        warn('foo')
    captured = capsys.readouterr()
    assert captured.out == ''  # gh-5592
    assert captured.err == ''  # this is because pytest.warns took it already
    # test ignore_namespaces
    bad_name = tmp_path / 'bad.fif'
    raw = RawArray(np.zeros((1, 1)), create_info(1, 1000., 'eeg'))
    with pytest.warns(RuntimeWarning, match='filename') as ws:
        raw.save(bad_name)
    assert len(ws) == 1
    assert 'test_logging.py' in ws[0].filename  # this file (it's in tests/)

    def warn_wrap(msg):
        warn(msg, ignore_namespaces=())

    monkeypatch.setattr(check, 'warn', warn_wrap)
    with pytest.warns(RuntimeWarning, match='filename') as ws:
        raw.save(bad_name, overwrite=True)

    assert len(ws) == 1
    assert 'test_logging.py' not in ws[0].filename  # this file
    assert '_logging.py' in ws[0].filename  # where `mne.utils.warn` lives


def test_get_call_line():
    """Test getting a call line."""
    @verbose
    def foo(verbose=None):
        return _get_call_line()

    for v in (None, True):
        my_line = foo(verbose=v)  # testing
        assert my_line == 'my_line = foo(verbose=v)  # testing'

    def bar():
        return _get_call_line()

    my_line = bar()  # testing more
    assert my_line == 'my_line = bar()  # testing more'


def test_verbose_strictness():
    """Test that the verbose decorator is strict about usability."""
    @verbose
    def bad_verbose():
        pass

    with pytest.raises(RuntimeError, match='does not accept'):
        bad_verbose()

    class Okay:

        @verbose
        def meth_2(self, verbose=None):
            logger.info('meth_2')

    o = Okay()
    with catch_logging() as log:
        o.meth_2(verbose=False)
    log = log.getvalue()
    assert log == ''
    with catch_logging() as log:
        o.meth_2(verbose=True)
    log = log.getvalue()
    assert 'meth_2' in log
    with catch_logging() as log:
        o.meth_2(verbose=False)
    log = log.getvalue()
    assert log == ''