Completed
Push — master ( 203a93...96107c )
by Oleksandr
01:54
created

isotopic_logging.DirectPrefixInjector   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%
Metric Value
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 10
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __repr__() 0 5 1
A mark() 0 3 1
A __init__() 0 5 1
A format_elapsed_time() 0 3 1
A elapsed_time() 0 9 2
1
# -*- coding: utf-8 -*-
2 1
from __future__ import unicode_literals
3
4 1
import datetime
5 1
import time
6
7 1
from .defaults import ELAPSED_TIME_FORMAT
8 1
from .generators import generate_oid
9 1
from .prefix import make_prefix, join_prefix
10
11
12 1
class DirectPrefixInjector(object):
13
14 1
    __slots__ = ['prefix', 'enter_time', ]
15
16 1
    def __init__(self, prefix):
17 1
        self.prefix = prefix
18
19
        # `enter_time` will be set by context manager
20 1
        self.enter_time = None
21
22 1
    def mark(self, message):
23
        # Use `format` as it will automatically convert parameters to strings
24 1
        return "{0}{1}".format(self.prefix, message)
25
26 1
    @property
27
    def elapsed_time(self):
28 1
        if self.enter_time is None:
29 1
            raise ValueError(
30
                "Prefix injector '{injector}' is out of context, hence has no "
31
                "elapsed time."
32
                .format(injector=self))
33
34 1
        return time.time() - self.enter_time
35
36 1
    def format_elapsed_time(self, fmt=None):
37 1
        dt = datetime.datetime.utcfromtimestamp(self.elapsed_time)
38 1
        return dt.strftime(fmt or ELAPSED_TIME_FORMAT)
39
40 1
    def __repr__(self):
41 1
        return """<{module}.{name}("{prefix}")>""".format(
42
            module=self.__class__.__module__,
43
            name=self.__class__.__name__,
44
            prefix=self.prefix)
45
46
47 1
class StaticPrefixInjector(DirectPrefixInjector):
48
49 1
    def __init__(self, prefix, delimiter=None):
50 1
        prefix = make_prefix(prefix, delimiter)
51 1
        super(StaticPrefixInjector, self).__init__(prefix)
52
53
54 1
class AutoprefixInjector(StaticPrefixInjector):
55
56 1
    def __init__(self, oid_generator=None, delimiter=None):
57 1
        autopart = generate_oid(oid_generator)
58 1
        super(AutoprefixInjector, self).__init__(autopart, delimiter)
59
60
61 1
class HybrydPrefixInjector(DirectPrefixInjector):
62
63 1
    def __init__(self, prefix, oid_generator=None, delimiter=None):
64 1
        autopart = generate_oid(oid_generator)
65 1
        prefix = join_prefix([autopart, prefix, ], delimiter)
66 1
        super(HybrydPrefixInjector, self).__init__(prefix)
67
68
69 1
def merge_injectors(*args):
70 1
    prefix = ''.join([x.prefix for x in args])
71
    return DirectPrefixInjector(prefix)
72