|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +"""Tests for the Celery part of ``superset.utils.logging_configurator``.""" |
| 18 | + |
| 19 | +import logging |
| 20 | +import os |
| 21 | +import sys |
| 22 | +import warnings |
| 23 | +from collections.abc import Iterator |
| 24 | +from pathlib import Path |
| 25 | +from unittest import mock |
| 26 | + |
| 27 | +import pytest |
| 28 | +from celery import Celery |
| 29 | +from celery.app.log import Logging |
| 30 | +from celery.signals import setup_logging |
| 31 | + |
| 32 | +from superset.utils.logging_configurator import keep_configured_logging |
| 33 | + |
| 34 | +# Loggers that Celery's logging setup touches |
| 35 | +LOGGERS = ("", "celery", "celery.task", "multiprocessing") |
| 36 | + |
| 37 | + |
| 38 | +def _logger_state(name: str) -> tuple[list[logging.Handler], int, bool]: |
| 39 | + logger = logging.getLogger(name) |
| 40 | + return list(logger.handlers), logger.level, bool(logger.propagate) |
| 41 | + |
| 42 | + |
| 43 | +@pytest.fixture |
| 44 | +def celery_instance(monkeypatch: pytest.MonkeyPatch) -> Iterator[Celery]: |
| 45 | + """ |
| 46 | + A Celery app whose logging setup can run in this process, plus a reset of |
| 47 | + everything that setup touches once the test is over. |
| 48 | + """ |
| 49 | + # Celery configures logging once per process and remembers that in a class |
| 50 | + # attribute; start from a clean slate and leave no receivers behind. |
| 51 | + monkeypatch.setattr(Logging, "_setup", False) |
| 52 | + monkeypatch.setattr(setup_logging, "receivers", []) |
| 53 | + monkeypatch.setattr(sys, "stdout", sys.stdout) |
| 54 | + monkeypatch.setattr(sys, "stderr", sys.stderr) |
| 55 | + before = {name: _logger_state(name) for name in LOGGERS} |
| 56 | + # A known root level, so the tests can tell whether Celery changed it |
| 57 | + logging.getLogger().setLevel(logging.INFO) |
| 58 | + |
| 59 | + app = Celery("superset_logging_test", set_as_current=False) |
| 60 | + # The setting people reach for first. It does not keep Celery from adding |
| 61 | + # its task-logger handler or from changing the root level. |
| 62 | + app.conf.worker_hijack_root_logger = False |
| 63 | + |
| 64 | + # ``Logging.setup()`` also exports CELERY_LOG_* / _MP_FORK_* variables for |
| 65 | + # prefork children and adds warning filters; undo both. |
| 66 | + with mock.patch.dict(os.environ), warnings.catch_warnings(): |
| 67 | + yield app |
| 68 | + |
| 69 | + for name, (handlers, level, propagate) in before.items(): |
| 70 | + logger = logging.getLogger(name) |
| 71 | + # Drop what Celery added and keep what was there, including the capture |
| 72 | + # handlers pytest attaches to the root logger around every test phase. |
| 73 | + for handler in list(logger.handlers): |
| 74 | + if handler not in handlers: |
| 75 | + logger.removeHandler(handler) |
| 76 | + logger.setLevel(level) |
| 77 | + logger.propagate = propagate |
| 78 | + |
| 79 | + |
| 80 | +def test_celery_reconfigures_logging_by_default(celery_instance: Celery) -> None: |
| 81 | + """ |
| 82 | + Without a receiver Celery still adds a handler to the task logger and |
| 83 | + overrides the root level, even with ``worker_hijack_root_logger`` off. |
| 84 | + """ |
| 85 | + task_logger = logging.getLogger("celery.task") |
| 86 | + task_handlers = list(task_logger.handlers) |
| 87 | + |
| 88 | + handled = celery_instance.log.setup(loglevel=logging.ERROR, logfile=None) |
| 89 | + |
| 90 | + assert not handled |
| 91 | + assert logging.getLogger().level == logging.ERROR |
| 92 | + assert len(task_logger.handlers) == len(task_handlers) + 1 |
| 93 | + assert not task_logger.propagate |
| 94 | + |
| 95 | + |
| 96 | +def test_receiver_keeps_configured_logging( |
| 97 | + celery_instance: Celery, |
| 98 | + tmp_path: Path, |
| 99 | +) -> None: |
| 100 | + """ |
| 101 | + With the receiver connected, Celery leaves every logger as the application |
| 102 | + configured it, opens no log file and skips the stdout/stderr redirection. |
| 103 | + """ |
| 104 | + setup_logging.connect(keep_configured_logging) |
| 105 | + setup_logging.connect(keep_configured_logging) # a second connect is a no-op |
| 106 | + assert len(setup_logging.receivers) == 1 |
| 107 | + |
| 108 | + before = {name: _logger_state(name) for name in LOGGERS} |
| 109 | + stdout, stderr = sys.stdout, sys.stderr |
| 110 | + logfile = tmp_path / "worker.log" |
| 111 | + |
| 112 | + # What ``celery worker -l ERROR --logfile ...`` and ``celery beat`` run on |
| 113 | + # start-up; a prefork child runs it again when the file name contains ``%i`` |
| 114 | + for _ in range(2): |
| 115 | + celery_instance.log.already_setup = False |
| 116 | + handled = celery_instance.log.setup( |
| 117 | + loglevel=logging.ERROR, logfile=str(logfile), redirect_stdouts=True |
| 118 | + ) |
| 119 | + # Celery hands back (receiver, return value) pairs; an exception raised |
| 120 | + # by the receiver would show up here instead of None |
| 121 | + assert handled == [(keep_configured_logging, None)] |
| 122 | + |
| 123 | + assert {name: _logger_state(name) for name in LOGGERS} == before |
| 124 | + assert not logfile.exists() |
| 125 | + assert sys.stdout is stdout |
| 126 | + assert sys.stderr is stderr |
0 commit comments