From 2efa0ef3e9a4ee4d3b2c4a4e9bf4cdea0f49746f Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Sun, 20 Oct 2024 17:52:20 +0200 Subject: [PATCH] fix and test bug in config env loading --- reflex/config.py | 16 +++++++++++++--- tests/units/test_config.py | 9 ++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/reflex/config.py b/reflex/config.py index 719d5c21f..c638fc313 100644 --- a/reflex/config.py +++ b/reflex/config.py @@ -3,6 +3,7 @@ from __future__ import annotations import importlib +import inspect import os import sys import urllib.parse @@ -10,6 +11,7 @@ from pathlib import Path from typing import Any, Dict, List, Optional, Set, Union from reflex.utils.exceptions import ConfigError +from reflex.utils.types import is_optional, is_union try: import pydantic.v1 as pydantic @@ -299,15 +301,23 @@ class Config(Base): ) # Convert the env var to the expected type. + type_ = field.type_ + if is_optional(type_): + type_ = type_.__args__[0] or type_.__args__[1] + # TODO: This just handles the first type in a Union. Needs refactoring. + if is_union(type_): + type_ = type_.__args__[0] try: - if issubclass(field.type_, bool): + if type_ is bool or ( + inspect.isclass(type_) and issubclass(type_, bool) + ): # special handling for bool values env_var = env_var.lower() in ["true", "1", "yes"] else: - env_var = field.type_(env_var) + env_var = type_(env_var) except ValueError as ve: console.error( - f"Could not convert {key.upper()}={env_var} to type {field.type_}" + f"Could not convert {key.upper()}={env_var} to type {type_}" ) raise EnvVarValueError from ve diff --git a/tests/units/test_config.py b/tests/units/test_config.py index a6c6fe697..dc0216d06 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -1,5 +1,6 @@ import multiprocessing import os +from typing import Any, Dict import pytest @@ -28,6 +29,7 @@ def test_set_app_name(base_config_values): "env_var, value", [ ("APP_NAME", "my_test_app"), + ("BUN_PATH", "/test"), ("FRONTEND_PORT", 3001), ("FRONTEND_PATH", "/test"), ("BACKEND_PORT", 8001), @@ -41,7 +43,12 @@ def test_set_app_name(base_config_values): ("TELEMETRY_ENABLED", True), ], ) -def test_update_from_env(base_config_values, monkeypatch, env_var, value): +def test_update_from_env( + base_config_values: Dict[str, Any], + monkeypatch: pytest.MonkeyPatch, + env_var: str, + value: Any, +): """Test that environment variables override config values. Args: