Debian Codegraph @

systemd/test/test_journal.py

raw symbols SCIP
1 from __future__ import print_function
2 import contextlib
3 import datetime
4 import errno
5 import logging
6 import os
7 import time
8 import uuid
9 import sys
10 import traceback
11
12 from systemd import journal, id128
13 from systemd.journal import _make_line
14
15 import pytest
16
17 TEST_MID = uuid.UUID('8441372f8dca4ca98694a6091fd8519f')
18 TEST_MID2 = uuid.UUID('8441370000000000000000001fd85000')
19
20 class MockSender:
21 def __init__(self):
22 self.buf = []
23
24 def send(self, MESSAGE, MESSAGE_ID=None,
25 CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
26 **kwargs):
27 args = ['MESSAGE=' + MESSAGE]
28
29 if MESSAGE_ID is not None:
30 id = getattr(MESSAGE_ID, 'hex', MESSAGE_ID)
31 args.append('MESSAGE_ID=' + id)
32
33 if CODE_LINE is CODE_FILE is CODE_FUNC is None:
34 CODE_FILE, CODE_LINE, CODE_FUNC = traceback.extract_stack(limit=2)[0][:3]
35 if CODE_FILE is not None:
36 args.append('CODE_FILE=' + CODE_FILE)
37 if CODE_LINE is not None:
38 args.append('CODE_LINE={:d}'.format(CODE_LINE))
39 if CODE_FUNC is not None:
40 args.append('CODE_FUNC=' + CODE_FUNC)
41
42 args.extend(_make_line(key, val) for key, val in kwargs.items())
43 self.buf.append(args)
44
45 @contextlib.contextmanager
46 def skip_oserror(code):
47 try:
48 yield
49 except (OSError, IOError) as e:
50 if e.errno == code:
51 pytest.skip()
52 raise
53
54 @contextlib.contextmanager
55 def skip_valueerror():
56 try:
57 yield
58 except ValueError:
59 pytest.skip()
60
61 def test_priorities():
62 p = journal.JournalHandler.map_priority
63
64 assert p(logging.NOTSET) == journal.LOG_DEBUG
65 assert p(logging.DEBUG) == journal.LOG_DEBUG
66 assert p(logging.DEBUG - 1) == journal.LOG_DEBUG
67 assert p(logging.DEBUG + 1) == journal.LOG_INFO
68 assert p(logging.INFO - 1) == journal.LOG_INFO
69 assert p(logging.INFO) == journal.LOG_INFO
70 assert p(logging.INFO + 1) == journal.LOG_WARNING
71 assert p(logging.WARN - 1) == journal.LOG_WARNING
72 assert p(logging.WARN) == journal.LOG_WARNING
73 assert p(logging.WARN + 1) == journal.LOG_ERR
74 assert p(logging.ERROR - 1) == journal.LOG_ERR
75 assert p(logging.ERROR) == journal.LOG_ERR
76 assert p(logging.ERROR + 1) == journal.LOG_CRIT
77 assert p(logging.FATAL) == journal.LOG_CRIT
78 assert p(logging.CRITICAL) == journal.LOG_CRIT
79 assert p(logging.CRITICAL + 1) == journal.LOG_ALERT
80
81
82 def test_journalhandler_init_exception():
83 kw = {' X ':3}
84 with pytest.raises(ValueError):
85 journal.JournalHandler(**kw)
86 with pytest.raises(ValueError):
87 journal.JournalHandler.with_args(kw)
88
89 def test_journalhandler_init():
90 kw = {'X':3, 'X3':4}
91 journal.JournalHandler(logging.INFO, **kw)
92 kw['level'] = logging.INFO
93 journal.JournalHandler.with_args(kw)
94
95 def test_journalhandler_info():
96 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
97
98 sender = MockSender()
99 kw = {'X':3, 'X3':4, 'sender_function': sender.send}
100 handler = journal.JournalHandler(logging.INFO, **kw)
101 handler.emit(record)
102 assert len(sender.buf) == 1
103 assert 'X=3' in sender.buf[0]
104 assert 'X3=4' in sender.buf[0]
105
106 sender = MockSender()
107 handler = journal.JournalHandler.with_args({'level':logging.INFO, 'X':3, 'X3':4, 'sender_function':sender.send})
108 handler.emit(record)
109 assert len(sender.buf) == 1
110 assert 'X=3' in sender.buf[0]
111 assert 'X3=4' in sender.buf[0]
112
113 # just check that args==None doesn't cause an error
114 journal.JournalHandler.with_args()
115
116 def test_journalhandler_no_message_id():
117 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
118 sender = MockSender()
119 handler = journal.JournalHandler(logging.INFO, sender_function=sender.send)
120 handler.emit(record)
121 assert len(sender.buf) == 1
122 assert all(not m.startswith('MESSAGE_ID=') for m in sender.buf[0])
123
124 def test_journalhandler_message_id_on_handler():
125 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
126 sender = MockSender()
127 handler = journal.JournalHandler(logging.INFO, sender_function=sender.send,
128 MESSAGE_ID=TEST_MID)
129 handler.emit(record)
130 assert len(sender.buf) == 1
131 assert 'MESSAGE_ID=' + TEST_MID.hex in sender.buf[0]
132
133 def test_journalhandler_message_id_on_handler_hex():
134 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
135 sender = MockSender()
136 handler = journal.JournalHandler(logging.INFO, sender_function=sender.send,
137 MESSAGE_ID=TEST_MID.hex)
138 handler.emit(record)
139 assert len(sender.buf) == 1
140 assert 'MESSAGE_ID=' + TEST_MID.hex in sender.buf[0]
141
142 def test_journalhandler_message_id_on_message():
143 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
144 record.__dict__['MESSAGE_ID'] = TEST_MID2
145 sender = MockSender()
146 handler = journal.JournalHandler(logging.INFO, sender_function=sender.send,
147 MESSAGE_ID=TEST_MID)
148 handler.emit(record)
149 assert len(sender.buf) == 1
150 assert 'MESSAGE_ID=' + TEST_MID2.hex in sender.buf[0]
151
152 def test_journalhandler_message_id_on_message_hex():
153 record = logging.LogRecord('test-logger', logging.INFO, 'testpath', 1, 'test', None, None)
154 record.__dict__['MESSAGE_ID'] = TEST_MID2.hex
155 sender = MockSender()
156 handler = journal.JournalHandler(logging.INFO, sender_function=sender.send,
157 MESSAGE_ID=TEST_MID)
158 handler.emit(record)
159 assert len(sender.buf) == 1
160 assert 'MESSAGE_ID=' + TEST_MID2.hex in sender.buf[0]
161
162 def test_reader_init_flags():
163 j1 = journal.Reader()
164 j2 = journal.Reader(journal.LOCAL_ONLY)
165 j3 = journal.Reader(journal.RUNTIME_ONLY)
166 j4 = journal.Reader(journal.SYSTEM_ONLY)
167 j5 = journal.Reader(journal.LOCAL_ONLY | journal.RUNTIME_ONLY | journal.SYSTEM_ONLY)
168 j6 = journal.Reader(0)
169
170 def test_reader_os_root(tmpdir):
171 with pytest.raises(ValueError):
172 journal.Reader(journal.OS_ROOT)
173 with skip_valueerror():
174 j1 = journal.Reader(path=tmpdir.strpath,
175 flags=journal.OS_ROOT)
176 with skip_valueerror():
177 j2 = journal.Reader(path=tmpdir.strpath,
178 flags=journal.OS_ROOT | journal.CURRENT_USER)
179 j3 = journal.Reader(path=tmpdir.strpath,
180 flags=journal.OS_ROOT | journal.SYSTEM_ONLY)
181
182 def test_reader_init_path(tmpdir):
183 j1 = journal.Reader(path=tmpdir.strpath)
184 journal.Reader(0, path=tmpdir.strpath)
185
186 j2 = journal.Reader(path=tmpdir.strpath)
187 journal.Reader(path=tmpdir.strpath)
188
189 def test_reader_init_path_invalid_fd():
190 with pytest.raises(OSError):
191 journal.Reader(0, path=-1)
192
193 def test_reader_init_path_nondirectory_fd():
194 with pytest.raises(OSError):
195 journal.Reader(0, path=0)
196
197 def test_reader_init_path_fd(tmpdir):
198 fd = os.open(tmpdir.strpath, os.O_RDONLY)
199
200 with skip_oserror(errno.ENOSYS):
201 j1 = journal.Reader(path=fd)
202 assert list(j1) == []
203
204 with skip_valueerror():
205 j2 = journal.Reader(journal.SYSTEM, path=fd)
206 assert list(j2) == []
207
208 j3 = journal.Reader(journal.CURRENT_USER, path=fd)
209 assert list(j3) == []
210
211 def test_reader_as_cm(tmpdir):
212 j = journal.Reader(path=tmpdir.strpath)
213 with j:
214 assert not j.closed
215 assert j.closed
216 # make sure that operations on the Reader fail
217 with pytest.raises(OSError):
218 next(j)
219
220 def test_reader_messageid_match(tmpdir):
221 j = journal.Reader(path=tmpdir.strpath)
222 with j:
223 j.messageid_match(id128.SD_MESSAGE_JOURNAL_START)
224 j.messageid_match(id128.SD_MESSAGE_JOURNAL_STOP.hex)
225
226 def test_reader_this_boot(tmpdir):
227 j = journal.Reader(path=tmpdir.strpath)
228 with j:
229 j.this_boot()
230 j.this_boot(TEST_MID)
231 j.this_boot(TEST_MID.hex)
232
233 def test_reader_this_machine(tmpdir):
234 j = journal.Reader(path=tmpdir.strpath)
235 with j:
236 j.this_machine()
237 j.this_machine(TEST_MID)
238 j.this_machine(TEST_MID.hex)
239
240 def test_reader_query_unique(tmpdir):
241 j = journal.Reader(path=tmpdir.strpath)
242 with j:
243 with skip_oserror(errno.ENOSYS):
244 ans = j.query_unique('FOOBAR')
245 assert isinstance(ans, set)
246 assert ans == set()
247
248 def test_reader_enumerate_fields(tmpdir):
249 j = journal.Reader(path=tmpdir.strpath)
250 with j:
251 with skip_oserror(errno.ENOSYS):
252 ans = j.enumerate_fields()
253 assert isinstance(ans, set)
254 assert ans == set()
255
256 def test_reader_has_runtime_files(tmpdir):
257 j = journal.Reader(path=tmpdir.strpath)
258 with j:
259 with skip_oserror(errno.ENOSYS):
260 ans = j.has_runtime_files()
261 assert ans is False
262
263 def test_reader_has_persistent_files(tmpdir):
264 j = journal.Reader(path=tmpdir.strpath)
265 with j:
266 with skip_oserror(errno.ENOSYS):
267 ans = j.has_runtime_files()
268 assert ans is False
269
270 def test_reader_converters(tmpdir):
271 converters = {'xxx' : lambda arg: 'yyy'}
272 j = journal.Reader(path=tmpdir.strpath, converters=converters)
273
274 val = j._convert_field('xxx', b'abc')
275 assert val == 'yyy'
276
277 val = j._convert_field('zzz', b'\200\200')
278 assert val == b'\200\200'
279
280 def test_reader_convert_entry(tmpdir):
281 converters = {'x1' : lambda arg: 'yyy',
282 'x2' : lambda arg: 'YYY'}
283 j = journal.Reader(path=tmpdir.strpath, converters=converters)
284
285 val = j._convert_entry({'x1' : b'abc',
286 'y1' : b'\200\200',
287 'x2' : [b'abc', b'def'],
288 'y2' : [b'\200\200', b'\200\201']})
289 assert val == {'x1' : 'yyy',
290 'y1' : b'\200\200',
291 'x2' : ['YYY', 'YYY'],
292 'y2' : [b'\200\200', b'\200\201']}
293
294 def test_reader_convert_timestamps(tmpdir):
295 j = journal.Reader(path=tmpdir.strpath)
296
297 val = j._convert_field('_SOURCE_REALTIME_TIMESTAMP', 1641651559324187)
298 if sys.version_info >= (3,):
299 assert val.tzinfo is not None
300
301 val = j._convert_field('__REALTIME_TIMESTAMP', 1641651559324187)
302 if sys.version_info >= (3,):
303 assert val.tzinfo is not None
304
305 val = j._convert_field('COREDUMP_TIMESTAMP', 1641651559324187)
306 if sys.version_info >= (3,):
307 assert val.tzinfo is not None
308
309 def test_seek_realtime(tmpdir):
310 j = journal.Reader(path=tmpdir.strpath)
311
312 now = time.time()
313 j.seek_realtime(now)
314
315 j.seek_realtime(12345)
316
317 long_ago = datetime.datetime(1970, 5, 4)
318 j.seek_realtime(long_ago)
319
320 def test_journal_stream():
321 # This will fail when running in a bare chroot without /run/systemd/journal/stdout
322 with skip_oserror(errno.ENOENT):
323 stream = journal.stream('test_journal.py')
324
325 res = stream.write('message...\n')
326 assert res in (11, None) # Python2 returns None
327
328 print('printed message...', file=stream)