File: test_output.py

package info (click to toggle)
python-structlog 25.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,416 kB
  • sloc: python: 8,182; makefile: 138
file content (335 lines) | stat: -rw-r--r-- 9,325 bytes parent folder | download | duplicates (2)
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License.  See the LICENSE file in the root of this
# repository for complete details.

import copy
import pickle

from io import BytesIO, StringIO

import pytest

from structlog import (
    BytesLogger,
    BytesLoggerFactory,
    PrintLogger,
    PrintLoggerFactory,
    WriteLogger,
    WriteLoggerFactory,
)
from structlog._output import WRITE_LOCKS, stderr, stdout

from .utils import stdlib_log_methods


class TestLoggers:
    """
    Tests common to the Print and WriteLoggers.
    """

    @pytest.fixture(name="logger_cls", params=(WriteLogger, PrintLogger))
    @staticmethod
    def _logger_cls(request):
        return request.param

    def test_prints_to_stdout_by_default(self, logger_cls, capsys):
        """
        Instantiating without arguments gives conveniently a logger to standard
        out.
        """
        logger_cls().msg("hello")

        out, err = capsys.readouterr()
        assert "hello\n" == out
        assert "" == err

    def test_prints_to_correct_file(self, logger_cls, tmp_path, capsys):
        """
        Supplied files are respected.
        """
        p = tmp_path / "test.log"

        with p.open("w") as f:
            logger_cls(f).msg("hello")
            out, err = capsys.readouterr()

            assert "" == out == err

        assert "hello\n" == p.read_text()

    def test_lock(self, logger_cls, sio):
        """
        Creating a logger adds a lock to WRITE_LOCKS.
        """
        assert sio not in WRITE_LOCKS

        logger_cls(sio)

        assert sio in WRITE_LOCKS

    @pytest.mark.parametrize("method", stdlib_log_methods)
    def test_stdlib_methods_support(self, logger_cls, method, sio):
        """
        Print/WriteLogger implements methods of stdlib loggers.
        """
        getattr(logger_cls(sio), method)("hello")

        assert "hello" in sio.getvalue()

    @pytest.mark.parametrize("file", [None, stdout, stderr])
    @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1))
    def test_pickle(self, logger_cls, file, proto):
        """
        Can be pickled and unpickled for stdout and stderr.

        Can't compare output because capsys et all would confuse the logic.
        """
        pl = logger_cls(file=file)

        rv = pickle.loads(pickle.dumps(pl, proto))

        assert pl._file is rv._file
        assert pl._lock is rv._lock

    @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1))
    def test_pickle_not_stdout_stderr(self, logger_cls, tmpdir, proto):
        """
        Loggers with different files than stdout/stderr raise a
        PickingError.
        """
        f = tmpdir.join("file.log")
        f.write("")
        pl = logger_cls(file=f.open())

        with pytest.raises(pickle.PicklingError, match="Only (.+)Loggers to"):
            pickle.dumps(pl, proto)

    def test_deepcopy(self, logger_cls, capsys):
        """
        Deepcopied logger works.
        """
        copied_logger = copy.deepcopy(logger_cls())
        copied_logger.msg("hello")

        out, err = capsys.readouterr()
        assert "hello\n" == out
        assert "" == err

    def test_deepcopy_no_stdout(self, logger_cls, tmp_path):
        """
        Only loggers that log to stdout or stderr can be deepcopy-ed.
        """
        p = tmp_path / "log.txt"
        with p.open(mode="w") as f:
            logger = logger_cls(f)
            logger.msg("hello")

            with pytest.raises(copy.error):
                copy.deepcopy(logger)

        assert "hello\n" == p.read_text()

    def test_repr(self, logger_cls):
        """
        __repr__ makes sense.
        """
        assert repr(logger_cls()).startswith(f"<{logger_cls.__name__}(file=")

    def test_stdout_monkeypatch(self, monkeypatch, capsys):
        """
        If stdout gets monkeypatched, the new instance receives the output.
        """
        import sys

        p = PrintLogger()
        new_stdout = StringIO()
        monkeypatch.setattr(sys, "stdout", new_stdout)
        p.msg("hello")

        out, err = capsys.readouterr()
        assert "hello\n" == new_stdout.getvalue()
        assert "" == out
        assert "" == err


