Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
ydm committed Jan 28, 2025
1 parent 060757d commit a416e6f
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 8 deletions.
8 changes: 3 additions & 5 deletions src/ape/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class PluginConfig(BaseSettings):
a config API must register a subclass of this class.
"""

model_config = SettingsConfigDict(extra="allow", env_prefix="APE_API_")
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_")

@classmethod
def from_overrides(
Expand Down Expand Up @@ -198,8 +198,6 @@ class DeploymentConfig(PluginConfig):
(must be a contract in the project).
"""

model_config = SettingsConfigDict(extra="allow", env_prefix="APE_API_")


def _get_problem_with_config(errors: list, path: Path) -> Optional[str]:
# Attempt to find line numbers in the config matching.
Expand Down Expand Up @@ -287,7 +285,7 @@ class ApeConfig(ExtraAttributesMixin, BaseSettings, ManagerAccessMixin):

def __init__(self, *args, **kwargs):
project_path = kwargs.get("project")
super(BaseSettings, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
# NOTE: Cannot reference `self` at all until after super init.
self._project_path = project_path

Expand Down Expand Up @@ -352,7 +350,7 @@ def __init__(self, *args, **kwargs):
"""

# NOTE: Plugin configs are technically "extras".
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_API_")
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_")

@model_validator(mode="before")
@classmethod
Expand Down
10 changes: 10 additions & 0 deletions src/ape_compile/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python

print(__package__)
print(__name__)

import re

match: re.Match | None = re.search(r'/(ape_\w+)/', __file__)
envprefix: str = f'{match.group(1).upper()}_' if match else 'APE_'
print(envprefix)
77 changes: 74 additions & 3 deletions tests/functional/test_config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union
from typing import Any, Callable, TYPE_CHECKING, Optional, Type, Union

import pytest
from pydantic import ValidationError
Expand All @@ -10,9 +10,14 @@
from ape.api.config import ApeConfig, ConfigEnum, PluginConfig
from ape.exceptions import ConfigError
from ape.managers.config import CONFIG_FILE_NAME, merge_configs
from ape_console.config import ConsoleConfig
from ape_cache.config import CacheConfig
from ape_compile.config import Config as CompileConfig
from ape.utils.os import create_tempdir
from ape_ethereum.ecosystem import EthereumConfig, NetworkConfig
from ape_networks import CustomNetwork
from ape_ethereum.ecosystem import BaseEthereumConfig, EthereumConfig, NetworkConfig, ForkedNetworkConfig
from ape_node.provider import EthereumNetworkConfig, EthereumNodeConfig
from ape_networks.config import CustomNetwork
from ape_test.config import ApeTestConfig, CoverageConfig, CoverageReportsConfig, EthTesterProviderConfig, GasConfig, GasExclusion, IsolationConfig
from tests.functional.conftest import PROJECT_WITH_LONG_CONTRACTS_FOLDER

if TYPE_CHECKING:
Expand Down Expand Up @@ -618,3 +623,69 @@ def test_project_level_settings(project):
assert project.config.my_string == "my_string"
assert project.config.my_int == 123
assert project.config.my_bool is True


def test_model_validate_handles_environment_variables():
def f(cls: Callable, attr: str, name: str, value: str, expected: Any = None):
expected = expected if expected is not None else value
before: str | None = os.environ.get(name)
os.environ[name] = value
try:
instance = cls()
assert hasattr(instance, attr)
assert getattr(instance, attr) == expected
finally:
if before is not None:
os.environ[name] = before

# Test different config classes.
f(ApeConfig, "contracts_folder", "APE_CONTRACTS_FOLDER", "3465220869b2")
f(ApeConfig, "dependencies", "APE_DEPENDENCIES", '[{"a":1},{"b":2},{"c":3}]', [{"a": 1}, {"b": 2}, {"c": 3}])
f(CacheConfig, "size", "APE_CACHE_SIZE", "8627", 8627)
f(CompileConfig, "include_dependencies", "APE_COMPILE_INCLUDE_DEPENDENCIES", "true", True)
f(ConsoleConfig, "plugins", "APE_CONSOLE_PLUGINS", '["a","b","c"]', ["a", "b", "c"])
f(BaseEthereumConfig, "default_network", "APE_ETHEREUM_DEFAULT_NETWORK", "abe9e8293383")
f(ForkedNetworkConfig, "upstream_provider", "APE_ETHEREUM_UPSTREAM_PROVIDER", "411236f13659")
f(NetworkConfig, "required_confirmations", "APE_ETHEREUM_REQUIRED_CONFIRMATIONS", "6498", 6498)
f(lambda: CustomNetwork(name="", chain_id=0, ecosystem=""),
"base_ecosystem_plugin", "APE_NETWORKS_BASE_ECOSYSTEM_PLUGIN", "ea5010088102")
f(EthereumNetworkConfig, "mainnet", "APE_NODE_MAINNET", '{"a":"b"}', {"a":"b"})
f(EthereumNodeConfig, "executable", "APE_NODE_EXECUTABLE", "40613177e494")
f(ApeTestConfig, "balance", "APE_TEST_BALANCE", "4798", 4798)
f(CoverageConfig, "track", "APE_TEST_TRACK", "true", True)
f(CoverageReportsConfig, "terminal", "APE_TEST_TERMINAL", "false", False)
f(EthTesterProviderConfig, "chain_id", "APE_TEST_CHAIN_ID", "7925", 7925)
f(GasConfig, "reports", "APE_TEST_REPORTS", '["terminal"]', ["terminal"])
f(GasExclusion, "method_name", "APE_TEST_METHOD_NAME", "32aa54e3c5d2")
f(IsolationConfig, "enable_session", "APE_TEST_ENABLE_SESSION", "false", False)

# Assert that union types are handled.
f(NetworkConfig, "gas_limit", "APE_ETHEREUM_GAS_LIMIT", "0", 0)
f(NetworkConfig, "gas_limit", "APE_ETHEREUM_GAS_LIMIT", "0x100", 0x100)
f(NetworkConfig, "gas_limit", "APE_ETHEREUM_GAS_LIMIT", "auto")
f(NetworkConfig, "gas_limit", "APE_ETHEREUM_GAS_LIMIT", "max")
with pytest.raises(ValidationError, match=r"Value error, Invalid gas limit"):
f(NetworkConfig, "gas_limit", "APE_ETHEREUM_GAS_LIMIT", "something")

# Assert that various bool variants are parsed correctly.
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "0", False)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "False", False)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "fALSE", False)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "FALSE", False)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "1", True)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "True", True)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "tRUE", True)
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "TRUE", True)

# We expect a failure when there's a type mismatch.
with pytest.raises(
ValidationError,
match=r"Input should be a valid boolean, unable to interpret input",
):
f(NetworkConfig, "is_mainnet", "APE_ETHEREUM_IS_MAINNET", "not a boolean", False)

with pytest.raises(
ValidationError,
match=r"Input should be a valid integer, unable to parse string as an integer",
):
f(NetworkConfig, "required_confirmations", "APE_ETHEREUM_REQUIRED_CONFIRMATIONS", "not a number", 42)

0 comments on commit a416e6f

Please sign in to comment.