File: utils.py

package info (click to toggle)
logbook 1.7.0-1.0
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,140 kB
  • sloc: python: 6,558; makefile: 141
file content (89 lines) | stat: -rw-r--r-- 1,953 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
"""
    test utils for logbook
    ~~~~~~~~~~~~~~~~~~~~~~

    :copyright: (c) 2010 by Armin Ronacher, Georg Brandl.
    :license: BSD, see LICENSE for more details.
"""
import functools
import importlib
import sys
from contextlib import contextmanager
from io import StringIO

import pytest

import logbook

_missing = object()

LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


def require_module(module_name):
    found = True
    try:
        importlib.import_module(module_name)
    except ImportError:
        found = False

    return pytest.mark.skipif(not found, reason=f"Module {module_name} is required")


def make_fake_mail_handler(**kwargs):
    class FakeMailHandler(logbook.MailHandler):
        mails = []

        def get_connection(self):
            return self

        def close_connection(self, con):
            pass

        def sendmail(self, fromaddr, recipients, mail):
            self.mails.append((fromaddr, recipients, mail))

    kwargs.setdefault("level", logbook.ERROR)
    return FakeMailHandler("foo@example.com", ["bar@example.com"], **kwargs)


def missing(name):
    def decorate(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            old = sys.modules.get(name, _missing)
            sys.modules[name] = None
            try:
                f(*args, **kwargs)
            finally:
                if old is _missing:
                    del sys.modules[name]
                else:
                    sys.modules[name] = old

        return wrapper

    return decorate


def activate_via_with_statement(handler):
    return handler


@contextmanager
def activate_via_push_pop(handler):
    handler.push_thread()
    try:
        yield handler
    finally:
        handler.pop_thread()


@contextmanager
def capturing_stderr_context():
    original = sys.stderr
    sys.stderr = StringIO()
    try:
        yield sys.stderr
    finally:
        sys.stderr = original