File: test_exceptions_catch.py

package info (click to toggle)
loguru 0.7.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,556 kB
  • sloc: python: 13,164; javascript: 49; makefile: 14
file content (626 lines) | stat: -rw-r--r-- 16,536 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
import asyncio
import site
import sys
import sysconfig
import threading
import types

import pytest

from loguru import logger


@pytest.mark.parametrize("diagnose", [False, True])
def test_caret_not_masked(writer, diagnose):
    logger.add(writer, backtrace=True, diagnose=diagnose, colorize=False, format="")

    @logger.catch
    def f(n):
        1 / n
        f(n - 1)

    f(30)

    assert sum(line.startswith("> ") for line in writer.read().splitlines()) == 1


@pytest.mark.parametrize("diagnose", [False, True])
def test_no_caret_if_no_backtrace(writer, diagnose):
    logger.add(writer, backtrace=False, diagnose=diagnose, colorize=False, format="")

    @logger.catch
    def f(n):
        1 / n
        f(n - 1)

    f(30)

    assert sum(line.startswith("> ") for line in writer.read().splitlines()) == 0


@pytest.mark.parametrize("encoding", ["ascii", "UTF8", None, "unknown-encoding", "", object()])
def test_sink_encoding(writer, encoding):
    class Writer:
        def __init__(self, encoding):
            self.encoding = encoding
            self.output = ""

        def write(self, message):
            self.output += message

    writer = Writer(encoding)
    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    def foo(a, b):
        a / b

    def bar(c):
        foo(c, 0)

    try:
        bar(4)
    except ZeroDivisionError:
        logger.exception("")

    assert writer.output.endswith("ZeroDivisionError: division by zero\n")


def test_file_sink_ascii_encoding(tmp_path):
    file = tmp_path / "test.log"
    logger.add(file, format="", encoding="ascii", errors="backslashreplace", catch=False)
    a = "天"

    try:
        "天" * a
    except Exception:
        logger.exception("")

    logger.remove()
    result = file.read_text("ascii")
    assert result.count('"\\u5929" * a') == 1
    assert result.count("-> '\\u5929'") == 1


def test_file_sink_utf8_encoding(tmp_path):
    file = tmp_path / "test.log"
    logger.add(file, format="", encoding="utf8", errors="strict", catch=False)
    a = "天"

    try:
        "天" * a
    except Exception:
        logger.exception("")

    logger.remove()
    result = file.read_text("utf8")
    assert result.count('"天" * a') == 1
    assert result.count("└ '天'") == 1


