|
1 | 1 | """Expect section structure of ethereum/tests fillers.""" |
2 | 2 |
|
3 | | -from enum import Enum |
4 | | -from typing import Annotated, Any, Dict, List, Mapping, Union |
| 3 | +import re |
| 4 | +from enum import StrEnum |
| 5 | +from typing import Annotated, Any, Dict, Iterator, List, Mapping, Set, Union |
5 | 6 |
|
6 | 7 | from pydantic import ( |
7 | 8 | BaseModel, |
8 | 9 | BeforeValidator, |
9 | 10 | Field, |
10 | | - ValidationInfo, |
11 | 11 | ValidatorFunctionWrapHandler, |
12 | 12 | field_validator, |
13 | 13 | model_validator, |
|
22 | 22 | Storage, |
23 | 23 | ) |
24 | 24 | from ethereum_test_exceptions import TransactionExceptionInstanceOrList |
25 | | -from ethereum_test_forks import get_forks |
| 25 | +from ethereum_test_forks import Fork, get_forks |
26 | 26 | from ethereum_test_types import Alloc |
27 | 27 |
|
28 | 28 | from .common import ( |
@@ -86,6 +86,14 @@ def resolve(self, tags: TagDict) -> Storage: |
86 | 86 | storage[resolved_key] = value |
87 | 87 | return storage |
88 | 88 |
|
| 89 | + def __contains__(self, key: Address) -> bool: |
| 90 | + """Check if the storage contains a key.""" |
| 91 | + return key in self.root |
| 92 | + |
| 93 | + def __iter__(self) -> Iterator[ValueOrCreateTagInFiller]: # type: ignore[override] |
| 94 | + """Iterate over the storage.""" |
| 95 | + return iter(self.root) |
| 96 | + |
89 | 97 |
|
90 | 98 | class AccountInExpectSection(BaseModel, TagDependentData): |
91 | 99 | """Class that represents an account in expect section filler.""" |
@@ -127,66 +135,116 @@ def resolve(self, tags: TagDict) -> Account: |
127 | 135 | return Account(**account_kwargs) |
128 | 136 |
|
129 | 137 |
|
130 | | -class CMP(Enum): |
| 138 | +class CMP(StrEnum): |
131 | 139 | """Comparison action.""" |
132 | 140 |
|
133 | | - GT = 1 |
134 | | - LT = 2 |
135 | | - LE = 3 |
136 | | - GE = 4 |
137 | | - EQ = 5 |
138 | | - |
139 | | - |
140 | | -def parse_networks(fork_with_operand: str) -> List[str]: |
141 | | - """Parse fork_with_operand `>=Cancun` into [Cancun, Prague, ...].""" |
142 | | - parsed_forks: List[str] = [] |
143 | | - all_forks_by_name = [fork.name() for fork in get_forks()] |
144 | | - |
145 | | - action: CMP = CMP.EQ |
146 | | - fork: str = fork_with_operand |
147 | | - if fork_with_operand[:1] == "<": |
148 | | - action = CMP.LT |
149 | | - fork = fork_with_operand[1:] |
150 | | - if fork_with_operand[:1] == ">": |
151 | | - action = CMP.GT |
152 | | - fork = fork_with_operand[1:] |
153 | | - if fork_with_operand[:2] == "<=": |
154 | | - action = CMP.LE |
155 | | - fork = fork_with_operand[2:] |
156 | | - if fork_with_operand[:2] == ">=": |
157 | | - action = CMP.GE |
158 | | - fork = fork_with_operand[2:] |
159 | | - |
160 | | - if action == CMP.EQ: |
161 | | - fork = fork_with_operand |
162 | | - |
163 | | - # translate unsupported fork names |
164 | | - if fork == "EIP158": |
165 | | - fork = "Byzantium" |
166 | | - |
167 | | - if action == CMP.EQ: |
168 | | - parsed_forks.append(fork) |
169 | | - return parsed_forks |
170 | | - |
171 | | - try: |
172 | | - # print(all_forks_by_name) |
173 | | - idx = all_forks_by_name.index(fork) |
174 | | - # ['Frontier', 'Homestead', 'Byzantium', 'Constantinople', 'ConstantinopleFix', |
175 | | - # 'Istanbul', 'MuirGlacier', 'Berlin', 'London', 'ArrowGlacier', 'GrayGlacier', |
176 | | - # 'Paris', 'Shanghai', 'Cancun', 'Prague', 'Osaka'] |
177 | | - except ValueError: |
178 | | - raise ValueError(f"Unsupported fork: {fork}") from Exception |
179 | | - |
180 | | - if action == CMP.GE: |
181 | | - parsed_forks = all_forks_by_name[idx:] |
182 | | - elif action == CMP.GT: |
183 | | - parsed_forks = all_forks_by_name[idx + 1 :] |
184 | | - elif action == CMP.LE: |
185 | | - parsed_forks = all_forks_by_name[: idx + 1] |
186 | | - elif action == CMP.LT: |
187 | | - parsed_forks = all_forks_by_name[:idx] |
188 | | - |
189 | | - return parsed_forks |
| 141 | + LE = "<=" |
| 142 | + GE = ">=" |
| 143 | + LT = "<" |
| 144 | + GT = ">" |
| 145 | + EQ = "=" |
| 146 | + |
| 147 | + |
| 148 | +class ForkConstraint(BaseModel): |
| 149 | + """Single fork with an operand.""" |
| 150 | + |
| 151 | + operand: CMP |
| 152 | + fork: Fork |
| 153 | + |
| 154 | + @field_validator("fork", mode="before") |
| 155 | + @classmethod |
| 156 | + def parse_fork_synonyms(cls, value: Any): |
| 157 | + """Resolve fork synonyms.""" |
| 158 | + if value == "EIP158": |
| 159 | + value = "Byzantium" |
| 160 | + return value |
| 161 | + |
| 162 | + @model_validator(mode="before") |
| 163 | + @classmethod |
| 164 | + def parse_from_string(cls, data: Any) -> Any: |
| 165 | + """Parse a fork with operand from a string.""" |
| 166 | + if isinstance(data, str): |
| 167 | + for cmp in CMP: |
| 168 | + if data.startswith(cmp): |
| 169 | + fork = data.removeprefix(cmp) |
| 170 | + return { |
| 171 | + "operand": cmp, |
| 172 | + "fork": fork, |
| 173 | + } |
| 174 | + return { |
| 175 | + "operand": CMP.EQ, |
| 176 | + "fork": data, |
| 177 | + } |
| 178 | + return data |
| 179 | + |
| 180 | + def match(self, fork: Fork) -> bool: |
| 181 | + """Return whether the fork satisfies the operand evaluation.""" |
| 182 | + match self.operand: |
| 183 | + case CMP.LE: |
| 184 | + return fork <= self.fork |
| 185 | + case CMP.GE: |
| 186 | + return fork >= self.fork |
| 187 | + case CMP.LT: |
| 188 | + return fork < self.fork |
| 189 | + case CMP.GT: |
| 190 | + return fork > self.fork |
| 191 | + case CMP.EQ: |
| 192 | + return fork == self.fork |
| 193 | + case _: |
| 194 | + raise ValueError(f"Invalid operand: {self.operand}") |
| 195 | + |
| 196 | + |
| 197 | +class ForkSet(EthereumTestRootModel): |
| 198 | + """Set of forks.""" |
| 199 | + |
| 200 | + root: Set[Fork] |
| 201 | + |
| 202 | + @model_validator(mode="before") |
| 203 | + @classmethod |
| 204 | + def parse_from_list_or_string(cls, value: Any) -> Set[Fork]: |
| 205 | + """Parse fork_with_operand `>=Cancun` into {Cancun, Prague, ...}.""" |
| 206 | + fork_set: Set[Fork] = set() |
| 207 | + if not isinstance(value, list): |
| 208 | + value = [value] |
| 209 | + |
| 210 | + for fork_with_operand in value: |
| 211 | + matches = re.findall(r"(<=|<|>=|>|=)([^<>=]+)", fork_with_operand) |
| 212 | + if matches: |
| 213 | + all_fork_constraints = [ |
| 214 | + ForkConstraint.model_validate(f"{op}{fork.strip()}") for op, fork in matches |
| 215 | + ] |
| 216 | + else: |
| 217 | + all_fork_constraints = [ForkConstraint.model_validate(fork_with_operand.strip())] |
| 218 | + |
| 219 | + for fork in get_forks(): |
| 220 | + for f in all_fork_constraints: |
| 221 | + if not f.match(fork): |
| 222 | + # If any constraint does not match, skip adding |
| 223 | + break |
| 224 | + else: |
| 225 | + # All constraints match, add the fork to the set |
| 226 | + fork_set.add(fork) |
| 227 | + |
| 228 | + return fork_set |
| 229 | + |
| 230 | + def __hash__(self) -> int: |
| 231 | + """Return the hash of the fork set.""" |
| 232 | + h = hash(None) |
| 233 | + for fork in sorted([str(f) for f in self]): |
| 234 | + h ^= hash(fork) |
| 235 | + return h |
| 236 | + |
| 237 | + def __contains__(self, fork: Fork) -> bool: |
| 238 | + """Check if the fork set contains a fork.""" |
| 239 | + return fork in self.root |
| 240 | + |
| 241 | + def __iter__(self) -> Iterator[Fork]: # type: ignore[override] |
| 242 | + """Iterate over the fork set.""" |
| 243 | + return iter(self.root) |
| 244 | + |
| 245 | + def __len__(self) -> int: |
| 246 | + """Return the length of the fork set.""" |
| 247 | + return len(self.root) |
190 | 248 |
|
191 | 249 |
|
192 | 250 | class ResultInFiller(EthereumTestRootModel, TagDependentData): |
@@ -228,44 +286,61 @@ def resolve(self, tags: TagDict) -> Alloc: |
228 | 286 | post[resolved_address] = account.resolve(tags) |
229 | 287 | return post |
230 | 288 |
|
| 289 | + def __contains__(self, address: Address) -> bool: |
| 290 | + """Check if the result contains an address.""" |
| 291 | + return address in self.root |
| 292 | + |
| 293 | + def __iter__(self) -> Iterator[AddressOrCreateTagInFiller]: # type: ignore[override] |
| 294 | + """Iterate over the result.""" |
| 295 | + return iter(self.root) |
| 296 | + |
| 297 | + def __len__(self) -> int: |
| 298 | + """Return the length of the result.""" |
| 299 | + return len(self.root) |
| 300 | + |
| 301 | + |
| 302 | +class ExpectException(EthereumTestRootModel): |
| 303 | + """Expect exception model.""" |
| 304 | + |
| 305 | + root: Dict[ForkSet, TransactionExceptionInstanceOrList] |
| 306 | + |
| 307 | + def __getitem__(self, fork: Fork) -> TransactionExceptionInstanceOrList: |
| 308 | + """Get an expectation for a given fork.""" |
| 309 | + for k in self.root: |
| 310 | + if fork in k: |
| 311 | + return self.root[k] |
| 312 | + raise KeyError(f"Fork {fork} not found in expectations.") |
| 313 | + |
| 314 | + def __contains__(self, fork: Fork) -> bool: |
| 315 | + """Check if the expect exception contains a fork.""" |
| 316 | + return fork in self.root |
| 317 | + |
| 318 | + def __iter__(self) -> Iterator[ForkSet]: # type: ignore[override] |
| 319 | + """Iterate over the expect exception.""" |
| 320 | + return iter(self.root) |
| 321 | + |
| 322 | + def __len__(self) -> int: |
| 323 | + """Return the length of the expect exception.""" |
| 324 | + return len(self.root) |
| 325 | + |
231 | 326 |
|
232 | 327 | class ExpectSectionInStateTestFiller(CamelModel): |
233 | 328 | """Expect section in state test filler.""" |
234 | 329 |
|
235 | 330 | indexes: Indexes = Field(default_factory=Indexes) |
236 | | - network: List[str] |
| 331 | + network: ForkSet |
237 | 332 | result: ResultInFiller |
238 | | - expect_exception: Dict[str, TransactionExceptionInstanceOrList] | None = None |
239 | | - |
240 | | - @field_validator("network", mode="before") |
241 | | - @classmethod |
242 | | - def parse_networks(cls, network: List[str], info: ValidationInfo) -> List[str]: |
243 | | - """Parse networks into array of forks.""" |
244 | | - forks: List[str] = [] |
245 | | - for net in network: |
246 | | - forks.extend(parse_networks(net)) |
247 | | - return forks |
248 | | - |
249 | | - @field_validator("expect_exception", mode="before") |
250 | | - @classmethod |
251 | | - def parse_expect_exception( |
252 | | - cls, expect_exception: Dict[str, str] | None, info: ValidationInfo |
253 | | - ) -> Dict[str, str] | None: |
254 | | - """Parse operand networks in exceptions.""" |
255 | | - if expect_exception is None: |
256 | | - return expect_exception |
257 | | - |
258 | | - parsed_expect_exception: Dict[str, str] = {} |
259 | | - for fork_with_operand, exception in expect_exception.items(): |
260 | | - forks: List[str] = parse_networks(fork_with_operand) |
261 | | - for fork in forks: |
262 | | - if fork in parsed_expect_exception: |
263 | | - raise ValueError( |
264 | | - "Expect exception has redundant fork with multiple exceptions!" |
265 | | - ) |
266 | | - parsed_expect_exception[fork] = exception |
267 | | - |
268 | | - return parsed_expect_exception |
| 333 | + expect_exception: ExpectException | None = None |
| 334 | + |
| 335 | + def model_post_init(self, __context): |
| 336 | + """Validate that the expectation is coherent.""" |
| 337 | + if self.expect_exception is None: |
| 338 | + return |
| 339 | + all_forks: Set[Fork] = set() |
| 340 | + for current_fork_set in self.expect_exception: |
| 341 | + for fork in current_fork_set: |
| 342 | + assert fork not in all_forks |
| 343 | + all_forks.add(fork) |
269 | 344 |
|
270 | 345 | def has_index(self, d: int, g: int, v: int) -> bool: |
271 | 346 | """Check if there is index set in indexes.""" |
|
0 commit comments