Skip to content

Commit

Permalink
Disable logging unless code is running in CLI
Browse files Browse the repository at this point in the history
Fixes regression from [^1]. I've manually checked that using the
CLI still generates logs as expected.

The caplog fixture is necessary to capture loguru logs [^2].

[^1]: ecd0c9d
[^2]: https://loguru.readthedocs.io/en/stable/resources/migration.html#making-things-work-with-pytest-and-caplog
  • Loading branch information
benthorner authored and avaldebe committed Jan 11, 2023
1 parent 90c4d6c commit 0d44ef0
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/pms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
from loguru import logger

logger.disable("pms") # disable logging by default


class SensorWarning(UserWarning):
"""Recoverable errors"""

Expand Down
3 changes: 2 additions & 1 deletion src/pms/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
app.command(name=ep.name)(ep.load())


def main():
def main(): # pragma: no cover
logger.enable("pms")
app()


Expand Down
21 changes: 21 additions & 0 deletions tests/core/reader/test_SensorReader.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import pytest
from _pytest.logging import LogCaptureFixture
from loguru import logger

from pms import SensorWarmingUp, SensorWarning
from pms.core.reader import SensorReader, UnableToRead
from pms.core.sensor import Sensor


@pytest.fixture
def caplog(caplog: LogCaptureFixture):
handler_id = logger.add(caplog.handler, format="{message}")
yield caplog
logger.remove(handler_id)


@pytest.fixture
def mock_sleep(monkeypatch):
def sleep(seconds):
Expand Down Expand Up @@ -233,3 +242,15 @@ def test_reader_sensor_no_response(reader: SensorReader):
pass

assert "did not respond" in str(e.value)


def test_logging(reader: SensorReader, capfd, caplog):
with reader:
obs = tuple(reader())

# check data was read
assert len(obs) == 1
assert obs[0].pm10 == 11822 # type:ignore

# check no logs output
assert caplog.text == ""

0 comments on commit 0d44ef0

Please sign in to comment.