class TestPrintLoggerFactory:
    def test_does_not_cache(self):
        """
        Due to doctest weirdness, we must not reuse PrintLoggers.
        """
        f = PrintLoggerFactory()

        assert f() is not f()

    def test_passes_file(self):
        """
        If a file is passed to the factory, it get passed on to the logger.
        """
        pl = PrintLoggerFactory(stderr)()

        assert stderr is pl._file

    def test_ignores_args(self):
        """
        PrintLogger doesn't take positional arguments.  If any are passed to
        the factory, they are not passed to the logger.
        """
        PrintLoggerFactory()(1, 2, 3)


class TestWriteLoggerFactory:
    def test_does_not_cache(self):
        """
        Due to doctest weirdness, we must not reuse WriteLoggers.
        """
        f = WriteLoggerFactory()

        assert f() is not f()

    def test_passes_file(self):
        """
        If a file is passed to the factory, it get passed on to the logger.
        """
        pl = WriteLoggerFactory(stderr)()

        assert stderr is pl._file

    def test_ignores_args(self):
        """
        WriteLogger doesn't take positional arguments.  If any are passed to
        the factory, they are not passed to the logger.
        """
        WriteLoggerFactory()(1, 2, 3)


class TestBytesLogger:
    def test_prints_to_stdout_by_default(self, capsys):
        """
        Instantiating without arguments gives conveniently a logger to standard
        out.
        """
        BytesLogger().msg(b"hell\xc3\xb6")

        out, err = capsys.readouterr()
        assert "hellö\n" == out
        assert "" == err

    def test_prints_to_correct_file(self, tmp_path, capsys):
        """
        Supplied files are respected.
        """
        p = tmp_path / "test.log"

        with p.open("wb") as f:
            BytesLogger(f).msg(b"hello")
            out, err = capsys.readouterr()

            assert "" == out == err

        assert "hello\n" == p.read_text()

    def test_repr(self):
        """
        __repr__ makes sense.
        """
        assert repr(BytesLogger()).startswith("<BytesLogger(file=")

    def test_lock(self, sio):
        """
        Creating a logger adds a lock to WRITE_LOCKS.
        """
        assert sio not in WRITE_LOCKS

        BytesLogger(sio)

        assert sio in WRITE_LOCKS

    @pytest.mark.parametrize("method", stdlib_log_methods)
    def test_stdlib_methods_support(self, method):
        """
        BytesLogger implements methods of stdlib loggers.
        """
        sio = BytesIO()

        getattr(BytesLogger(sio), method)(b"hello")

        assert b"hello" in sio.getvalue()

    @pytest.mark.parametrize("file", [None, stdout.buffer, stderr.buffer])
    @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1))
    def test_pickle(self, file, proto):
        """
        Can be pickled and unpickled for stdout and stderr.

        Can't compare output because capsys et all would confuse the logic.
        """
        pl = BytesLogger(file=file)

        rv = pickle.loads(pickle.dumps(pl, proto))

        assert pl._file is rv._file
        assert pl._lock is rv._lock

    @pytest.mark.parametrize("proto", range(pickle.HIGHEST_PROTOCOL + 1))
    def test_pickle_not_stdout_stderr(self, tmpdir, proto):
        """
        BytesLoggers with different files than stdout/stderr raise a
        PickingError.
        """
        f = tmpdir.join("file.log")
        f.write("")
        pl = BytesLogger(file=f.open())

        with pytest.raises(pickle.PicklingError, match="Only BytesLoggers to"):
            pickle.dumps(pl, proto)

    def test_deepcopy(self, capsys):
        """
        Deepcopied BytesLogger works.
        """
        copied_logger = copy.deepcopy(BytesLogger())
        copied_logger.msg(b"hello")

        out, err = capsys.readouterr()
        assert "hello\n" == out
        assert "" == err

    def test_deepcopy_no_stdout(self, tmp_path):
        """
        Only BytesLoggers that log to stdout or stderr can be deepcopy-ed.
        """
        p = tmp_path / "log.txt"
        with p.open(mode="wb") as f:
            logger = BytesLogger(f)
            logger.msg(b"hello")

            with pytest.raises(copy.error):
                copy.deepcopy(logger)

        assert "hello\n" == p.read_text()


class TestBytesLoggerFactory:
    def test_does_not_cache(self):
        """
        Due to doctest weirdness, we must not reuse BytesLoggers.
        """
        f = BytesLoggerFactory()

        assert f() is not f()

    def test_passes_file(self):
        """
        If a file is passed to the factory, it get passed on to the logger.
        """
        pl = BytesLoggerFactory(stderr)()

        assert stderr is pl._file

    def test_ignores_args(self):
        """
        BytesLogger doesn't take positional arguments.  If any are passed to
        the factory, they are not passed to the logger.
        """
        BytesLoggerFactory()(1, 2, 3)