Skip to content

Commit

Permalink
Run black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksandr Shtaub committed Jan 17, 2024
1 parent aafbf88 commit 76641a9
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 154 deletions.
16 changes: 8 additions & 8 deletions src/pylogctx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
)

__all__ = [
'AdapterNotFound',
'AddContextFilter',
'AddContextFormatter',
'ExcInfoFilter',
'LazyAccessor',
'context',
'log_adapter',
"AdapterNotFound",
"AddContextFilter",
"AddContextFormatter",
"ExcInfoFilter",
"LazyAccessor",
"context",
"log_adapter",
]

__version__ = '1.13.dev0'
__version__ = "1.13.dev0"
7 changes: 3 additions & 4 deletions src/pylogctx/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@


class LoggingTask(Task):

def before_call(self, *args, **kwargs):
# Override if you need to add some vars or log something.
pass
Expand All @@ -31,7 +30,7 @@ def __call__(self, *args, **kwargs):
if arg_spec.varargs is None:
# To keep breaking compat
warnings.warn(
'Method `before_call` without args is deprecated', stacklevel=1
"Method `before_call` without args is deprecated", stacklevel=1
)
self.before_call()
else:
Expand All @@ -42,7 +41,7 @@ def __call__(self, *args, **kwargs):
try:
context.update(task)
except Exception as e:
logger.debug('Failed to push task to log context: %r', e)
logger.debug("Failed to push task to log context: %r", e)

try:
return super().__call__(*args, **kwargs)
Expand All @@ -51,7 +50,7 @@ def __call__(self, *args, **kwargs):
if arg_spec.varargs is None:
# To keep breaking compat
warnings.warn(
'Method `after_call` without args is deprecated',
"Method `after_call` without args is deprecated",
stacklevel=1,
)
self.after_call()
Expand Down
9 changes: 4 additions & 5 deletions src/pylogctx/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def __exit__(self, exc_type, exc_value, traceback):


class AddContextFilter(logging.Filter):
def __init__(self, name='', default=None):
def __init__(self, name="", default=None):
super().__init__(name)
self.default = default or {}

Expand All @@ -156,10 +156,8 @@ def filter(self, record):
class AddContextFormatter(logging.Formatter):
def format(self, record):
msg = super().format(record)
context_str = ' '.join([
f'{k}:{v}' for k, v in context.items()
])
return f'{msg} {context_str}'
context_str = " ".join([f"{k}:{v}" for k, v in context.items()])
return f"{msg} {context_str}"


_adapter_mapping = {}
Expand All @@ -173,6 +171,7 @@ def log_adapter(class_):
def decorator(callable_):
_adapter_mapping[class_] = callable_
return callable_

return decorator


Expand Down
8 changes: 6 additions & 2 deletions src/pylogctx/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ def deepupdate(target, src):
{'name': 'toto', 'hobbies': ['programming', 'chess', 'gaming']}
"""
from pylogctx.core import LazyAccessor

if src and isinstance(src, dict):
for k, v in src.items():
if k in target and target[k] is not None and isinstance(
v, (list, dict, set)):
if (
k in target
and target[k] is not None
and isinstance(v, (list, dict, set))
):
if isinstance(v, list):
target[k].extend(v)
elif isinstance(v, dict):
Expand Down
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.conf import settings


def pytest_configure():
settings.configure()
32 changes: 14 additions & 18 deletions tests/test_celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def test_task():

@app.task
def my_task():
context.update(taskField='RUNNED')
context.update(taskField="RUNNED")
logger = get_task_logger(current_task.name)
logger.info("I log!")
return context.as_dict()
Expand All @@ -25,15 +25,15 @@ def my_task():
else:
result.maybe_throw()
fields = result.result
assert 'taskField' in fields
assert "taskField" in fields
assert not context.as_dict()


class OldLoggingTask(LoggingTask):

def before_call(self):
from pylogctx import context
context.update(taskField='RUNNED')

context.update(taskField="RUNNED")


def test_old_task():
Expand All @@ -48,8 +48,7 @@ def my_task():
return context.as_dict()

with pytest.warns(
UserWarning,
match="Method `before_call` without args is deprecated"
UserWarning, match="Method `before_call` without args is deprecated"
):
result = my_task.apply()

Expand All @@ -58,7 +57,7 @@ def my_task():
else:
result.maybe_throw()
fields = result.result
assert 'taskField' in fields
assert "taskField" in fields
assert not context.as_dict()


Expand All @@ -69,30 +68,27 @@ def test_failing():

@app.task
def my_task():
raise Exception('fail!')
raise Exception("fail!")

result = my_task.apply()
assert isinstance(result.result, Exception)
assert not context.as_dict()


def test_adapter(mocker):
mocker.patch.dict('pylogctx.core._adapter_mapping')
mocker.patch.dict("pylogctx.core._adapter_mapping")
from pylogctx import context, log_adapter

# To fill save context
context.update(toto="tata")
fields = context.as_dict()
assert 'toto' in fields
assert "toto" in fields

app = Celery(task_cls='pylogctx.celery.LoggingTask')
app = Celery(task_cls="pylogctx.celery.LoggingTask")

@log_adapter(app.Task)
def adapter(task):
return {
'celeryTaskId': task.request.id,
'celeryTask': task.name
}
return {"celeryTaskId": task.request.id, "celeryTask": task.name}

@app.task
def my_task():
Expand All @@ -105,11 +101,11 @@ def my_task():
result.maybe_throw()

fields = result.result
assert 'celeryTask' in fields
assert 'celeryTaskId' in fields
assert "celeryTask" in fields
assert "celeryTaskId" in fields

# Check context is the same before task was started
fields = context.as_dict()
assert 'toto' in fields
assert "toto" in fields

context.clear() # Clear context
Loading

0 comments on commit 76641a9

Please sign in to comment.