Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions aws_lambda_powertools/metrics/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
)
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import strtobool
from aws_lambda_powertools.shared.functions import resolve_bool_env_var

if TYPE_CHECKING:
from aws_lambda_powertools.utilities.typing.lambda_context import LambdaContext
Expand Down Expand Up @@ -155,8 +155,8 @@ def is_metrics_disabled() -> bool:
- If POWERTOOLS_DEV is True and POWERTOOLS_METRICS_DISABLED is not set: Disable metrics
"""

is_dev_mode = strtobool(os.getenv(constants.POWERTOOLS_DEV_ENV, "false"))
is_metrics_disabled = strtobool(os.getenv(constants.METRICS_DISABLED_ENV, "false"))
is_dev_mode = resolve_bool_env_var(constants.POWERTOOLS_DEV_ENV)
is_metrics_disabled = resolve_bool_env_var(constants.METRICS_DISABLED_ENV)

disable_conditions = [
is_metrics_disabled,
Expand Down
22 changes: 20 additions & 2 deletions aws_lambda_powertools/shared/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from typing import TYPE_CHECKING, Any, TypeGuard, overload

from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.warnings import PowertoolsUserWarning

if TYPE_CHECKING:
from collections.abc import Generator
Expand Down Expand Up @@ -57,6 +58,23 @@ def resolve_truthy_env_var_choice(env: str, choice: bool | None = None) -> bool:
return choice if choice is not None else strtobool(env)


def resolve_bool_env_var(env_var: str, default: bool = False) -> bool:
"""Resolve a boolean environment variable, falling back to the default on an empty or unparsable value"""
value = os.getenv(env_var)
if value is None:
return default

try:
return strtobool(value)
except ValueError:
warnings.warn(
f"{env_var} has an unrecognised value {value!r}. Falling back to {default}.",
category=PowertoolsUserWarning,
stacklevel=3,
)
return default


def resolve_max_age(env: str, choice: int | None) -> int:
"""Resolve max age value"""
return choice if choice is not None else int(env)
Expand Down Expand Up @@ -121,7 +139,7 @@ def bytes_to_string(value: bytes) -> str:


def powertools_dev_is_set() -> bool:
is_on = strtobool(os.getenv(constants.POWERTOOLS_DEV_ENV, "0"))
is_on = resolve_bool_env_var(constants.POWERTOOLS_DEV_ENV)
if is_on:
warnings.warn(
"POWERTOOLS_DEV environment variable is enabled. Increasing verbosity across utilities.",
Expand All @@ -133,7 +151,7 @@ def powertools_dev_is_set() -> bool:


def powertools_debug_is_set() -> bool:
is_on = strtobool(os.getenv(constants.POWERTOOLS_DEBUG_ENV, "0"))
is_on = resolve_bool_env_var(constants.POWERTOOLS_DEBUG_ENV)
if is_on:
warnings.warn("POWERTOOLS_DEBUG environment variable is enabled. Setting logging level to DEBUG.", stacklevel=2)
return True
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
import functools
import inspect
import logging
import os
import warnings
from typing import TYPE_CHECKING, Any

from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import strtobool
from aws_lambda_powertools.shared.functions import resolve_bool_env_var
from aws_lambda_powertools.utilities.circuit_breaker.base import CircuitBreakerHandler
from aws_lambda_powertools.utilities.circuit_breaker.config import CircuitBreakerConfig
from aws_lambda_powertools.warnings import PowertoolsUserWarning
Expand Down Expand Up @@ -93,7 +92,7 @@ def charge(order: dict) -> dict:
def decorator(function: Callable) -> Callable:
def disabled() -> bool:
# Skip the circuit entirely when disabled (development only).
if not strtobool(os.getenv(constants.CIRCUIT_BREAKER_DISABLED_ENV, "false")):
if not resolve_bool_env_var(constants.CIRCUIT_BREAKER_DISABLED_ENV):
return False
warnings.warn(
message="Disabling the circuit breaker is intended for development environments only "
Expand Down
12 changes: 12 additions & 0 deletions tests/functional/circuit_breaker/test_circuit_breaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
)
from aws_lambda_powertools.utilities.circuit_breaker.exceptions import CircuitBreakerError
from aws_lambda_powertools.utilities.circuit_breaker.persistence.record import CircuitStateRecord
from aws_lambda_powertools.warnings import PowertoolsUserWarning

# All tests disable the local read cache (max_age=0) so each call re-reads the fake store.

Expand Down Expand Up @@ -318,6 +319,17 @@ def call():
assert call() == "ran anyway"


def test_disabled_env_empty_or_unparsable_keeps_circuit_enabled(store, monkeypatch):
monkeypatch.setenv("POWERTOOLS_CIRCUIT_BREAKER_DISABLED", "")

@circuit_breaker(name="c", persistence_store=store, config=CircuitBreakerConfig(local_cache_max_age=0))
def call():
return "ran"

with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_CIRCUIT_BREAKER_DISABLED has an unrecognised value"):
assert call() == "ran"


def test_config_is_optional(store):
@circuit_breaker(name="c", persistence_store=store)
def call():
Expand Down
10 changes: 10 additions & 0 deletions tests/unit/metrics/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from aws_lambda_powertools.metrics.functions import (
extract_cloudwatch_metric_resolution_value,
extract_cloudwatch_metric_unit_value,
is_metrics_disabled,
)
from aws_lambda_powertools.metrics.provider.cloudwatch_emf.exceptions import (
MetricResolutionError,
Expand Down Expand Up @@ -104,3 +105,12 @@ def test_add_dimension_overwrite_warning(warning_catcher):
# AND a warning should be issued with the exact message
expected_warning = f"Dimension '{dimension_name}' has already been added. The previous value will be overwritten."
assert any(str(w) == expected_warning for w in warning_catcher)


@pytest.mark.parametrize("env_value", ["", "maybe"])
def test_is_metrics_disabled_empty_or_unparsable(monkeypatch: pytest.MonkeyPatch, env_value: str):
monkeypatch.setenv("POWERTOOLS_METRICS_DISABLED", env_value)
monkeypatch.delenv("POWERTOOLS_DEV", raising=False)

with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_METRICS_DISABLED has an unrecognised value"):
assert is_metrics_disabled() is False
25 changes: 25 additions & 0 deletions tests/unit/test_shared_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest
from pydantic import BaseModel

from aws_lambda_powertools import Logger
from aws_lambda_powertools.shared import constants
from aws_lambda_powertools.shared.functions import (
abs_lambda_path,
Expand All @@ -23,6 +24,7 @@
)
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
from aws_lambda_powertools.utilities.parameters.base import DEFAULT_MAX_AGE_SECS
from aws_lambda_powertools.warnings import PowertoolsUserWarning


@pytest.fixture
Expand Down Expand Up @@ -84,6 +86,29 @@ def test_powertools_debug_warning(monkeypatch: pytest.MonkeyPatch):
assert str(w[0].message) == warning_message


@pytest.mark.parametrize("env_value", ["", "maybe"])
def test_powertools_dev_empty_or_unparsable(monkeypatch: pytest.MonkeyPatch, env_value: str):
monkeypatch.setenv(constants.POWERTOOLS_DEV_ENV, env_value)

with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_DEV has an unrecognised value"):
assert powertools_dev_is_set() is False


@pytest.mark.parametrize("env_value", ["", "maybe"])
def test_powertools_debug_empty_or_unparsable(monkeypatch: pytest.MonkeyPatch, env_value: str):
monkeypatch.setenv(constants.POWERTOOLS_DEBUG_ENV, env_value)

with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_DEBUG has an unrecognised value"):
assert powertools_debug_is_set() is False


def test_logger_init_with_empty_powertools_dev(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv(constants.POWERTOOLS_DEV_ENV, "")

with pytest.warns(PowertoolsUserWarning, match="POWERTOOLS_DEV has an unrecognised value"):
Logger(service="svc")


def test_extract_event_dict():
data = {"hello": "world"}
assert extract_event_from_common_models(data) == data
Expand Down
Loading