diff --git a/docs/reference/matrix-updates/0.11.0-activation.tsv b/docs/reference/matrix-updates/0.11.0-activation.tsv new file mode 100644 index 00000000..418374ad --- /dev/null +++ b/docs/reference/matrix-updates/0.11.0-activation.tsv @@ -0,0 +1,2 @@ +inactivity:log-texts adapted BootUI 2.6.0 (BootUiShellGuardAutoConfiguration.java:66-76) logs fixed inactivity texts. sharpit logs the same texts and levels with BootUI replaced by sharpit, the bootui.* properties replaced by the SHARPIT_* variables and Spring Boot DevTools replaced by a reloading development server, because sharpit has no Spring properties and detects reload through the development server. +inactivity:warnings-count adapted BootUI logs neither the configuration warnings nor their number while it is inactive. While sharpit is inactive it logs one WARNING with the number of configuration warnings (omitted when there are none) instead of the warnings themselves, because the count keeps an invalid setting visible without printing its value. The count leaves out the invalid SHARPIT_ENABLED warning, which the fixed text already reports, so an invalid SHARPIT_ENABLED logs one record as in BootUI. diff --git a/docs/superpowers/plans/2026-10-30-sharpit-mvp.md b/docs/superpowers/plans/2026-10-30-sharpit-mvp.md index f5245801..df934cfd 100644 --- a/docs/superpowers/plans/2026-10-30-sharpit-mvp.md +++ b/docs/superpowers/plans/2026-10-30-sharpit-mvp.md @@ -174,7 +174,7 @@ scripts/sanitize_golden.py **Interfaces:** - Consumes: Tasks 2–5. - Produces: - - `install(app, *, settings: Sequence[object] = (), **options) -> SharpitHandle` — reads `load_settings(options, os.environ)`, `decide(...)`, inserts a `SharpitMount(path, app=sub_app, name="sharpit")` at `app.router.routes[0]`. `SharpitMount` subclasses Starlette `Mount` and overrides its compiled path regex to `^{path}(?:/(?P.*))?$` so the **bare** `{path}` (any method) also reaches the sub-app and its guard (a plain `Mount` never receives it; the host router would redirect or a host catch-all would answer). It registers a lifespan-start hook by wrapping `app.router.lifespan_context` (the original is kept as `handle.original_lifespan` for Task 10) that records startup ms; logs one INFO line `sharpit inactive: ` when inactive; when active and `show_banner`, prints the banner to stderr, including the generated token if any; when `expose_values` is FULL, logs a WARNING. + - `install(app, *, settings: Sequence[object] = (), **options) -> SharpitHandle` — reads `load_settings(options, os.environ)`, `decide(...)`, inserts a `SharpitMount(path, app=sub_app, name="sharpit")` at `app.router.routes[0]`. `SharpitMount` subclasses Starlette `Mount` and overrides its compiled path regex to `^{path}(?:/(?P.*))?$` so the **bare** `{path}` (any method) also reaches the sub-app and its guard (a plain `Mount` never receives it; the host router would redirect or a host catch-all would answer). It registers a lifespan-start hook by wrapping `app.router.lifespan_context` (the original is kept as `handle.original_lifespan` for Task 10) that records startup ms; logs one fixed text when inactive (INFO for AUTO mode, DEBUG for OFF and a disabled profile, WARNING for an invalid `SHARPIT_ENABLED`; never the reason), plus one WARNING with the number of configuration warnings when there are any; when active and `show_banner`, prints the banner to stderr, including the generated token if any; when `expose_values` is FULL, logs a WARNING. - Inactive response: 404 with the host framework's not-found shape (`{"detail":"Not Found"}` JSON for a FastAPI host), no sharpit headers, for every method and every path including the bare `{path}`. - Host middleware (e.g. `TrustedHostMiddleware`, auth middleware) wraps the mount and stays authoritative; README documents adding `localhost` to the host's allowed hosts. sharpit does not try to bypass it. - `class SharpitHandle: settings; activation: ActivationStatus; context: SharpitContext; original_lifespan` (for tests). diff --git a/src/sharpit/engine/activation.py b/src/sharpit/engine/activation.py index 494b1e26..d51a1621 100644 --- a/src/sharpit/engine/activation.py +++ b/src/sharpit/engine/activation.py @@ -2,13 +2,16 @@ from __future__ import annotations +import logging from collections.abc import Mapping, Sequence from dataclasses import dataclass -from typing import Any +from typing import Any, Literal from sharpit.engine.guard import remote_access_configured from sharpit.settings import SharpitSettings, parse_mode +Inactivity = Literal["auto", "off", "disabled-profile", "invalid"] + @dataclass(frozen=True) class ActivationStatus: @@ -16,6 +19,7 @@ class ActivationStatus: localhost_only: bool reason: str warnings: tuple[str, ...] + inactivity: Inactivity | None = None def to_dto(self) -> dict[str, Any]: return { @@ -26,6 +30,28 @@ def to_dto(self) -> dict[str, Any]: } +# Fixed texts and levels (port of BootUI 2.6.0 ``BootUiShellGuardAutoConfiguration.bootUiInactiveStartupDiagnostic``). +# They never carry the decision's reason or warnings: those can hold configured values, which stay out of the log. +_INACTIVITY_MESSAGES: dict[Inactivity, tuple[int, str]] = { + "auto": ( + logging.INFO, + "sharpit is inactive in AUTO mode: no enabled profile is active and no reloading development server was" + " detected. For local development, activate a SHARPIT_ENABLED_PROFILES profile or set SHARPIT_ENABLED=ON.", + ), + "off": (logging.DEBUG, "sharpit is inactive: SHARPIT_ENABLED=OFF."), + "disabled-profile": (logging.DEBUG, "sharpit is inactive: an active profile matches SHARPIT_DISABLED_PROFILES."), + "invalid": ( + logging.WARNING, + "sharpit is inactive: invalid SHARPIT_ENABLED configuration (fail-closed). Use AUTO, ON, or OFF.", + ), +} + + +def inactivity_message(status: ActivationStatus) -> tuple[int, str] | None: + """The log level and fixed text for an inactive status; ``None`` when sharpit is enabled.""" + return None if status.inactivity is None else _INACTIVITY_MESSAGES[status.inactivity] + + def active_profiles(settings: SharpitSettings, environ: Mapping[str, str]) -> list[str]: """Union of the ``profile_vars`` env vars: comma-split, trimmed, lower-cased, de-duplicated in order.""" seen: dict[str, None] = {} @@ -40,12 +66,12 @@ def decide(settings: SharpitSettings, profiles: Sequence[str], dev_signal: str | warnings = list(settings.warnings) localhost_only = not remote_access_configured(settings) # sharpit: trusted proxies and gateway trust count too - def result(enabled: bool, reason: str) -> ActivationStatus: - return ActivationStatus(enabled, localhost_only, reason, tuple(warnings)) + def result(enabled: bool, reason: str, inactivity: Inactivity | None = None) -> ActivationStatus: + return ActivationStatus(enabled, localhost_only, reason, tuple(warnings), inactivity) mode = parse_mode(settings.enabled) if mode is None: - return result(False, f"Disabled: invalid SHARPIT_ENABLED value '{settings.enabled}'") + return result(False, f"Disabled: invalid SHARPIT_ENABLED value '{settings.enabled}'", "invalid") active = {p.strip().lower() for p in profiles} for profile in settings.disabled_profiles: @@ -55,10 +81,14 @@ def result(enabled: bool, reason: str) -> ActivationStatus: f"Profile '{profile}' is in SHARPIT_DISABLED_PROFILES but SHARPIT_ENABLED=ON forces it on." ) return result(True, f"Explicitly enabled (SHARPIT_ENABLED=ON) despite disabled profile '{profile}'") - return result(False, f"Disabled because active profile '{profile}' is in SHARPIT_DISABLED_PROFILES") + return result( + False, + f"Disabled because active profile '{profile}' is in SHARPIT_DISABLED_PROFILES", + "disabled-profile", + ) if mode == "OFF": - return result(False, "Disabled by SHARPIT_ENABLED=OFF") + return result(False, "Disabled by SHARPIT_ENABLED=OFF", "off") if mode == "ON": return result(True, "Enabled by SHARPIT_ENABLED=ON") for profile in settings.enabled_profiles: @@ -66,4 +96,4 @@ def result(enabled: bool, reason: str) -> ActivationStatus: return result(True, f"Enabled by active profile '{profile}'") if dev_signal: return result(True, f"Enabled because a reloading development server was detected ({dev_signal})") - return result(False, "Disabled: no enabled profile and no reloading development server detected") + return result(False, "Disabled: no enabled profile and no reloading development server detected", "auto") diff --git a/src/sharpit/fastapi/install.py b/src/sharpit/fastapi/install.py index 48553821..78e65935 100644 --- a/src/sharpit/fastapi/install.py +++ b/src/sharpit/fastapi/install.py @@ -19,7 +19,7 @@ from starlette.middleware import Middleware from sharpit.engine import guard, sqla -from sharpit.engine.activation import ActivationStatus, active_profiles, decide +from sharpit.engine.activation import ActivationStatus, active_profiles, decide, inactivity_message from sharpit.engine.capture import route_path from sharpit.engine.capture.exceptions import ExceptionStore from sharpit.engine.capture.exchanges import HttpExchangeBuffer @@ -40,7 +40,7 @@ from sharpit.fastapi.handle import SharpitHandle # not from adapter: it imports this module at its end from sharpit.fastapi.introspector import FastApiIntrospector from sharpit.fastapi.signals import dev_server_signal -from sharpit.settings import SharpitSettings, load_settings, parse_mode +from sharpit.settings import INVALID_ENABLED_WARNING_PREFIX, SharpitSettings, load_settings __all__ = ["install", "_configure_capture"] @@ -185,20 +185,11 @@ def _models(models: object) -> tuple[object, ...]: # NOSONAR - one element per return tuple(cast("Iterable[object]", models)) -def _requested(settings: SharpitSettings, profiles: tuple[str, ...]) -> bool: - """sharpit was asked for (an unusable SHARPIT_ENABLED, or an enabled profile is active) yet ended up inactive.""" - return parse_mode(settings.enabled) is None or any(p in profiles for p in settings.enabled_profiles) - - def _existing_handle(router: Any, mount_type: type) -> Any: """An earlier install's handle on this router, with its warning logged; ``None`` on a first install.""" existing = next((r.sharpit_handle for r in router.routes if isinstance(r, mount_type) and r.sharpit_handle), None) if existing is not None: - first = ( - "" - if existing.activation.enabled - else f" (that install left sharpit inactive: {existing.activation.reason})" - ) + first = "" if existing.activation.enabled else " (that install left sharpit inactive)" logger.warning("sharpit.install() was already called on this app; ignoring this call%s", first) return existing @@ -276,6 +267,16 @@ def _apply_runtime_overrides( ) +def _log_inactivity(activation: ActivationStatus) -> None: + """BootUI's levels and fixed texts: neither the reason nor a settings warning (both may hold a configured value).""" + if (inactive := inactivity_message(activation)) is not None: + logger.log(*inactive) + # The invalid SHARPIT_ENABLED warning is left out: the fixed text above already reports it. + count = sum(not warning.startswith(INVALID_ENABLED_WARNING_PREFIX) for warning in activation.warnings) + if count: + logger.warning("sharpit is inactive; %d configuration warning(s) are not shown while it is inactive.", count) + + def install( app: Any, *, @@ -319,18 +320,17 @@ def install( ) handle = sharpit_handle_type(sharpit_settings, activation, ctx, original) idle_tracker: IdleTracker | None = None - for warning in activation.warnings: # the overview panel shows them too, but not while sharpit is inactive - logger.warning("%s", warning) if not activation.enabled: mount = sharpit_mount_type(sharpit_settings.path, app=_not_found, name="sharpit") mount.sharpit_handle = handle router.routes.insert(0, mount) - # asked for but still off is a WARNING (uvicorn drops INFO from unconfigured loggers); an explicit OFF is INFO - level = logging.WARNING if _requested(sharpit_settings, profiles) else logging.INFO - logger.log(level, "sharpit inactive: %s", activation.reason) + _log_inactivity(activation) return handle + for warning in activation.warnings: # the overview panel shows them too + logger.warning("%s", warning) + ctx.masker.identity_key = _identity_key(sharpit_settings) if ctx.masker.identity_key is None: logger.warning("SQLite statement identities are unavailable because sharpit could not load a state key") diff --git a/src/sharpit/settings.py b/src/sharpit/settings.py index b418e127..772e97f4 100644 --- a/src/sharpit/settings.py +++ b/src/sharpit/settings.py @@ -19,6 +19,9 @@ from sharpit.engine.panels import PANELS _NEVER_ECHOED = _registry.NEVER_ECHOED + +# The invalid SHARPIT_ENABLED warning: the inactive log reports it with a fixed text, so it is not counted. +INVALID_ENABLED_WARNING_PREFIX = "Ignoring invalid SHARPIT_ENABLED value" _JOURNAL_SOURCES = _registry.JOURNAL_SOURCES _SPECS = _registry.SPECS _UNSET = _registry.UNSET @@ -274,7 +277,8 @@ def load_settings(kwargs: Mapping[str, object], environ: Mapping[str, str]) -> S except ValueError: # install() logs warnings: never echo a token, however malformed, or a URI that can carry credentials shown = "" if name in _NEVER_ECHOED else f" '{raw}'" - warnings.append(f"Ignoring invalid {env} value{shown}") + prefix = INVALID_ENABLED_WARNING_PREFIX if name == "enabled" else f"Ignoring invalid {env} value" + warnings.append(f"{prefix}{shown}") # `enabled` keeps the raw text so decide() reports it; other fields take their fail-safe (or default). if name == "enabled": values[name] = str(raw).strip() diff --git a/tests/engine/test_activation.py b/tests/engine/test_activation.py index 527fc83c..f90ad924 100644 --- a/tests/engine/test_activation.py +++ b/tests/engine/test_activation.py @@ -14,9 +14,12 @@ from __future__ import annotations +import logging + import pytest -from sharpit.engine.activation import ActivationStatus, active_profiles, decide +from inactivity_texts import AUTO_TEXT, DISABLED_PROFILE_TEXT, INVALID_TEXT, OFF_TEXT +from sharpit.engine.activation import ActivationStatus, active_profiles, decide, inactivity_message from sharpit.settings import SharpitSettings, load_settings SIGNAL = "uvicorn --reload" @@ -299,3 +302,75 @@ def test_to_dto_shape(): def test_decide_accepts_unnormalised_profiles(): assert decide(SharpitSettings(), [" PROD "], None).enabled is False + + +# ---- inactivity category and fixed log texts (BootUI 2.6.0) --------------------------------------------------------- + + +@pytest.mark.parametrize( + ("environ", "expected"), + [ + pytest.param( + {"APP_ENV": "dev", "SHARPIT_ENABLED": "maybe"}, "invalid", id="invalid" + ), # ported: BootUiActivationConditionTests.invalidEnabledModeFailsClosedEvenWithEnabledProfile + pytest.param( + {"APP_ENV": "prod,dev"}, "disabled-profile", id="disabled-profile" + ), # ported: BootUiActivationConditionTests.disabledProfileForcesOffByDefault + pytest.param( + {"APP_ENV": "dev", "SHARPIT_ENABLED": "OFF"}, "off", id="off" + ), # ported: BootUiActivationConditionTests.enabledOffForcesDisabled + pytest.param( + {"APP_ENV": "staging"}, "auto", id="auto" + ), # ported: BootUiActivationConditionTests.autoDisablesWithoutEnabledProfileAndWithoutDevtools + ], +) +def test_inactivity_category_per_branch(environ: dict[str, str], expected: str): + assert run(environ).inactivity == expected + + +@pytest.mark.parametrize( + ("environ", "dev_signal"), + [ + pytest.param({"SHARPIT_ENABLED": "ON"}, None, id="on"), + pytest.param( + {"APP_ENV": "dev"}, None, id="enabled-profile" + ), # ported: BootUiActivationConditionTests.autoEnablesOnEnabledProfile + pytest.param( + {}, SIGNAL, id="dev-signal" + ), # ported: BootUiActivationConditionTests.autoEnablesWhenDevtoolsIsPresent + pytest.param( + {"APP_ENV": "prod", "SHARPIT_ENABLED": "ON"}, None, id="on-despite-disabled-profile" + ), # ported: BootUiActivationConditionTests.enabledOnOverridesDisabledProfileButRecordsWarning + ], +) +def test_inactivity_is_none_when_enabled(environ: dict[str, str], dev_signal: str | None): + # ported: BootUiInactiveStartupDiagnosticTests.enabledInstallationDoesNotRegisterAnInactiveDiagnostic + status = run(environ, dev_signal=dev_signal) + assert status.enabled is True + assert status.inactivity is None + + +def test_activation_dto_has_no_inactivity_key(): + status = run({"APP_ENV": "dev", "SHARPIT_ENABLED": "OFF"}) + assert "inactivity" not in status.to_dto() + + +@pytest.mark.parametrize( + ("environ", "level", "text"), + [ + pytest.param({"APP_ENV": "staging"}, logging.INFO, AUTO_TEXT, id="auto"), + pytest.param({"SHARPIT_ENABLED": "OFF"}, logging.DEBUG, OFF_TEXT, id="off"), + pytest.param({"APP_ENV": "prod"}, logging.DEBUG, DISABLED_PROFILE_TEXT, id="disabled-profile"), + pytest.param({"SHARPIT_ENABLED": "maybe"}, logging.WARNING, INVALID_TEXT, id="invalid"), + ], +) +def test_inactivity_message_levels_and_texts(environ: dict[str, str], level: int, text: str): + # ported: BootUiInactiveStartupDiagnosticTests.ordinaryAutoInactivityLogsOnceWithALocalDevelopmentAction + # ported: BootUiInactiveStartupDiagnosticTests.explicitOffOnlyLogsAtDebug + # ported: BootUiInactiveStartupDiagnosticTests.disabledProfileOnlyLogsAtDebugWithoutEchoingTheProfile + # ported: BootUiInactiveStartupDiagnosticTests.invalidConfigurationStaysClosedAndLogsOnlyAFixedSafeWarning + assert inactivity_message(run(environ)) == (level, text) + + +def test_inactivity_message_is_none_when_enabled(): + assert inactivity_message(run({"SHARPIT_ENABLED": "ON"})) is None diff --git a/tests/fastapi/test_install.py b/tests/fastapi/test_install.py index b53d8f35..54e7e92a 100644 --- a/tests/fastapi/test_install.py +++ b/tests/fastapi/test_install.py @@ -16,6 +16,7 @@ from conftest import golden from fastapi import FastAPI, Request +from inactivity_texts import AUTO_TEXT, DISABLED_PROFILE_TEXT, INVALID_TEXT, OFF_TEXT from sharpit import install from sharpit.engine.guard import ( MESSAGE_CROSS_SITE, @@ -61,10 +62,11 @@ def test_inactive_404_every_path_and_method(): assert "x-frame-options" not in resp.headers -def test_inactive_logs_reason(caplog: pytest.LogCaptureFixture): - with caplog.at_level(logging.INFO, logger="sharpit"): +def test_inactive_logs_a_fixed_text(caplog: pytest.LogCaptureFixture): + # ported: BootUiInactiveStartupDiagnosticTests.explicitOffOnlyLogsAtDebug + with caplog.at_level(logging.DEBUG, logger="sharpit"): install(FastAPI(), enabled="OFF") - assert [r.getMessage() for r in caplog.records] == ["sharpit inactive: Disabled by SHARPIT_ENABLED=OFF"] + assert [r.getMessage() for r in caplog.records] == [OFF_TEXT] def test_an_inactive_install_creates_no_key(tmp_path: Any) -> None: @@ -480,43 +482,181 @@ def test_settings_warnings_are_logged(caplog: pytest.LogCaptureFixture, monkeypa ] -def test_explicit_off_is_info(caplog: pytest.LogCaptureFixture): - # review M3: switching sharpit off on purpose is not a warning +def test_auto_inactivity_is_one_info_record(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch): + _clear_activation_env(monkeypatch) with caplog.at_level(logging.INFO, logger="sharpit"): - install(FastAPI(), enabled="OFF") - assert [(r.levelno, r.getMessage()) for r in caplog.records] == [ - (logging.INFO, "sharpit inactive: Disabled by SHARPIT_ENABLED=OFF") - ] + install(FastAPI()) + assert [r.levelno for r in caplog.records] == [logging.INFO] -def test_requested_but_inactive_is_a_warning(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch): - # an enabled profile that a disabled profile overrides, and an unusable SHARPIT_ENABLED: asked for, still off - monkeypatch.setenv("SHARPIT_PROFILES", "dev,prod") - with caplog.at_level(logging.INFO, logger="sharpit"): - install(FastAPI(), show_banner=False) - install(FastAPI(), enabled="maybe") - inactive = [r for r in caplog.records if r.getMessage().startswith("sharpit inactive")] - assert [r.levelno for r in inactive] == [logging.WARNING, logging.WARNING] +# --- inactivity log: fixed texts, no configured value (BootUI 2.6.0) ---------------------------------------------- +SECRET = "secret-token-xyz" + + +def _clear_activation_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("SHARPIT_ENABLED", "SHARPIT_PROFILES", "APP_ENV", "ENVIRONMENT"): + monkeypatch.delenv(name, raising=False) + for name in [n for n in os.environ if n.upper().startswith(("SHARPIT_ENABLED_", "SHARPIT_DISABLED_"))]: + monkeypatch.delenv(name) -def test_second_install_after_an_inactive_one_names_the_reason(caplog: pytest.LogCaptureFixture): - # review M4 - app = FastAPI() - install(app, enabled="OFF") - with caplog.at_level(logging.WARNING, logger="sharpit"): - install(app, enabled="ON") - (again,) = [r.getMessage() for r in caplog.records if "already called" in r.getMessage()] - assert "Disabled by SHARPIT_ENABLED=OFF" in again +def _everything(record: logging.LogRecord) -> str: + return f"{record.getMessage()}|{record.msg}|{record.args}" -def test_inactive_reason_is_info_when_nothing_was_configured( + +def _sharpit_records(caplog: pytest.LogCaptureFixture) -> list[tuple[int, str]]: + return [(r.levelno, r.getMessage()) for r in caplog.records if r.name.startswith("sharpit")] + + +def test_inactivity_log_carries_no_invalid_enabled_value( caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ): - for name in [n for n in os.environ if n.upper().startswith("SHARPIT_")]: - monkeypatch.delenv(name) - with caplog.at_level(logging.INFO, logger="sharpit"): - install(FastAPI()) - assert [r.levelno for r in caplog.records] == [logging.INFO] + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", SECRET) + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert caplog.records + assert [r for r in caplog.records if SECRET in _everything(r)] == [] + + +def test_inactivity_log_carries_no_profile_name(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch): + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_PROFILES", "secret-profile") + monkeypatch.setenv("SHARPIT_DISABLED_PROFILES", "secret-profile") + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert caplog.records + assert [r for r in caplog.records if "secret-profile" in _everything(r)] == [] + + +def test_invalid_enabled_value_cannot_forge_a_log_line( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +): + # ported: BootUiInactiveStartupDiagnosticTests.invalidConfigurationStaysClosedAndLogsOnlyAFixedSafeWarning + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", "x\nforged " + "a" * 4096) + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert [r for r in caplog.records if "\n" in r.getMessage()] == [] + assert [r for r in caplog.records if "forged" in _everything(r)] == [] + assert [r for r in caplog.records if len(r.getMessage()) >= 300] == [] + assert _sharpit_records(caplog) == [(logging.WARNING, INVALID_TEXT)] + + +def test_invalid_enabled_value_still_counts_other_warnings( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +): + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", SECRET) + monkeypatch.setenv("SHARPIT_STREAM_MAX_SECONDS", "leak") + caplog.set_level(logging.DEBUG) + install(FastAPI()) + count = "sharpit is inactive; 1 configuration warning(s) are not shown while it is inactive." + assert _sharpit_records(caplog) == [(logging.WARNING, INVALID_TEXT), (logging.WARNING, count)] + + +def test_auto_inactivity_does_not_echo_custom_profiles_or_path( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +): + # ported: BootUiInactiveStartupDiagnosticTests.ordinaryAutoDiagnosticDoesNotEchoCustomProfilesOrPaths + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_PROFILES", "private-active-profile") + monkeypatch.setenv("SHARPIT_ENABLED_PROFILES", "private-enabled") + monkeypatch.setenv("SHARPIT_DISABLED_PROFILES", "private-disabled") + monkeypatch.setenv("SHARPIT_PATH", "/private-console") + monkeypatch.setenv("SHARPIT_API_PATH", "/private-console/api") + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert _sharpit_records(caplog) == [(logging.INFO, AUTO_TEXT)] + assert [r for r in caplog.records if "private-" in _everything(r)] == [] + + +@pytest.mark.parametrize( + ("mode", "profile"), + [ + pytest.param("OFF", "dev", id="OFF-with-dev-active"), + pytest.param("AUTO", "prod", id="AUTO-with-prod-active"), + pytest.param("AUTO", "production", id="AUTO-with-production-active"), + ], +) +def test_deliberate_disablement_is_silent_at_info( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, mode: str, profile: str +): + # ported: BootUiInactiveStartupDiagnosticTests.deliberateDisablementIsSilentAtInfo + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", mode) + monkeypatch.setenv("SHARPIT_PROFILES", profile) + caplog.set_level(logging.INFO) + install(FastAPI()) + assert _sharpit_records(caplog) == [] + + +@pytest.mark.parametrize( + ("mode", "profiles"), + [ + pytest.param("OFF", "", id="OFF"), + pytest.param("false", "", id="false"), + pytest.param("no", "", id="no"), + pytest.param(" off ", "", id="padded"), + pytest.param("OFF", "dev", id="OFF-with-dev-active"), + ], +) +def test_explicit_off_only_logs_at_debug( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, mode: str, profiles: str +): + # ported: BootUiInactiveStartupDiagnosticTests.explicitOffOnlyLogsAtDebug + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", mode) + if profiles: + monkeypatch.setenv("SHARPIT_PROFILES", profiles) + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert _sharpit_records(caplog) == [(logging.DEBUG, OFF_TEXT)] + + +@pytest.mark.parametrize("profile", ["prod", "production", "private-profile-secret"]) +def test_disabled_profile_only_logs_at_debug( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch, profile: str +): + # ported: BootUiInactiveStartupDiagnosticTests.disabledProfileOnlyLogsAtDebugWithoutEchoingTheProfile + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_PROFILES", f"{profile},dev") + monkeypatch.setenv("SHARPIT_DISABLED_PROFILES", profile) + caplog.set_level(logging.DEBUG) + install(FastAPI()) + assert _sharpit_records(caplog) == [(logging.DEBUG, DISABLED_PROFILE_TEXT)] + assert [r for r in caplog.records if profile in _everything(r)] == [] + + +def test_inactive_install_logs_warning_count_not_values( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +): + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_STREAM_MAX_SECONDS", "leak\nx") + caplog.set_level(logging.DEBUG) + install(FastAPI(), enabled="OFF") + count = "sharpit is inactive; 1 configuration warning(s) are not shown while it is inactive." + assert [(r.levelno, r.getMessage()) for r in caplog.records if r.getMessage() == count] == [ + (logging.WARNING, count) + ] + assert [r for r in caplog.records if "leak" in _everything(r)] == [] + + +def test_repeated_install_log_carries_no_configured_value( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +): + _clear_activation_env(monkeypatch) + monkeypatch.setenv("SHARPIT_ENABLED", SECRET) + app = FastAPI() + install(app) + caplog.set_level(logging.DEBUG) + install(app) + again = [r.getMessage() for r in caplog.records if "already called" in r.getMessage()] + assert again == [ + "sharpit.install() was already called on this app; ignoring this call (that install left sharpit inactive)" + ] + assert [r for r in caplog.records if SECRET in _everything(r)] == [] def _nested(**options: Any) -> FastAPI: diff --git a/tests/inactivity_texts.py b/tests/inactivity_texts.py new file mode 100644 index 00000000..a6a5e592 --- /dev/null +++ b/tests/inactivity_texts.py @@ -0,0 +1,11 @@ +"""The fixed inactivity log texts (BootUI 2.6.0), written out once for the engine and FastAPI tests.""" + +from __future__ import annotations + +AUTO_TEXT = ( + "sharpit is inactive in AUTO mode: no enabled profile is active and no reloading development server was detected." + " For local development, activate a SHARPIT_ENABLED_PROFILES profile or set SHARPIT_ENABLED=ON." +) +OFF_TEXT = "sharpit is inactive: SHARPIT_ENABLED=OFF." +DISABLED_PROFILE_TEXT = "sharpit is inactive: an active profile matches SHARPIT_DISABLED_PROFILES." +INVALID_TEXT = "sharpit is inactive: invalid SHARPIT_ENABLED configuration (fail-closed). Use AUTO, ON, or OFF."