Skip to content

Commit 7e7e04d

Browse files
committed
test for log workers
1 parent 55c5d09 commit 7e7e04d

File tree

3 files changed

+54
-1
lines changed

3 files changed

+54
-1
lines changed

src/textual/__init__.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def __call__(self, *args: object, **kwargs) -> None:
105105
)
106106
print(*print_args)
107107
return
108-
if app.devtools is None or not app.devtools.is_connected:
108+
if not app._is_devtools_connected:
109109
return
110110

111111
current_frame = inspect.currentframe()
@@ -198,4 +198,10 @@ def worker(self) -> Logger:
198198
from textual import log
199199
log(locals())
200200
```
201+
202+
!!! note
203+
This logger will only work if there is an active app in the current thread.
204+
Use `app.log` to write logs from a thread without an active app.
205+
206+
201207
"""

src/textual/app.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,11 @@ def __init__(
842842
)
843843
)
844844

845+
@property
846+
def _is_devtools_connected(self) -> bool:
847+
"""Is the app connected to the devtools?"""
848+
return self.devtools is not None and self.devtools.is_connected
849+
845850
@cached_property
846851
def _exception_event(self) -> asyncio.Event:
847852
"""An event that will be set when the first exception is encountered."""

tests/test_logger.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import inspect
2+
from typing import Any
3+
4+
from textual import work
5+
from textual._log import LogGroup, LogVerbosity
6+
from textual.app import App
7+
8+
9+
async def test_log_from_worker() -> None:
10+
"""Check that log calls from threaded workers call app._log"""
11+
12+
log_messages: list[tuple] = []
13+
14+
class LogApp(App):
15+
16+
def _log(
17+
self,
18+
group: LogGroup,
19+
verbosity: LogVerbosity,
20+
_textual_calling_frame: inspect.Traceback,
21+
*objects: Any,
22+
**kwargs,
23+
) -> None:
24+
log_messages.append(objects)
25+
26+
@property
27+
def _is_devtools_connected(self):
28+
"""Fake connected devtools."""
29+
return True
30+
31+
def on_mount(self) -> None:
32+
self.do_work()
33+
self.call_after_refresh(self.exit)
34+
35+
@work(thread=True)
36+
def do_work(self) -> None:
37+
self.log("HELLO from do_work")
38+
39+
app = LogApp()
40+
async with app.run_test() as pilot:
41+
await pilot.pause()
42+
assert ("HELLO from do_work",) in log_messages

0 commit comments

Comments
 (0)