Skip to content

Commit

Permalink
refactor: move ape-test cfg to config module (#2338)
Browse files Browse the repository at this point in the history
  • Loading branch information
antazoey authored Oct 23, 2024
1 parent a257cac commit c2203f5
Show file tree
Hide file tree
Showing 3 changed files with 178 additions and 170 deletions.
171 changes: 8 additions & 163 deletions src/ape_test/__init__.py
Original file line number Diff line number Diff line change
@@ -1,170 +1,15 @@
from typing import NewType, Optional, Union

from pydantic import NonNegativeInt, field_validator

from ape import plugins
from ape.api.config import PluginConfig
from ape.utils.basemodel import ManagerAccessMixin
from ape.utils.testing import (
DEFAULT_NUMBER_OF_TEST_ACCOUNTS,
DEFAULT_TEST_ACCOUNT_BALANCE,
DEFAULT_TEST_HD_PATH,
DEFAULT_TEST_MNEMONIC,
)
from ape_test.accounts import TestAccount, TestAccountContainer
from ape_test.config import (
ApeTestConfig,
CoverageConfig,
CoverageReportsConfig,
GasConfig,
GasExclusion,
)
from ape_test.provider import EthTesterProviderConfig, LocalProvider


class GasExclusion(PluginConfig):
contract_name: str = "*" # If only given method, searches across all contracts.
method_name: Optional[str] = None # By default, match all methods in a contract


CoverageExclusion = NewType("CoverageExclusion", GasExclusion)


class GasConfig(PluginConfig):
"""
Configuration related to test gas reports.
"""

exclude: list[GasExclusion] = []
"""
Contract methods patterns to skip. Specify ``contract_name:`` and not
``method_name:`` to skip all methods in the contract. Only specify
``method_name:`` to skip all methods across all contracts. Specify
both to skip methods in a certain contracts. Entries use glob-rules;
use ``prefix_*`` to skip all items with a certain prefix.
"""

reports: list[str] = []
"""
Report-types to use. Currently, only supports `terminal`.
"""

@field_validator("reports", mode="before")
@classmethod
def validate_reports(cls, values):
values = list(set(values or []))
valid = ("terminal",)
for val in values:
if val not in valid:
valid_str = ", ".join(valid)
raise ValueError(f"Invalid gas-report format '{val}'. Valid: {valid_str}")

return values

@property
def show(self) -> bool:
return "terminal" in self.reports


_ReportType = Union[bool, dict]
"""Dict is for extra report settings."""


class CoverageReportsConfig(PluginConfig):
"""
Enable reports.
"""

terminal: _ReportType = True
"""
Set to ``False`` to hide the terminal coverage report.
"""

xml: _ReportType = False
"""
Set to ``True`` to generate an XML coverage report in your .build folder.
"""

html: _ReportType = False
"""
Set to ``True`` to generate HTML coverage reports.
"""

@property
def has_any(self) -> bool:
return any(x not in ({}, None, False) for x in (self.html, self.terminal, self.xml))


class CoverageConfig(PluginConfig):
"""
Configuration related to contract coverage.
"""

track: bool = False
"""
Setting this to ``True`` is the same as always running with
the ``--coverage`` flag.
"""

reports: CoverageReportsConfig = CoverageReportsConfig()
"""
Enable reports.
"""

exclude: list[CoverageExclusion] = []
"""
Contract methods patterns to skip. Specify ``contract_name:`` and not
``method_name:`` to skip all methods in the contract. Only specify
``method_name:`` to skip all methods across all contracts. Specify
both to skip methods in a certain contracts. Entries use glob-rules;
use ``prefix_*`` to skip all items with a certain prefix.
"""


class ApeTestConfig(PluginConfig):
balance: int = DEFAULT_TEST_ACCOUNT_BALANCE
"""
The starting-balance of every test account in Wei (NOT Ether).
"""

coverage: CoverageConfig = CoverageConfig()
"""
Configuration related to coverage reporting.
"""

disconnect_providers_after: bool = True
"""
Set to ``False`` to keep providers connected at the end of the test run.
"""

gas: GasConfig = GasConfig()
"""
Configuration related to gas reporting.
"""

hd_path: str = DEFAULT_TEST_HD_PATH
"""
The hd_path to use when generating the test accounts.
"""

mnemonic: str = DEFAULT_TEST_MNEMONIC
"""
The mnemonic to use when generating the test accounts.
"""

number_of_accounts: NonNegativeInt = DEFAULT_NUMBER_OF_TEST_ACCOUNTS
"""
The number of test accounts to generate in the provider.
"""

provider: EthTesterProviderConfig = EthTesterProviderConfig()
"""
Settings for the provider.
"""

@field_validator("balance", mode="before")
@classmethod
def validate_balance(cls, value):
return (
value
if isinstance(value, int)
else ManagerAccessMixin.conversion_manager.convert(value, int)
)


@plugins.register(plugins.Config)
def config_class():
return ApeTestConfig
Expand All @@ -185,8 +30,8 @@ def providers():
"TestAccount",
"EthTesterProviderConfig",
"LocalProvider",
"GasExclusion",
"GasConfig",
"GasExclusion",
"CoverageReportsConfig",
"CoverageConfig",
"ApeTestConfig",
Expand Down
168 changes: 168 additions & 0 deletions src/ape_test/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
from typing import NewType, Optional, Union

from pydantic import NonNegativeInt, field_validator

from ape.api.config import PluginConfig
from ape.utils.basemodel import ManagerAccessMixin
from ape.utils.testing import (
DEFAULT_NUMBER_OF_TEST_ACCOUNTS,
DEFAULT_TEST_ACCOUNT_BALANCE,
DEFAULT_TEST_CHAIN_ID,
DEFAULT_TEST_HD_PATH,
DEFAULT_TEST_MNEMONIC,
)


class EthTesterProviderConfig(PluginConfig):
chain_id: int = DEFAULT_TEST_CHAIN_ID
auto_mine: bool = True


class GasExclusion(PluginConfig):
contract_name: str = "*" # If only given method, searches across all contracts.
method_name: Optional[str] = None # By default, match all methods in a contract


CoverageExclusion = NewType("CoverageExclusion", GasExclusion)


class GasConfig(PluginConfig):
"""
Configuration related to test gas reports.
"""

exclude: list[GasExclusion] = []
"""
Contract methods patterns to skip. Specify ``contract_name:`` and not
``method_name:`` to skip all methods in the contract. Only specify
``method_name:`` to skip all methods across all contracts. Specify
both to skip methods in a certain contracts. Entries use glob-rules;
use ``prefix_*`` to skip all items with a certain prefix.
"""

reports: list[str] = []
"""
Report-types to use. Currently, only supports `terminal`.
"""

@field_validator("reports", mode="before")
@classmethod
def validate_reports(cls, values):
values = list(set(values or []))
valid = ("terminal",)
for val in values:
if val not in valid:
valid_str = ", ".join(valid)
raise ValueError(f"Invalid gas-report format '{val}'. Valid: {valid_str}")

return values

@property
def show(self) -> bool:
return "terminal" in self.reports


_ReportType = Union[bool, dict]
"""Dict is for extra report settings."""


class CoverageReportsConfig(PluginConfig):
"""
Enable reports.
"""

terminal: _ReportType = True
"""
Set to ``False`` to hide the terminal coverage report.
"""

xml: _ReportType = False
"""
Set to ``True`` to generate an XML coverage report in your .build folder.
"""

html: _ReportType = False
"""
Set to ``True`` to generate HTML coverage reports.
"""

@property
def has_any(self) -> bool:
return any(x not in ({}, None, False) for x in (self.html, self.terminal, self.xml))


class CoverageConfig(PluginConfig):
"""
Configuration related to contract coverage.
"""

track: bool = False
"""
Setting this to ``True`` is the same as always running with
the ``--coverage`` flag.
"""

reports: CoverageReportsConfig = CoverageReportsConfig()
"""
Enable reports.
"""

exclude: list[CoverageExclusion] = []
"""
Contract methods patterns to skip. Specify ``contract_name:`` and not
``method_name:`` to skip all methods in the contract. Only specify
``method_name:`` to skip all methods across all contracts. Specify
both to skip methods in a certain contracts. Entries use glob-rules;
use ``prefix_*`` to skip all items with a certain prefix.
"""


class ApeTestConfig(PluginConfig):
balance: int = DEFAULT_TEST_ACCOUNT_BALANCE
"""
The starting-balance of every test account in Wei (NOT Ether).
"""

coverage: CoverageConfig = CoverageConfig()
"""
Configuration related to coverage reporting.
"""

disconnect_providers_after: bool = True
"""
Set to ``False`` to keep providers connected at the end of the test run.
"""

gas: GasConfig = GasConfig()
"""
Configuration related to gas reporting.
"""

hd_path: str = DEFAULT_TEST_HD_PATH
"""
The hd_path to use when generating the test accounts.
"""

mnemonic: str = DEFAULT_TEST_MNEMONIC
"""
The mnemonic to use when generating the test accounts.
"""

number_of_accounts: NonNegativeInt = DEFAULT_NUMBER_OF_TEST_ACCOUNTS
"""
The number of test accounts to generate in the provider.
"""

provider: EthTesterProviderConfig = EthTesterProviderConfig()
"""
Settings for the provider.
"""

@field_validator("balance", mode="before")
@classmethod
def validate_balance(cls, value):
return (
value
if isinstance(value, int)
else ManagerAccessMixin.conversion_manager.convert(value, int)
)
9 changes: 2 additions & 7 deletions src/ape_test/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from web3.providers.eth_tester.defaults import API_ENDPOINTS, static_return
from web3.types import TxParams

from ape.api.config import PluginConfig
from ape.api.providers import BlockAPI, TestProviderAPI
from ape.api.trace import TraceAPI
from ape.api.transactions import ReceiptAPI, TransactionAPI
Expand All @@ -35,19 +34,15 @@
from ape.types.events import ContractLog, LogFilter
from ape.types.vm import BlockID, SnapshotID
from ape.utils.misc import gas_estimation_error_message
from ape.utils.testing import DEFAULT_TEST_CHAIN_ID, DEFAULT_TEST_HD_PATH
from ape.utils.testing import DEFAULT_TEST_HD_PATH
from ape_ethereum.provider import Web3Provider
from ape_ethereum.trace import TraceApproach, TransactionTrace
from ape_test.config import EthTesterProviderConfig

if TYPE_CHECKING:
from ape.api.accounts import TestAccountAPI


class EthTesterProviderConfig(PluginConfig):
chain_id: int = DEFAULT_TEST_CHAIN_ID
auto_mine: bool = True


class LocalProvider(TestProviderAPI, Web3Provider):
_evm_backend: Optional[PyEVMBackend] = None
_CANNOT_AFFORD_GAS_PATTERN: Pattern = re.compile(
Expand Down

0 comments on commit c2203f5

Please sign in to comment.