def test_has_sys_real_prefix(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(sys, "real_prefix", "/foo/bar/baz", raising=False)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_no_sys_real_prefix(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.delattr(sys, "real_prefix", raising=False)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_has_site_getsitepackages(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(site, "getsitepackages", lambda: ["foo", "bar", "baz"], raising=False)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_no_site_getsitepackages(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.delattr(site, "getsitepackages", raising=False)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_user_site_is_path(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(site, "USER_SITE", "/foo/bar/baz")
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_user_site_is_none(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(site, "USER_SITE", None)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_sysconfig_get_path_return_path(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(sysconfig, "get_path", lambda *a, **k: "/foo/bar/baz")
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_sysconfig_get_path_return_none(writer, monkeypatch):
    with monkeypatch.context() as context:
        context.setattr(sysconfig, "get_path", lambda *a, **k: None)
        logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

        try:
            1 / 0  # noqa: B018
        except ZeroDivisionError:
            logger.exception("")

        assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_no_exception(writer):
    logger.add(writer, backtrace=False, diagnose=False, colorize=False, format="{message}")

    logger.exception("No Error.")

    assert writer.read() in (
        "No Error.\nNoneType\n",
        "No Error.\nNoneType: None\n",  # Old versions of Python 3.5
    )


def test_exception_is_none():
    err = object()

    def writer(msg):
        nonlocal err
        err = msg.record["exception"]

    logger.add(writer)

    logger.error("No exception")

    assert err is None


def test_exception_is_tuple():
    exception = None

    def writer(msg):
        nonlocal exception
        exception = msg.record["exception"]

    logger.add(writer, catch=False)

    try:
        1 / 0  # noqa: B018
    except ZeroDivisionError:
        logger.exception("Exception")
        reference = sys.exc_info()

    t_1, v_1, tb_1 = exception
    t_2, v_2, tb_2 = (x for x in exception)
    t_3, v_3, tb_3 = exception[0], exception[1], exception[2]
    t_4, v_4, tb_4 = exception.type, exception.value, exception.traceback

    assert isinstance(exception, tuple)
    assert len(exception) == 3
    assert exception == reference
    assert reference == exception
    assert not (exception != reference)
    assert not (reference != exception)
    assert all(t is ZeroDivisionError for t in (t_1, t_2, t_3, t_4))
    assert all(isinstance(v, ZeroDivisionError) for v in (v_1, v_2, v_3, v_4))
    assert all(isinstance(tb, types.TracebackType) for tb in (tb_1, tb_2, tb_3, tb_4))


@pytest.mark.parametrize(
    "exception", [ZeroDivisionError, ArithmeticError, (ValueError, ZeroDivisionError)]
)
def test_exception_not_raising(writer, exception):
    logger.add(writer)

    @logger.catch(exception)
    def a():
        1 / 0  # noqa: B018

    a()
    assert writer.read().endswith("ZeroDivisionError: division by zero\n")


@pytest.mark.parametrize("exception", [ValueError, ((SyntaxError, TypeError))])
def test_exception_raising(writer, exception):
    logger.add(writer)

    @logger.catch(exception=exception)
    def a():
        1 / 0  # noqa: B018

    with pytest.raises(ZeroDivisionError):
        a()

    assert writer.read() == ""


@pytest.mark.parametrize(
    "exclude", [ZeroDivisionError, ArithmeticError, (ValueError, ZeroDivisionError)]
)
@pytest.mark.parametrize("exception", [BaseException, ZeroDivisionError])
def test_exclude_exception_raising(writer, exclude, exception):
    logger.add(writer)

    @logger.catch(exception, exclude=exclude)
    def a():
        1 / 0  # noqa: B018

    with pytest.raises(ZeroDivisionError):
        a()

    assert writer.read() == ""


@pytest.mark.parametrize("exclude", [ValueError, ((SyntaxError, TypeError))])
@pytest.mark.parametrize("exception", [BaseException, ZeroDivisionError])
def test_exclude_exception_not_raising(writer, exclude, exception):
    logger.add(writer)

    @logger.catch(exception, exclude=exclude)
    def a():
        1 / 0  # noqa: B018

    a()
    assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_reraise(writer):
    logger.add(writer)

    @logger.catch(reraise=True)
    def a():
        1 / 0  # noqa: B018

    with pytest.raises(ZeroDivisionError):
        a()

    assert writer.read().endswith("ZeroDivisionError: division by zero\n")


def test_onerror(writer):
    is_error_valid = False
    logger.add(writer, format="{message}")

    def onerror(error):
        nonlocal is_error_valid
        logger.info("Called after logged message")
        _, exception, _ = sys.exc_info()
        is_error_valid = (error == exception) and isinstance(error, ZeroDivisionError)

    @logger.catch(onerror=onerror)
    def a():
        1 / 0  # noqa: B018

    a()

    assert is_error_valid
    assert writer.read().endswith(
        "ZeroDivisionError: division by zero\n" "Called after logged message\n"
    )


def test_onerror_with_reraise(writer):
    called = False
    logger.add(writer, format="{message}")

    def onerror(_):
        nonlocal called
        called = True

    with pytest.raises(ZeroDivisionError):
        with logger.catch(onerror=onerror, reraise=True):
            1 / 0  # noqa: B018

    assert called


def test_decorate_function(writer):
    logger.add(writer, format="{message}", diagnose=False, backtrace=False, colorize=False)

    @logger.catch
    def a(x):
        return 100 / x

    assert a(50) == 2
    assert writer.read() == ""


def test_decorate_coroutine(writer):
    logger.add(writer, format="{message}", diagnose=False, backtrace=False, colorize=False)

    @logger.catch
    async def foo(a, b):
        return a + b

    result = asyncio.run(foo(100, 5))

    assert result == 105
    assert writer.read() == ""


def test_decorate_generator(writer):
    @logger.catch
    def foo(x, y, z):
        yield x
        yield y
        return z

    f = foo(1, 2, 3)
    assert next(f) == 1
    assert next(f) == 2

    with pytest.raises(StopIteration, match=r"3"):
        next(f)


def test_decorate_generator_with_error():
    @logger.catch
    def foo():
        for i in range(3):
            1 / (2 - i)
            yield i

    assert list(foo()) == [0, 1]


def test_default_with_function():
    @logger.catch(default=42)
    def foo():
        1 / 0  # noqa: B018

    assert foo() == 42


def test_default_with_generator():
    @logger.catch(default=42)
    def foo():
        yield 1 / 0

    with pytest.raises(StopIteration, match=r"42"):
        next(foo())


def test_default_with_coroutine():
    @logger.catch(default=42)
    async def foo():
        return 1 / 0

    assert asyncio.run(foo()) == 42


def test_error_when_decorating_class_without_parentheses():
    with pytest.raises(TypeError):

        @logger.catch
        class Foo:
            pass


def test_error_when_decorating_class_with_parentheses():
    with pytest.raises(TypeError):

        @logger.catch()
        class Foo:
            pass


def test_unprintable_but_decorated_repr(writer):

    class Foo:
        @logger.catch(reraise=True)
        def __repr__(self):
            raise ValueError("Something went wrong")

    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    assert writer.read().endswith("ValueError: Something went wrong\n")


def test_unprintable_but_decorated_repr_without_reraise(writer):
    class Foo:
        @logger.catch(reraise=False, default="?")
        def __repr__(self):
            raise ValueError("Something went wrong")

    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    foo = Foo()

    repr(foo)

    assert writer.read().endswith("ValueError: Something went wrong\n")


def test_unprintable_but_decorated_multiple_sinks(capsys):
    class Foo:
        @logger.catch(reraise=True)
        def __repr__(self):
            raise ValueError("Something went wrong")

    logger.add(sys.stderr, backtrace=True, diagnose=True, colorize=False, format="", catch=False)
    logger.add(sys.stdout, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    out, err = capsys.readouterr()
    assert out.endswith("ValueError: Something went wrong\n")
    assert err.endswith("ValueError: Something went wrong\n")


def test_unprintable_but_decorated_repr_with_enqueue(writer):
    class Foo:
        @logger.catch(reraise=True)
        def __repr__(self):
            raise ValueError("Something went wrong")

    logger.add(
        writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False, enqueue=True
    )

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    logger.complete()

    assert writer.read().endswith("ValueError: Something went wrong\n")


def test_unprintable_but_decorated_repr_twice(writer):
    class Foo:
        @logger.catch(reraise=True)
        @logger.catch(reraise=True)
        def __repr__(self):
            raise ValueError("Something went wrong")

    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    assert writer.read().endswith("ValueError: Something went wrong\n")


def test_unprintable_with_catch_context_manager(writer):
    class Foo:
        def __repr__(self):
            with logger.catch(reraise=True):
                raise ValueError("Something went wrong")

    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    assert writer.read().endswith("ValueError: Something went wrong\n")


def test_unprintable_with_catch_context_manager_reused(writer):
    def sink(_):
        raise ValueError("Sink error")

    logger.remove()
    logger.add(sink, catch=False)

    catcher = logger.catch(reraise=False)

    class Foo:
        def __repr__(self):
            with catcher:
                raise ValueError("Something went wrong")

    foo = Foo()

    with pytest.raises(ValueError, match="^Sink error$"):
        repr(foo)

    logger.remove()
    logger.add(writer)

    with catcher:
        raise ValueError("Error")

    assert writer.read().endswith("ValueError: Error\n")


def test_unprintable_but_decorated_repr_multiple_threads(writer):
    wait_for_repr_block = threading.Event()
    wait_for_worker_finish = threading.Event()

    recursive = False

    class Foo:
        @logger.catch(reraise=True)
        def __repr__(self):
            nonlocal recursive
            if not recursive:
                recursive = True
            else:
                wait_for_repr_block.set()
                wait_for_worker_finish.wait()
            raise ValueError("Something went wrong")

    def worker():
        wait_for_repr_block.wait()
        with logger.catch(reraise=False):
            raise ValueError("Worker error")
        wait_for_worker_finish.set()

    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    thread = threading.Thread(target=worker)
    thread.start()

    foo = Foo()

    with pytest.raises(ValueError, match="^Something went wrong$"):
        repr(foo)

    thread.join()

    assert "ValueError: Worker error\n" in writer.read()
    assert writer.read().endswith("ValueError: Something went wrong\n")