Skip to content

Commit a39f65e

Browse files
committed
unit test for logging
1 parent 8ecb756 commit a39f65e

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

labthings/core/tasks/pool.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
from .thread import TaskThread
66

7-
from flask import copy_current_request_context
7+
from flask import copy_current_request_context, has_request_context
88

99

1010
class TaskMaster:
@@ -37,8 +37,11 @@ def states(self):
3737

3838
def new(self, f, *args, **kwargs):
3939
# copy_current_request_context allows threads to access flask current_app
40+
if has_request_context():
41+
# The if block stops this failing if we're outside a Flask app.
42+
f = copy_current_request_context(f)
4043
task = TaskThread(
41-
target=copy_current_request_context(f), args=args, kwargs=kwargs
44+
target=f, args=args, kwargs=kwargs
4245
)
4346
self._tasks.append(task)
4447
return task

labthings/core/tasks/thread.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ def __init__(self, thread=None, dest=None):
229229
"""
230230
logging.Handler.__init__(self)
231231
self.thread = thread
232-
self.dest = dest if dest else []
232+
self.dest = [] if dest is None else dest
233233
self.addFilter(self.check_thread)
234234

235235
def check_thread(self, record):
@@ -238,16 +238,18 @@ def check_thread(self, record):
238238
return 1
239239
if record.thread == self.thread.ident:
240240
return 1
241+
if record.threadName == self.thread.name:
242+
return 1 # TODO: check if this is unsafe, or better with greenlets
241243
return 0
242244

243245
def emit(self, record):
244246
"""Do something with a logged message"""
245-
print("emitting a log")
246247
record_dict = {"message": record.getMessage()}
247248
for k in ["created", "levelname", "levelno", "lineno", "filename"]:
248249
record_dict[k] = getattr(record, k)
249250
self.dest.append(record_dict)
250251
# FIXME: make sure this doesn't become a memory disaster!
251252
# We probably need to check the size of the list...
252253
# TODO: think about whether any of the keys are security flaws
253-
# (this is why I don't dump the whole logrecord)
254+
# (this is why I don't dump the whole logrecord)
255+
print(f"log is now {self.dest}")

tests/test_tasks.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
import labthings.core.tasks as tasks
3+
import time
4+
import logging
5+
6+
#@pytest.fixture
7+
def count(N, dt=0.01):
8+
for i in range(N):
9+
time.sleep(dt)
10+
logging.info(f"Counted to {i}")
11+
12+
def test_logging():
13+
logging.getLogger().setLevel("INFO")
14+
task = tasks.taskify(count)(10)
15+
task.join()
16+
assert len(task.log) == 10

0 commit comments

Comments
 (0)