| 1 |
"""Stupid tests that ensure logging works as expected""" |
| 2 |
|
| 3 |
import logging as log |
| 4 |
import sys |
| 5 |
import threading |
| 6 |
from types import ModuleType |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
import beets.logging as blog |
| 11 |
from beets import plugins, ui |
| 12 |
from beets.test.helper import AsIsImporterMixin, ImportHelper, PluginMixin |
| 13 |
|
| 14 |
|
| 15 |
class TestStrFormatLogger: |
| 16 |
"""Tests for the custom str-formatting logger.""" |
| 17 |
|
| 18 |
def test_logger_creation(self): |
| 19 |
l1 = log.getLogger("foo123") |
| 20 |
l2 = blog.getLogger("foo123") |
| 21 |
assert l1 == l2 |
| 22 |
assert l1.__class__ == log.Logger |
| 23 |
|
| 24 |
l3 = blog.getLogger("bar123") |
| 25 |
l4 = log.getLogger("bar123") |
| 26 |
assert l3 == l4 |
| 27 |
assert l3.__class__ == blog.BeetsLogger |
| 28 |
assert isinstance( |
| 29 |
l3, (blog.StrFormatLogger, blog.ThreadLocalLevelLogger) |
| 30 |
) |
| 31 |
|
| 32 |
l5 = l3.getChild("shalala") |
| 33 |
assert l5.__class__ == blog.BeetsLogger |
| 34 |
|
| 35 |
l6 = blog.getLogger() |
| 36 |
assert l1 != l6 |
| 37 |
|
| 38 |
@pytest.mark.parametrize( |
| 39 |
"level", [log.DEBUG, log.INFO, log.WARNING, log.ERROR] |
| 40 |
) |
| 41 |
@pytest.mark.parametrize( |
| 42 |
"msg, args, kwargs, expected", |
| 43 |
[ |
| 44 |
("foo {} bar {}", ("oof", "baz"), {}, "foo oof bar baz"), |
| 45 |
( |
| 46 |
"foo {bar} baz {foo}", |
| 47 |
(), |
| 48 |
{"foo": "oof", "bar": "baz"}, |
| 49 |
"foo baz baz oof", |
| 50 |
), |
| 51 |
("no args", (), {}, "no args"), |
| 52 |
("foo {} bar {baz}", ("oof",), {"baz": "baz"}, "foo oof bar baz"), |
| 53 |
], |
| 54 |
) |
| 55 |
def test_str_format_logging( |
| 56 |
self, level, msg, args, kwargs, expected, caplog |
| 57 |
): |
| 58 |
logger = blog.getLogger("test_logger") |
| 59 |
logger.setLevel(level) |
| 60 |
|
| 61 |
with caplog.at_level(level, logger="test_logger"): |
| 62 |
logger.log(level, msg, *args, **kwargs) |
| 63 |
|
| 64 |
assert caplog.records, "No log records were captured" |
| 65 |
assert str(caplog.records[0].msg) == expected |
| 66 |
|
| 67 |
|
| 68 |
class TestLogSanitization: |
| 69 |
"""Log messages should have control characters removed from: |
| 70 |
- String arguments |
| 71 |
- Keyword argument values |
| 72 |
- Bytes arguments (which get decoded first) |
| 73 |
""" |
| 74 |
|
| 75 |
@pytest.mark.parametrize( |
| 76 |
"msg, args, kwargs, expected", |
| 77 |
[ |
| 78 |
# Valid UTF-8 bytes are decoded and preserved |
| 79 |
( |
| 80 |
"foo {} bar {bar}", |
| 81 |
(b"oof \xc3\xa9",), |
| 82 |
{"bar": b"baz \xc3\xa9"}, |
| 83 |
"foo oof é bar baz é", |
| 84 |
), |
| 85 |
# Invalid UTF-8 bytes are decoded with replacement characters |
| 86 |
( |
| 87 |
"foo {} bar {bar}", |
| 88 |
(b"oof \xff",), |
| 89 |
{"bar": b"baz \xff"}, |
| 90 |
"foo oof � bar baz �", |
| 91 |
), |
| 92 |
# Control characters should be removed |
| 93 |
( |
| 94 |
"foo {} bar {bar}", |
| 95 |
("oof \x9e",), |
| 96 |
{"bar": "baz \x9e"}, |
| 97 |
"foo oof � bar baz �", |
| 98 |
), |
| 99 |
# Whitespace control characters should be preserved |
| 100 |
( |
| 101 |
"foo {} bar {bar}", |
| 102 |
("foo\t\n",), |
| 103 |
{"bar": "bar\r"}, |
| 104 |
"foo foo\t\n bar bar\r", |
| 105 |
), |
| 106 |
], |
| 107 |
) |
| 108 |
def test_sanitization(self, msg, args, kwargs, expected, caplog): |
| 109 |
level = log.INFO |
| 110 |
logger = blog.getLogger("test_logger") |
| 111 |
logger.setLevel(level) |
| 112 |
|
| 113 |
with caplog.at_level(level, logger="test_logger"): |
| 114 |
logger.log(level, msg, *args, **kwargs) |
| 115 |
|
| 116 |
assert caplog.records, "No log records were captured" |
| 117 |
assert str(caplog.records[0].msg) == expected |
| 118 |
|
| 119 |
|
| 120 |
class DummyModule(ModuleType): |
| 121 |
class DummyPlugin(plugins.BeetsPlugin): |
| 122 |
def __init__(self): |
| 123 |
plugins.BeetsPlugin.__init__(self, "dummy") |
| 124 |
self.import_stages = [self.import_stage] |
| 125 |
self.register_listener("dummy_event", self.listener) |
| 126 |
|
| 127 |
def log_all(self, name): |
| 128 |
self._log.debug("debug {}", name) |
| 129 |
self._log.info("info {}", name) |
| 130 |
self._log.warning("warning {}", name) |
| 131 |
|
| 132 |
def commands(self): |
| 133 |
cmd = ui.Subcommand("dummy") |
| 134 |
cmd.func = lambda _, __, ___: self.log_all("cmd") |
| 135 |
return (cmd,) |
| 136 |
|
| 137 |
def import_stage(self, session, task): |
| 138 |
self.log_all("import_stage") |
| 139 |
|
| 140 |
def listener(self): |
| 141 |
self.log_all("listener") |
| 142 |
|
| 143 |
def __init__(self, *_, **__): |
| 144 |
module_name = "beetsplug.dummy" |
| 145 |
super().__init__(module_name) |
| 146 |
self.DummyPlugin.__module__ = module_name |
| 147 |
self.DummyPlugin = self.DummyPlugin |
| 148 |
|
| 149 |
|
| 150 |
class TestLoggingLevel(AsIsImporterMixin, PluginMixin, ImportHelper): |
| 151 |
plugin = "dummy" |
| 152 |
|
| 153 |
@pytest.fixture(autouse=True) |
| 154 |
def _patch_dummy_module(self, monkeypatch): |
| 155 |
monkeypatch.setitem(sys.modules, "beetsplug.dummy", DummyModule()) |
| 156 |
|
| 157 |
def test_command_level0(self, caplog): |
| 158 |
self.config["verbose"] = 0 |
| 159 |
with caplog.at_level("DEBUG"): |
| 160 |
self.run_command("dummy") |
| 161 |
assert "warning cmd" in caplog.messages |
| 162 |
assert "info cmd" in caplog.messages |
| 163 |
assert "debug cmd" not in caplog.messages |
| 164 |
|
| 165 |
def test_command_level1(self, caplog): |
| 166 |
self.config["verbose"] = 1 |
| 167 |
with caplog.at_level("DEBUG"): |
| 168 |
self.run_command("dummy") |
| 169 |
assert "warning cmd" in caplog.messages |
| 170 |
assert "info cmd" in caplog.messages |
| 171 |
assert "debug cmd" in caplog.messages |
| 172 |
|
| 173 |
def test_command_level2(self, caplog): |
| 174 |
self.config["verbose"] = 2 |
| 175 |
with caplog.at_level("DEBUG"): |
| 176 |
self.run_command("dummy") |
| 177 |
assert "warning cmd" in caplog.messages |
| 178 |
assert "info cmd" in caplog.messages |
| 179 |
assert "debug cmd" in caplog.messages |
| 180 |
|
| 181 |
def test_listener_level0(self, caplog): |
| 182 |
self.config["verbose"] = 0 |
| 183 |
with caplog.at_level("DEBUG"): |
| 184 |
plugins.send("dummy_event") |
| 185 |
assert "warning listener" in caplog.messages |
| 186 |
assert "info listener" not in caplog.messages |
| 187 |
assert "debug listener" not in caplog.messages |
| 188 |
|
| 189 |
def test_listener_level1(self, caplog): |
| 190 |
self.config["verbose"] = 1 |
| 191 |
with caplog.at_level("DEBUG"): |
| 192 |
plugins.send("dummy_event") |
| 193 |
assert "warning listener" in caplog.messages |
| 194 |
assert "info listener" in caplog.messages |
| 195 |
assert "debug listener" not in caplog.messages |
| 196 |
|
| 197 |
def test_listener_level2(self, caplog): |
| 198 |
self.config["verbose"] = 2 |
| 199 |
with caplog.at_level("DEBUG"): |
| 200 |
plugins.send("dummy_event") |
| 201 |
assert "warning listener" in caplog.messages |
| 202 |
assert "info listener" in caplog.messages |
| 203 |
assert "debug listener" in caplog.messages |
| 204 |
|
| 205 |
def test_import_stage_level0(self, caplog): |
| 206 |
self.config["verbose"] = 0 |
| 207 |
with caplog.at_level("DEBUG"): |
| 208 |
self.run_asis_importer() |
| 209 |
assert "warning import_stage" in caplog.messages |
| 210 |
assert "info import_stage" not in caplog.messages |
| 211 |
assert "debug import_stage" not in caplog.messages |
| 212 |
|
| 213 |
def test_import_stage_level1(self, caplog): |
| 214 |
self.config["verbose"] = 1 |
| 215 |
with caplog.at_level("DEBUG"): |
| 216 |
self.run_asis_importer() |
| 217 |
assert "warning import_stage" in caplog.messages |
| 218 |
assert "info import_stage" in caplog.messages |
| 219 |
assert "debug import_stage" not in caplog.messages |
| 220 |
|
| 221 |
def test_import_stage_level2(self, caplog): |
| 222 |
self.config["verbose"] = 2 |
| 223 |
with caplog.at_level("DEBUG"): |
| 224 |
self.run_asis_importer() |
| 225 |
assert "warning import_stage" in caplog.messages |
| 226 |
assert "info import_stage" in caplog.messages |
| 227 |
assert "debug import_stage" in caplog.messages |
| 228 |
|
| 229 |
|
| 230 |
class TestConcurrentEvents(AsIsImporterMixin, ImportHelper): |
| 231 |
"""Similar to LoggingLevelTest but lower-level and focused on multiple |
| 232 |
events interaction. Since this is a bit heavy we don't do it in |
| 233 |
LoggingLevelTest. |
| 234 |
""" |
| 235 |
|
| 236 |
db_on_disk = True |
| 237 |
|
| 238 |
class DummyPlugin(plugins.BeetsPlugin): |
| 239 |
def __init__(self, test_case): |
| 240 |
plugins.BeetsPlugin.__init__(self, "dummy") |
| 241 |
self.register_listener("dummy_event1", self.listener1) |
| 242 |
self.register_listener("dummy_event2", self.listener2) |
| 243 |
self.lock1 = threading.Lock() |
| 244 |
self.lock2 = threading.Lock() |
| 245 |
self.test_case = test_case |
| 246 |
self.exc = None |
| 247 |
self.t1_step = self.t2_step = 0 |
| 248 |
|
| 249 |
def listener1(self): |
| 250 |
try: |
| 251 |
assert self._log.level == log.INFO |
| 252 |
self.t1_step = 1 |
| 253 |
self.lock1.acquire() |
| 254 |
assert self._log.level == log.INFO |
| 255 |
self.t1_step = 2 |
| 256 |
except Exception as e: |
| 257 |
self.exc = e |
| 258 |
|
| 259 |
def listener2(self): |
| 260 |
try: |
| 261 |
assert self._log.level == log.DEBUG |
| 262 |
self.t2_step = 1 |
| 263 |
self.lock2.acquire() |
| 264 |
assert self._log.level == log.DEBUG |
| 265 |
self.t2_step = 2 |
| 266 |
except Exception as e: |
| 267 |
self.exc = e |
| 268 |
|
| 269 |
def test_concurrent_events(self): |
| 270 |
dp = self.DummyPlugin(self) |
| 271 |
|
| 272 |
def check_dp_exc(): |
| 273 |
if dp.exc: |
| 274 |
raise dp.exc |
| 275 |
|
| 276 |
try: |
| 277 |
dp.lock1.acquire() |
| 278 |
dp.lock2.acquire() |
| 279 |
assert dp._log.level == log.NOTSET |
| 280 |
|
| 281 |
self.config["verbose"] = 1 |
| 282 |
t1 = threading.Thread(target=dp.listeners["dummy_event1"][0]) |
| 283 |
t1.start() # blocked. t1 tested its log level |
| 284 |
while dp.t1_step != 1: |
| 285 |
check_dp_exc() |
| 286 |
assert t1.is_alive() |
| 287 |
assert dp._log.level == log.NOTSET |
| 288 |
|
| 289 |
self.config["verbose"] = 2 |
| 290 |
t2 = threading.Thread(target=dp.listeners["dummy_event2"][0]) |
| 291 |
t2.start() # blocked. t2 tested its log level |
| 292 |
while dp.t2_step != 1: |
| 293 |
check_dp_exc() |
| 294 |
assert t2.is_alive() |
| 295 |
assert dp._log.level == log.NOTSET |
| 296 |
|
| 297 |
dp.lock1.release() # dummy_event1 tests its log level + finishes |
| 298 |
while dp.t1_step != 2: |
| 299 |
check_dp_exc() |
| 300 |
t1.join(0.1) |
| 301 |
assert not t1.is_alive() |
| 302 |
assert t2.is_alive() |
| 303 |
assert dp._log.level == log.NOTSET |
| 304 |
|
| 305 |
dp.lock2.release() # dummy_event2 tests its log level + finishes |
| 306 |
while dp.t2_step != 2: |
| 307 |
check_dp_exc() |
| 308 |
t2.join(0.1) |
| 309 |
assert not t2.is_alive() |
| 310 |
|
| 311 |
except Exception: |
| 312 |
print("Alive threads:", threading.enumerate()) |
| 313 |
if dp.lock1.locked(): |
| 314 |
print("Releasing lock1 after exception in test") |
| 315 |
dp.lock1.release() |
| 316 |
if dp.lock2.locked(): |
| 317 |
print("Releasing lock2 after exception in test") |
| 318 |
dp.lock2.release() |
| 319 |
print("Alive threads:", threading.enumerate()) |
| 320 |
raise |
| 321 |
|
| 322 |
def test_root_logger_levels(self, caplog): |
| 323 |
"""Root logger level should be shared between threads.""" |
| 324 |
self.config["threaded"] = True |
| 325 |
|
| 326 |
blog.getLogger("beets").set_global_level(blog.WARNING) |
| 327 |
with caplog.at_level("DEBUG"): |
| 328 |
self.run_asis_importer() |
| 329 |
assert caplog.messages == [] |
| 330 |
|
| 331 |
blog.getLogger("beets").set_global_level(blog.INFO) |
| 332 |
with caplog.at_level("DEBUG"): |
| 333 |
self.run_asis_importer() |
| 334 |
for line in caplog.messages: |
| 335 |
assert "import" in line |
| 336 |
assert "album" in line |
| 337 |
|
| 338 |
blog.getLogger("beets").set_global_level(blog.DEBUG) |
| 339 |
with caplog.at_level("DEBUG"): |
| 340 |
self.run_asis_importer() |
| 341 |
assert "Sending event: database_change" in caplog.messages |
| 342 |
|
| 343 |
|
| 344 |
class TestLegacyFormatter: |
| 345 |
"""Tests for ``LegacyFormatter``, which strips the ``beets.`` prefix |
| 346 |
from logger names and prepends the remainder to the message. |
| 347 |
""" |
| 348 |
|
| 349 |
@pytest.mark.parametrize( |
| 350 |
"logger_name, expected", |
| 351 |
[ |
| 352 |
("beets", "hello world"), |
| 353 |
("beets.musicbrainz", "musicbrainz: hello world"), |
| 354 |
("beets.musicbrainz.sub", "musicbrainz.sub: hello world"), |
| 355 |
("root.foobar", "foobar: hello world"), |
| 356 |
], |
| 357 |
) |
| 358 |
def test_format(self, logger_name, expected): |
| 359 |
"""Root logger passes message unchanged; child loggers get |
| 360 |
``prefix: msg`` format after the ``beets.`` prefix is stripped. |
| 361 |
""" |
| 362 |
formatter = blog.LegacyFormatter("%(legacy_prefix)s%(message)s") |
| 363 |
record = log.LogRecord( |
| 364 |
logger_name, log.INFO, __file__, 0, "hello world", (), None |
| 365 |
) |
| 366 |
assert formatter.format(record) == expected |